diff options
Diffstat (limited to 'components')
61 files changed, 4588 insertions, 0 deletions
diff --git a/components/kpi-computation-ms/pom.xml b/components/kpi-computation-ms/pom.xml new file mode 100644 index 00000000..58758a2e --- /dev/null +++ b/components/kpi-computation-ms/pom.xml @@ -0,0 +1,358 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ ============LICENSE_START======================================================= + ~ Copyright (c) 2021 China Mobile. 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========================================================= + --> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.oparent</groupId> + <artifactId>oparent</artifactId> + <version>2.0.0</version> + </parent> + + <groupId>org.onap.dcaegen2.services.components</groupId> + <artifactId>kpi-ms</artifactId> + <version>1.0.0-SNAPSHOT</version> + <name>dcaegen2-services-kpi-computation-ms</name> + <description>Kpi ms</description> + <packaging>jar</packaging> + + <properties> + <java.version>11</java.version> + <sdk.version>1.5.0</sdk.version> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <maven.compiler.source>11</maven.compiler.source> + <maven.compiler.target>11</maven.compiler.target> + <docker.image.name>onap/${project.groupId}.${project.artifactId}</docker.image.name> + <!-- NEXUS RELATED SETTINGS --> + <nexusproxy>https://nexus.onap.org</nexusproxy> + <snapshots.path>content/repositories/snapshots/</snapshots.path> + <releases.path>content/repositories/releases/</releases.path> + <site.path>content/sites/site/org/onap/dcaegen2/services/${project.artifactId}/${project.version}</site.path> + <maven.build.timestamp.format>yyyyMMdd'T'HHmmss</maven.build.timestamp.format> + <sonar.coverage.jacoco.xmlReportPaths> + ${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml + </sonar.coverage.jacoco.xmlReportPaths> + <lombok.version>1.18.4</lombok.version> + <undertow.version>2.0.30.Final</undertow.version> + <xml.version>2.3.1</xml.version> + <jaxb.version>2.3.0.1</jaxb.version> + <docker.repository>nexus3.onap.org:10001</docker.repository> + <spring.version>5.2.7.RELEASE</spring.version> + <junit.version>5.3.2</junit.version> + <mockito.version>2.23.4</mockito.version> + <mockito-ju5-ext.version>2.23.4</mockito-ju5-ext.version> + <powermock.version>2.0.7</powermock.version> + <mockserver.version>3.10.8</mockserver.version> + <junit4.version>4.12</junit4.version> + </properties> + + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-autoconfigure</artifactId> + <version>2.3.1.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-webmvc</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-core</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-beans</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-expression</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-web</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-context</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-tx</artifactId> + <version>5.2.7.RELEASE</version> + </dependency> + <!-- cbs client --> + <dependency> + <groupId>org.onap.dcaegen2.services.sdk.rest.services</groupId> + <artifactId>cbs-client</artifactId> + <version>${sdk.version}</version> + </dependency> + + <dependency> + <groupId>org.onap.dcaegen2.services.sdk.security.crypt</groupId> + <artifactId>crypt-password</artifactId> + <version>${sdk.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-dependencies</artifactId> + <version>2.1.3.RELEASE</version> + <type>pom</type> + <scope>import</scope> + </dependency> + <dependency> + <groupId>com.att.nsa</groupId> + <artifactId>cambriaClient</artifactId> + <version>0.0.1</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-core</artifactId> + <version>2.11.0</version> + </dependency> + <dependency> + <groupId>net.javacrumbs.json-unit</groupId> + <artifactId>json-unit-assertj</artifactId> + <version>2.14.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + <version>2.11.0</version> + </dependency> + <dependency> + <groupId>javax.json</groupId> + <artifactId>javax.json-api</artifactId> + <version>1.1.2</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + <version>2.2.0.RELEASE</version> + <exclusions> + <exclusion> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-tomcat</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.functionaljava</groupId> + <artifactId>functionaljava</artifactId> + <version>3.0</version> + </dependency> + + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.7</version> + </dependency> + + <dependency> + <groupId>org.eclipse.jetty</groupId> + <artifactId>jetty-server</artifactId> + <version>9.4.17.v20190418</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <version>2.3.0</version> + </dependency> + <dependency> + <groupId>org.javassist</groupId> + <artifactId>javassist</artifactId> + <version>3.24.1-GA</version> + </dependency> + <dependency> + <groupId>org.json</groupId> + <artifactId>json</artifactId> + <version>20190722</version> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>${lombok.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>io.undertow</groupId> + <artifactId>undertow-core</artifactId> + <version>${undertow.version}</version> + </dependency> + <dependency> + <groupId>io.undertow</groupId> + <artifactId>undertow-servlet</artifactId> + <version>${undertow.version}</version> + </dependency> + <dependency> + <groupId>commons-lang</groupId> + <artifactId>commons-lang</artifactId> + <version>2.6</version> + </dependency> + <dependency> + <groupId>javax.xml.bind</groupId> + <artifactId>jaxb-api</artifactId> + <version>${xml.version}</version> + </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-core</artifactId> + <version>${jaxb.version}</version> + </dependency> + <dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-impl</artifactId> + <version>${xml.version}</version> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>3.7</version> + </dependency> + + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-engine</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-junit-jupiter</artifactId> + <version>${mockito-ju5-ext.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>${mockito.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>${powermock.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.junit.vintage</groupId> + <artifactId>junit-vintage-engine</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito2</artifactId> + <version>${powermock.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.junit.jupiter</groupId> + <artifactId>junit-jupiter-params</artifactId> + <version>${junit.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <version>2.1.3.RELEASE</version> + <scope>test</scope> + </dependency> + <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core --> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.openpojo</groupId> + <artifactId>openpojo</artifactId> + <version>0.8.10</version> + </dependency> + </dependencies> + + <build> + <plugins> + + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <version>2.3.1.RELEASE</version> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>com.spotify</groupId> + <artifactId>docker-maven-plugin</artifactId> + <version>1.2.2</version> + <configuration> + <serverId>${docker.repository}</serverId> + <imageName>${docker.repository}/${docker.image.name}</imageName> + <imageTags> + <imageTag>${project.version}-${maven.build.timestamp}Z</imageTag> + <imageTag>${project.version}</imageTag> + <imageTag>latest</imageTag> + </imageTags> + <baseImage>onap/integration-java11:8.0.0</baseImage> + <user>onap</user> + <resources> + <resource> + <targetPath>/home/onap</targetPath> + <directory>${project.build.directory}</directory> + <include>${project.artifactId}-${project.version}.jar</include> + </resource> + <resource> + <targetPath>/app</targetPath> + <directory>${project.basedir}</directory> + <include>entry.sh</include> + </resource> + </resources> + + <runs> + <!-- Maven is loosing file permissions during artifacts copy --> + <run>export trustpass=`cat /opt/app/kpims/etc/cert/trust.pass`</run> + <run>mv /home/onap/*.jar /app/app.jar</run> + </runs> + <exposes> + <expose>8080</expose> + </exposes> + <entryPoint>exec java -Djavax.net.ssl.trustStore=/opt/app/kpims/etc/cert/trust.jks -Djavax.net.ssl.trustStorePassword=$trustpass -jar /app/app.jar</entryPoint> + </configuration> + </plugin> + </plugins> + </build> + +</project> + diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/Application.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/Application.java new file mode 100644 index 00000000..b2d3446e --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/Application.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.time.Duration; + +import org.onap.dcaegen2.kpi.controller.ConfigFetchFromCbs; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.scheduling.annotation.EnableScheduling; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +/** + * Entry point for the kpi computation service application. + * + * @author Kai Lu + * + */ +@EnableScheduling +@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class }) +public class Application { + + private static Logger log = LoggerFactory.getLogger(Application.class); + + /** + * Main method where initial configuration and context is set. + * + * @param args args + */ + public static void main(String[] args) { + Boolean standalone = Boolean.parseBoolean(System.getenv("STANDALONE")); + + if (standalone) { + String configFile = System.getenv("CONFIG_FILE"); + getStandaloneConfig(configFile); + + } else { + getConfig(); + } + + log.info("Starting spring boot application"); + SpringApplication.run(Application.class, args); + } + + /** + * Get Configuration from config file. + * + * @param configFile : location of the config file. + */ + public static void getStandaloneConfig(String configFile) { + + log.info("Running in standalone mode"); + + String configAllJson = readFromFile(configFile); + + JsonObject configAll = new Gson().fromJson(configAllJson, JsonObject.class); + + JsonObject config = configAll.getAsJsonObject("config"); + + Configuration.getInstance().updateConfigurationFromJsonObject(config); + + return; + } + + /** + * Get config from cbs. + * + */ + public static void getConfig() { + + ConfigFetchFromCbs configFetchFromCbs = new ConfigFetchFromCbs(Duration.ofSeconds(60)); + Thread configFetchThread = new Thread(configFetchFromCbs); + configFetchThread.start(); + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + log.debug("InterruptedException : {}", e); + Thread.currentThread().interrupt(); + } + log.info("after 10s sleep"); + } + + private static String readFromFile(String file) { + String content = ""; + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + content = bufferedReader.readLine(); + String temp; + while ((temp = bufferedReader.readLine()) != null) { + content = content.concat(temp); + } + content = content.trim(); + } catch (Exception e) { + content = null; + } + return content; + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/Command.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/Command.java new file mode 100644 index 00000000..90f1661d --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/Command.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +import org.onap.dcaegen2.kpi.config.ControlLoopSchemaType; +import org.onap.dcaegen2.kpi.models.PerformanceEvent; +import org.onap.dcaegen2.kpi.models.VesEvent; + +/** + * Command Type. + * + * @author Kai Lu + * + */ +@FunctionalInterface +public interface Command { + + /** + * Command Interface. + * + * @param pmEvent PerformanceEvent + * @param schemaType schemaType + * @param measInfoMap measInfoMap + * @param measType measType + * + * @return object + */ + VesEvent handle(PerformanceEvent pmEvent, ControlLoopSchemaType schemaType, + Map<String, List<BigDecimal>> measInfoMap, String measType); +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/CommandHandler.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/CommandHandler.java new file mode 100644 index 00000000..5934a2e0 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/CommandHandler.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +import org.onap.dcaegen2.kpi.config.ControlLoopSchemaType; +import org.onap.dcaegen2.kpi.models.PerformanceEvent; +import org.onap.dcaegen2.kpi.models.VesEvent; + +/** + * Get special methods to do computation. + * + * @author Kai Lu + * + */ +public class CommandHandler { + + /** + * The method to handle data. + * + * @param className class name + * @param pmEvent pmEvent + * @param schemaType schemaType + * @param measInfoMap measInfoMap + * @param measType measType + * @return VesEvent VesEvent + */ + public static VesEvent handle(String className, PerformanceEvent pmEvent, ControlLoopSchemaType schemaType, + Map<String, List<BigDecimal>> measInfoMap, String measType) { + + try { + // Load Command Object + Command command = (Command) Class.forName(className).getDeclaredConstructor().newInstance(); + return command.handle(pmEvent, schemaType, measInfoMap, measType); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/KpiComputation.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/KpiComputation.java new file mode 100644 index 00000000..e039b519 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/KpiComputation.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.lang.StringUtils; +import org.onap.dcaegen2.kpi.config.ControlLoopSchemaType; +import org.onap.dcaegen2.kpi.config.Kpi; +import org.onap.dcaegen2.kpi.config.KpiConfig; +import org.onap.dcaegen2.kpi.config.KpiJsonConversion; +import org.onap.dcaegen2.kpi.config.MethodForKpi; +import org.onap.dcaegen2.kpi.config.Operation; +import org.onap.dcaegen2.kpi.exception.KpiComputationException; +import org.onap.dcaegen2.kpi.models.CommonEventHeader; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.kpi.models.MeasDataCollection; +import org.onap.dcaegen2.kpi.models.MeasInfo; +import org.onap.dcaegen2.kpi.models.MeasResult; +import org.onap.dcaegen2.kpi.models.MeasValues; +import org.onap.dcaegen2.kpi.models.Perf3gppFields; +import org.onap.dcaegen2.kpi.models.PerformanceEvent; +import org.onap.dcaegen2.kpi.models.VesEvent; +import org.onap.dcaegen2.kpi.utils.VesJsonConversion; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * KPI computation. + * + * @author Kai Lu + */ +public class KpiComputation { + + private static Logger logger = LoggerFactory.getLogger(KpiComputation.class); + + /** + * do KPI computation. + * + * @param ves ves + * @param config config + * @return Kpi ves list + * + */ + public List<VesEvent> checkAndDoComputation(String ves, Configuration config) { + + if (ves == null || ves.equalsIgnoreCase("{}")) { + return null; + } + + KpiConfig kpiConfig = KpiJsonConversion.convertKpiConfig(config.getKpiConfig()); + if (kpiConfig == null) { + logger.info("No kpi config."); + return null; + } + + logger.info("kpi config. {}", kpiConfig); + VesEvent vesEvent = VesJsonConversion.convertVesEvent(ves); + // Get event Name + PerformanceEvent pmEvent = vesEvent.getEvent(); + String eventName = Optional.of(pmEvent).map(PerformanceEvent::getCommonEventHeader) + .map(CommonEventHeader::getEventName) + .orElseThrow(() -> new KpiComputationException("Required Field: EventName not present")); + + // Get Kpi's config per event name matching event name + MethodForKpi methodForKpi = kpiConfig.getMethodForKpi().stream() + .filter(m -> m.getEventName().equalsIgnoreCase(eventName)).findFirst().orElse(null); + // if ves event not exist + if (methodForKpi == null) { + logger.info("No event name matched."); + return null; + } + + MeasDataCollection measDataCollection = Optional.of(pmEvent).map(PerformanceEvent::getPerf3gppFields) + .map(Perf3gppFields::getMeasDataCollection) + .orElseThrow(() -> new KpiComputationException("Required Field: MeasData not present")); + // Do computation for each KPI + List<VesEvent> events = new ArrayList<>(); + List<Kpi> kpis = methodForKpi.getKpis(); + kpis.forEach(k -> { + Map<String, List<BigDecimal>> measInfoMap = getOperands(measDataCollection, k.getOperands()); + if (measInfoMap == null) { + logger.info("No kpi need to do computation for {}", k.getOperands()); + return; + } + + ControlLoopSchemaType schemaType = methodForKpi.getControlLoopSchemaType(); + String measType = k.getMeasType(); + Operation operation = k.getOperation(); + + VesEvent kpiVesEvent = CommandHandler.handle(operation.value, pmEvent, schemaType, measInfoMap, measType); + events.add(kpiVesEvent); + }); + return events; + } + + private Map<String, List<BigDecimal>> getOperands(MeasDataCollection measDataCollection, String operands) { + List<BigDecimal> kpiOperands = new ArrayList<>(); + List<MeasInfo> measInfoList = measDataCollection.getMeasInfoList(); + String[] key = new String[1]; + measInfoList.forEach(m -> { + List<String> measTypesList = m.getMeasTypes().getMeasTypesList(); + String measValue = measTypesList.stream() + .filter(s -> StringUtils.substring(s, 0, operands.length()).equalsIgnoreCase(operands)).findFirst() + .orElse(null); + if (measValue != null) { + key[0] = measValue.substring(operands.length() + 1); + int index = measTypesList.indexOf(measValue); + MeasValues measValues = m.getMeasValuesList().stream().findFirst().orElse(null); + List<MeasResult> measResults = measValues.getMeasResults(); + kpiOperands.add(new BigDecimal(measResults.get(index).getSvalue())); + } + }); + if (kpiOperands.size() <= 0) { + logger.info("No measureValues matched"); + return null; + } + Map<String, List<BigDecimal>> measInfoMap = new HashMap<>(); + measInfoMap.put(key[0], kpiOperands); + logger.info("kpi operate: {}", kpiOperands); + return measInfoMap; + } +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/SumKpiComputation.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/SumKpiComputation.java new file mode 100644 index 00000000..0fe1c4b6 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/computation/SumKpiComputation.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.onap.dcaegen2.kpi.config.ControlLoopSchemaType; +import org.onap.dcaegen2.kpi.models.CommonEventHeader; +import org.onap.dcaegen2.kpi.models.MeasDataCollection; +import org.onap.dcaegen2.kpi.models.MeasInfo; +import org.onap.dcaegen2.kpi.models.MeasInfoId; +import org.onap.dcaegen2.kpi.models.MeasResult; +import org.onap.dcaegen2.kpi.models.MeasTypes; +import org.onap.dcaegen2.kpi.models.MeasValues; +import org.onap.dcaegen2.kpi.models.Perf3gppFields; +import org.onap.dcaegen2.kpi.models.PerformanceEvent; +import org.onap.dcaegen2.kpi.models.VesEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SumKpiComputation. + * + * @author Kai Lu + */ +public class SumKpiComputation implements Command { + + private static Logger logger = LoggerFactory.getLogger(SumKpiComputation.class); + + @Override + public VesEvent handle(PerformanceEvent pmEvent, ControlLoopSchemaType schemaType, + Map<String, List<BigDecimal>> measInfoMap, String measType) { + + return generateSumVesEvent(pmEvent, schemaType, measInfoMap, measType); + } + + private VesEvent generateSumVesEvent(PerformanceEvent pmEvent, ControlLoopSchemaType schemaType, + Map<String, List<BigDecimal>> measInfoMap, String measType) { + + // Create ves kpi data + CommonEventHeader commonEventHeader = new CommonEventHeader(); + commonEventHeader.setDomain(pmEvent.getCommonEventHeader().getDomain()); + commonEventHeader.setEventId(UUID.randomUUID().toString()); + commonEventHeader.setSequence(0); + commonEventHeader.setEventName(pmEvent.getCommonEventHeader().getEventName()); + commonEventHeader.setSourceName(pmEvent.getCommonEventHeader().getSourceName()); + commonEventHeader.setReportingEntityName(pmEvent.getCommonEventHeader().getReportingEntityName()); + commonEventHeader.setPriority(pmEvent.getCommonEventHeader().getPriority()); + commonEventHeader.setStartEpochMicrosec(pmEvent.getCommonEventHeader().getStartEpochMicrosec()); + commonEventHeader.setLastEpochMicrosec(pmEvent.getCommonEventHeader().getLastEpochMicrosec()); + commonEventHeader.setVersion(pmEvent.getCommonEventHeader().getVersion()); + commonEventHeader.setVesEventListenerVersion(pmEvent.getCommonEventHeader().getVesEventListenerVersion()); + commonEventHeader.setTimeZoneOffset(pmEvent.getCommonEventHeader().getTimeZoneOffset()); + Perf3gppFields perf3gppFields = new Perf3gppFields(); + perf3gppFields.setPerf3gppFieldsVersion(pmEvent.getPerf3gppFields().getPerf3gppFieldsVersion()); + MeasDataCollection tmpMeasDataCollection = new MeasDataCollection(); + tmpMeasDataCollection + .setGranularityPeriod(pmEvent.getPerf3gppFields().getMeasDataCollection().getGranularityPeriod()); + tmpMeasDataCollection.setMeasuredEntityUserName( + pmEvent.getPerf3gppFields().getMeasDataCollection().getMeasuredEntityUserName()); + tmpMeasDataCollection + .setMeasuredEntityDn(pmEvent.getPerf3gppFields().getMeasDataCollection().getMeasuredEntityDn()); + tmpMeasDataCollection.setMeasuredEntitySoftwareVersion( + pmEvent.getPerf3gppFields().getMeasDataCollection().getMeasuredEntitySoftwareVersion()); + MeasInfoId measInfoId = new MeasInfoId(); + measInfoId.setMeasInfoId(schemaType.toString()); + MeasTypes measTypes = new MeasTypes(); + List<String> measTypesList = new ArrayList<>(); + String keyOperands = measInfoMap.keySet().stream().findAny().get(); + measTypesList.add(new StringBuilder().append(measType).append(keyOperands).toString()); + measTypes.setMeasTypesList(measTypesList); + MeasValues measValue = new MeasValues(); + measValue.setSuspectFlag(false); + List<MeasResult> measResults = new ArrayList<>(); + MeasResult measureMent = new MeasResult(); + List<BigDecimal> kpiOperands = measInfoMap.values().stream().findAny().get(); + BigDecimal result = kpiOperands.stream().map(i -> i).reduce(BigDecimal.ZERO, BigDecimal::add); + + measureMent.setPvalue(1); + measureMent.setSvalue(result.toString()); + measResults.add(measureMent); + MeasInfo measInfo = new MeasInfo(); + measValue.setMeasResults(measResults); + List<MeasValues> measValuesList = new ArrayList<>(); + measValuesList.add(measValue); + measInfo.setMeasInfoId(measInfoId); + measInfo.setMeasTypes(measTypes); + measInfo.setMeasValuesList(measValuesList); + List<MeasInfo> measInfoList = new ArrayList<>(); + measInfoList.add(measInfo); + tmpMeasDataCollection.setMeasInfoList(measInfoList); + perf3gppFields.setMeasDataCollection(tmpMeasDataCollection); + VesEvent kpiVesEvent = new VesEvent(); + PerformanceEvent kpiEvent = new PerformanceEvent(); + kpiEvent.setCommonEventHeader(commonEventHeader); + kpiEvent.setPerf3gppFields(perf3gppFields); + kpiVesEvent.setEvent(kpiEvent); + logger.info("kpiVesEvent: {}", kpiVesEvent); + return kpiVesEvent; + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/BaseDynamicPropertiesProvider.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/BaseDynamicPropertiesProvider.java new file mode 100644 index 00000000..b3e8d02d --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/BaseDynamicPropertiesProvider.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +import lombok.Data; + +/** + * BaseDynamicPropertiesProvider. + * + * @author Kai Lu + * + */ +@Data +public class BaseDynamicPropertiesProvider implements DynamicPropertiesProvider { + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/BaseModule.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/BaseModule.java new file mode 100644 index 00000000..8b955ec8 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/BaseModule.java @@ -0,0 +1,35 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.config; + +/** + * BaseModule. + * + * @author Kai Lu + * + */ +public abstract class BaseModule extends BaseDynamicPropertiesProvider { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/ControlLoopSchemaType.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/ControlLoopSchemaType.java new file mode 100644 index 00000000..e36d4cce --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/ControlLoopSchemaType.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +/** + * Control Loop Schema Type. + * + * @author Kai Lu + */ +public enum ControlLoopSchemaType { + + VNF, VM, SLICE; +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/DynamicPropertiesProvider.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/DynamicPropertiesProvider.java new file mode 100644 index 00000000..a3d12ba2 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/DynamicPropertiesProvider.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +import java.io.Serializable; + +/** + * This contract allows the deserialization mechanism to catch dynamic + * properties in a Map so that deserialization mechanism will not loose any + * information and can be serialized back everything without any loss in + * information. + * + * @author Kai Lu + */ +public interface DynamicPropertiesProvider extends Serializable { + +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/Kpi.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/Kpi.java new file mode 100644 index 00000000..01fc8bc6 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/Kpi.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +import com.google.gson.annotations.SerializedName; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * KPI Formula. + * + * @author Kai Lu + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class Kpi extends BaseModule { + + private static final long serialVersionUID = 1L; + + /** + * measType. + */ + @SerializedName("measType") + private String measType; + + /** + * operation. + */ + private Operation operation; + + /** + * operands. + */ + private String operands; + + /** + * condition. + * + */ + private String condition; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/KpiConfig.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/KpiConfig.java new file mode 100644 index 00000000..d3bc429b --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/KpiConfig.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +import com.google.gson.annotations.SerializedName; +import java.util.List; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * Kpi Config. + * + * @author Kai Lu + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class KpiConfig extends BaseModule { + + private static final long serialVersionUID = 1L; + + /** + * Kpi domain which is associated with KPI incoming ves message domain. + */ + private String domain; + + /** + * Contains MethodForKpi metrics that needs to be applied to each Functional + * Role. + */ + @SerializedName("methodForKpi") + private List<MethodForKpi> methodForKpi; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/KpiJsonConversion.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/KpiJsonConversion.java new file mode 100644 index 00000000..f4a7c428 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/KpiJsonConversion.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +import com.google.gson.Gson; + +/** + * Kpi Json Conversion. + * + * @author Kai Lu + * + */ +public class KpiJsonConversion { + + /** + * Constructor. + * + * @author Kai Lu + * + */ + private KpiJsonConversion() { + } + + /** + * Convert String Kpi Config Object. + * + * @param kpiConfigString kpiConfigString + * + * @return kpiConfig + * + */ + public static KpiConfig convertKpiConfig(String kpiConfigString) { + Gson gson = new Gson(); + KpiConfig kpiConfig = gson.fromJson(kpiConfigString, KpiConfig.class); + return kpiConfig; + } +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/MethodForKpi.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/MethodForKpi.java new file mode 100644 index 00000000..b7067731 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/MethodForKpi.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +import com.google.gson.annotations.SerializedName; +import java.util.List; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * MethodForKpi. + * + * @author Kai Lu + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MethodForKpi extends BaseModule { + + private static final long serialVersionUID = 1L; + + /** + * Event Name. + */ + @SerializedName("eventName") + private String eventName; + + /** + * Control Loop Schema Type. + */ + @SerializedName("controlLoopSchemaType") + private ControlLoopSchemaType controlLoopSchemaType; + + /** + * Policy Scope. + */ + @SerializedName("policyScope") + private String policyScope; + + /** + * Policy Name. + */ + @SerializedName("policyName") + private String policyName; + + /** + * Policy Version. + */ + @SerializedName("policyVersion") + private String policyVersion; + + /** + * Policy Thresholds. + */ + private List<Kpi> kpis; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/Operation.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/Operation.java new file mode 100644 index 00000000..c61b827e --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/config/Operation.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.config; + +public enum Operation { + + SUM("org.onap.dcaegen2.kpi.computation.SumKpiComputation"), RATIO("org.onap.dcaegen2.kpi.computation.RATIO"), + MEAN("org.onap.dcaegen2.kpi.computation.MEAN"); + + public final String value; + + private Operation(String value) { + this.value = value; + } + + public String value() { + return this.value; + } +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/controller/ConfigFetchFromCbs.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/controller/ConfigFetchFromCbs.java new file mode 100644 index 00000000..ba8e33ea --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/controller/ConfigFetchFromCbs.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.controller; + +import java.lang.reflect.Type; +import java.time.Duration; +import java.util.Map; + +import org.onap.dcaegen2.kpi.models.ConfigPolicy; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory; +import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests; +import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration; +import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest; +import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import reactor.core.Disposable; + +/** + * This class provides method to fetch application Configuration from CBS. + */ +public class ConfigFetchFromCbs implements Runnable { + + private static Logger log = LoggerFactory.getLogger(ConfigFetchFromCbs.class); + + private Duration interval; + + public ConfigFetchFromCbs() { + + } + + public ConfigFetchFromCbs(Duration interval) { + this.interval = interval; + } + + /** + * Gets app config from CBS. + */ + private Disposable getAppConfig() { + + // Generate RequestID and InvocationID which will be used when logging and in + // HTTP requests + log.info("getAppconfig start .."); + RequestDiagnosticContext diagnosticContext = RequestDiagnosticContext.create(); + // Read necessary properties from the environment + final var env = CbsClientConfiguration.fromEnvironment(); + + log.debug("environments {}", env); + ConfigPolicy configPolicy = ConfigPolicy.getInstance(); + + // Polling properties + final Duration initialDelay = Duration.ofSeconds(5); + final Duration period = interval; + + // Create the client and use it to get the configuration + final CbsRequest request = CbsRequests.getAll(diagnosticContext); + return CbsClientFactory.createCbsClient(env) + .flatMapMany(cbsClient -> cbsClient.updates(request, initialDelay, period)).subscribe(jsonObject -> { + log.info("configuration and policy from CBS {}", jsonObject); + JsonObject config = jsonObject.getAsJsonObject("config"); + Duration newPeriod = Duration.ofSeconds(config.get("cbsPollingInterval").getAsInt()); + if (!newPeriod.equals(period)) { + interval = newPeriod; + synchronized (this) { + this.notifyAll(); + } + + } + Configuration.getInstance().updateConfigurationFromJsonObject(config); + + Type mapType = new TypeToken<Map<String, Object>>() { + }.getType(); + if (jsonObject.getAsJsonObject("policies") != null) { + JsonObject policyJson = jsonObject.getAsJsonObject("policies").getAsJsonArray("items").get(0) + .getAsJsonObject().getAsJsonObject("config"); + Map<String, Object> policy = new Gson().fromJson(policyJson, mapType); + configPolicy.setConfig(policy); + log.info("Config policy {}", configPolicy); + } + }, throwable -> log.warn("Get config from cbs error", throwable)); + } + + @Override + public void run() { + Boolean done = false; + while (!done) { + try { + Disposable disp = getAppConfig(); + synchronized (this) { + this.wait(); + } + log.info("Polling interval changed"); + disp.dispose(); + } catch (Exception e) { + log.info("The config won't be updated"); + done = true; + } + } + } + +} + + diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/controller/HealthCheck.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/controller/HealthCheck.java new file mode 100644 index 00000000..58d2483b --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/controller/HealthCheck.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * This Controller provides the kpi-ms application's health. + */ +@RestController +public class HealthCheck { + @RequestMapping(value = "/healthcheck", method = RequestMethod.GET) + public ResponseEntity<HttpStatus> healthCheck() { + return new ResponseEntity<>(HttpStatus.OK); + } +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/DmaapClient.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/DmaapClient.java new file mode 100644 index 00000000..d6e17d62 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/DmaapClient.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import com.att.nsa.cambria.client.CambriaConsumer; + +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.annotation.PostConstruct; + +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.kpi.utils.DmaapUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Component; + +/** + * This class initializes and starts the dmaap client to listen on application + * required dmaap events. + */ +@Component +public class DmaapClient { + + private Configuration configuration; + private static Logger log = LoggerFactory.getLogger(DmaapClient.class); + + private DmaapUtils dmaapUtils; + + /** + * init dmaap client. + */ + @PostConstruct + public void initClient() { + log.debug("initializing client"); + dmaapUtils = new DmaapUtils(); + configuration = Configuration.getInstance(); + if (log.isDebugEnabled()) { + log.debug(configuration.toString()); + } + + startClient(); + } + + /** + * start dmaap client. + */ + @SuppressWarnings("unchecked") + public synchronized void startClient() { + + Map<String, Object> streamSubscribes = configuration.getStreamsSubscribes(); + + String pmTopicUrl = ((Map<String, String>) ((Map<String, Object>) streamSubscribes + .get("performance_management_topic")).get("dmaap_info")).get("topic_url"); + String[] pmTopicSplit = pmTopicUrl.split("\\/"); + String pmTopic = pmTopicSplit[pmTopicSplit.length - 1]; + log.debug("pm topic : {}", pmTopic); + + CambriaConsumer pmNotifCambriaConsumer = dmaapUtils.buildConsumer(configuration, pmTopic); + + ScheduledExecutorService executorPool; + + // create notification consumers for PM + NotificationConsumer pmNotificationConsumer = new NotificationConsumer(pmNotifCambriaConsumer, + new KpiComputationCallBack()); + // start pm notification consumer threads + executorPool = Executors.newScheduledThreadPool(10); + executorPool.scheduleAtFixedRate(pmNotificationConsumer, 0, configuration.getPollingInterval(), + TimeUnit.SECONDS); + + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/KpiComputationCallBack.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/KpiComputationCallBack.java new file mode 100644 index 00000000..8ab625c7 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/KpiComputationCallBack.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import java.util.List; + +import org.onap.dcaegen2.kpi.computation.KpiComputation; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.kpi.models.VesEvent; +import org.onap.dcaegen2.kpi.utils.DmaapUtils; +import org.onap.dcaegen2.kpi.utils.VesJsonConversion; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SumKpiComputation. + * + * @author Kai Lu + */ +public class KpiComputationCallBack implements NotificationCallback { + + private static Logger logger = LoggerFactory.getLogger(KpiComputationCallBack.class); + + @Override + public void activateCallBack(String msg) { + Configuration config = Configuration.getInstance(); + if (config == null) { + logger.info("Config is not exist"); + return; + } + + kpiComputation(msg, config); + } + + /** + * do KPI computation and publish result to dmaap. + * + * @param msg msg + * @param config config + * + */ + public void kpiComputation(String msg, Configuration config) { + logger.info("Original PM data: {}", msg); + + logger.info("Kpi Config: {}", config.getKpiConfig()); + + // do computation + KpiComputation kpiComputation = new KpiComputation(); + List<VesEvent> vesEvents = kpiComputation.checkAndDoComputation(msg, config); + + if (vesEvents == null || vesEvents.isEmpty()) { + logger.info("No Kpi Event exist"); + return; + } + logger.info("KPI results: {}", vesEvents); + + // publish kpi computation result + if (publish(vesEvents, config)) { + logger.info("publish success"); + return; + } + + logger.error("publish events failed: {}", vesEvents); + + } + + /** + * ves publish. + * + * @param vesEvents vesEvents + * + */ + private boolean publish(List<VesEvent> vesEvents, Configuration configuration) { + logger.info("Publishing KPI VES events to messagerouter."); + KpiDmaapClient kpiDmaapClient = new KpiDmaapClient(new DmaapUtils(), configuration); + try { + vesEvents.forEach(e -> { + // publish kpi computation result + String event = VesJsonConversion.convertVesEventToString(e); + + logger.info("Publishing event: {}.", event); + + kpiDmaapClient.sendNotificationToDmaap(event); + }); + logger.info("KPI computation done successfully"); + return true; + } catch (Exception e) { + logger.error("KPI computation done failed.", e); + } + return false; + } +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/KpiDmaapClient.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/KpiDmaapClient.java new file mode 100644 index 00000000..5e8733e9 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/KpiDmaapClient.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import java.io.IOException; +import java.util.Map; + +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.kpi.utils.DmaapUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; + +/** + * Client class to handle kpi interactions. + */ +public class KpiDmaapClient { + + private static Logger logger = LoggerFactory.getLogger(KpiDmaapClient.class); + + private DmaapUtils dmaapUtils; + + private Configuration configuration; + + public KpiDmaapClient(DmaapUtils dmaapUtils, Configuration configuration) { + this.dmaapUtils = dmaapUtils; + this.configuration = configuration; + } + + /** + * Method stub for sending kpi msg to dmaap. + */ + @SuppressWarnings("unchecked") + public boolean sendNotificationToDmaap(String msg) { + + Map<String, Object> streamsPublishes = configuration.getStreamsPublishes(); + + logger.info("streamsPublishes: {}", streamsPublishes); + String topicUrl = ((Map<String, String>) ((Map<String, Object>) streamsPublishes.get("kpi_topic")) + .get("dmaap_info")).get("topic_url"); + + logger.info("Kpi publish topic url: {}", topicUrl); + String[] topicSplit = topicUrl.split("\\/"); + String topic = topicSplit[topicSplit.length - 1]; + CambriaBatchingPublisher cambriaBatchingPublisher; + try { + + cambriaBatchingPublisher = dmaapUtils.buildPublisher(configuration, topic); + + NotificationProducer notificationProducer = new NotificationProducer(cambriaBatchingPublisher); + notificationProducer.sendNotification(msg); + } catch (IOException e) { + return false; + } + return true; + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NewPmNotification.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NewPmNotification.java new file mode 100644 index 00000000..fcd5e259 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NewPmNotification.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import javax.annotation.PostConstruct; + +import org.springframework.stereotype.Component; + +/** + * This class indicates whether new pm notification is set for the kpi-ms. + */ +@Component +public class NewPmNotification { + + private boolean newNotif; + + /** + * Initialize new pm Notification flag. + */ + @PostConstruct + public void init() { + newNotif = false; + } + + public boolean getNewNotif() { + return newNotif; + } + + public void setNewNotif(boolean newNotif) { + this.newNotif = newNotif; + } + + public NewPmNotification(boolean newNotif) { + super(); + this.newNotif = newNotif; + } + + /** + * Default constructor. + */ + public NewPmNotification() { + + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationCallback.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationCallback.java new file mode 100644 index 00000000..fbd8d2b2 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationCallback.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +public interface NotificationCallback { + + public abstract void activateCallBack(String msg); + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationConsumer.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationConsumer.java new file mode 100644 index 00000000..d7e3376a --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationConsumer.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import com.att.nsa.cambria.client.CambriaConsumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Consume Notifications from DMAAP events. + */ +public class NotificationConsumer implements Runnable { + + private static Logger log = LoggerFactory.getLogger(NotificationConsumer.class); + private CambriaConsumer cambriaConsumer; + private NotificationCallback notificationCallback; + + /** + * Parameterized Constructor. + */ + public NotificationConsumer(CambriaConsumer cambriaConsumer, NotificationCallback notificationCallback) { + super(); + this.cambriaConsumer = cambriaConsumer; + this.notificationCallback = notificationCallback; + } + + /** + * starts fetching msgs from dmaap events. + */ + @Override + public void run() { + try { + Iterable<String> msgs = cambriaConsumer.fetch(); + for (String msg : msgs) { + log.info(msg); + notificationCallback.activateCallBack(msg); + } + } catch (Exception e) { + log.debug("exception when fetching msgs from dmaap", e); + } + + } +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationProducer.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationProducer.java new file mode 100644 index 00000000..628f3d0e --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/dmaap/NotificationProducer.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; + +import java.io.IOException; + +/** + * Produces Notification on DMAAP events. + */ +public class NotificationProducer { + + private CambriaBatchingPublisher cambriaBatchingPublisher; + + /** + * Parameterized constructor. + */ + public NotificationProducer(CambriaBatchingPublisher cambriaBatchingPublisher) { + super(); + this.cambriaBatchingPublisher = cambriaBatchingPublisher; + } + + /** + * sends notification to dmaap. + */ + public int sendNotification(String msg) throws IOException { + + return cambriaBatchingPublisher.send("", msg); + + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/exception/KpiComputationException.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/exception/KpiComputationException.java new file mode 100644 index 00000000..a358797f --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/exception/KpiComputationException.java @@ -0,0 +1,54 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.exception; + +/** + * KPI Computation Exception. + * + * @author Kai Lu + * + */ +public class KpiComputationException extends RuntimeException { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * KPI computation Exception with message. + * + * @param message Error Message for Exception + */ + public KpiComputationException(final String message) { + super(message); + } + + /** + * KPI computation with message and cause. + * + * @param message Error Message for Exception + * @param cause Actual Exception which caused + */ + public KpiComputationException(final String message, final Throwable cause) { + super(message, cause); + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/CommonEventHeader.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/CommonEventHeader.java new file mode 100644 index 00000000..6de18306 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/CommonEventHeader.java @@ -0,0 +1,132 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Fields common to all Events. + * + * @author Kai Lu + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class CommonEventHeader extends BaseModule { + + private static final long serialVersionUID = 1L; + + /** + * The eventing domain associated with this event. + */ + private String domain; + + /** + * Event key that is unique to the event source. + */ + private String eventId; + + /** + * Unique event name. + */ + private String eventName; + + /** + * Event type e.g. applicationVnf, guestOS, hostOS, platform. + */ + private String eventType; + + /** + * The latest unix time aka epoch time associated with the event from any + * component--as microseconds elapsed since 1 Jan 1970 not including leap + * seconds. + */ + private Long lastEpochMicrosec; + + /** + * Three character network function component type as aligned with vfc naming + * standards. + */ + private String nfcNamingCode; + + /** + * Four character network function type as aligned with vnf naming standards. + */ + private String nfNamingCode; + + /** + * Processing Priority. + */ + private Priority priority; + + /** + * UUID identifying the entity reporting the event, for example an OAM VM; must + * be populated by the enrichment process. + */ + private String reportingEntityId; + + /** + * Name of the entity reporting the event, for example, an EMS name; may be the + * same as sourceName. + */ + private String reportingEntityName; + + /** + * Ordering of events communicated by an event source instance or 0 if not + * needed. + */ + private Integer sequence; + + /** + * UUID identifying the entity experiencing the event issue; must be populated + * by the enrichment process. + */ + private String sourceId; + + /** + * Name of the entity experiencing the event issue. + */ + private String sourceName; + + /** + * the earliest unix time aka epoch time associated with the event from any + * component--as microseconds elapsed since 1 Jan 1970 not including leap + * seconds. + */ + private Long startEpochMicrosec; + + /** + * Version of the event header. + */ + private Float version; + + /** + * vesEventListenerVersion. + */ + private String vesEventListenerVersion; + + /** + * timeZoneOffset. + */ + private String timeZoneOffset; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/ConfigPolicy.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/ConfigPolicy.java new file mode 100644 index 00000000..99ffdc61 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/ConfigPolicy.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.models; + +import java.util.Map; + +/** + * ConfigPolicy. + * + * @author Kai Lu + * + */ +public class ConfigPolicy { + + private static ConfigPolicy instance = null; + private Map<String, Object> config; + + protected ConfigPolicy() { + } + + /** + * Get instance of class. + */ + public static ConfigPolicy getInstance() { + if (instance == null) { + instance = new ConfigPolicy(); + } + return instance; + } + + /** + * Get config param of ConfigPolicy. + */ + public Map<String, Object> getConfig() { + return config; + } + + /** + * set config param of ConfigPolicy. + */ + public void setConfig(Map<String, Object> config) { + this.config = config; + } + + /** + * Return ConfigPolicy instance as String. + */ + @Override + public String toString() { + return "ConfigPolicy [config=" + config + "]"; + } +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java new file mode 100644 index 00000000..94085146 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Configuration.java @@ -0,0 +1,277 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.models; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Model class for the application Configuration. + */ +public class Configuration { + private static Logger log = LoggerFactory.getLogger(Configuration.class); + + private static Configuration instance = null; + private List<String> dmaapServers; + private int pollingInterval; + private int pollingTimeout; + private int cbsPollingInterval; + private String aafUsername; + private String aafPassword; + private Map<String, Object> streamsSubscribes; + private Map<String, Object> streamsPublishes; + private String kpiConfig; + private String host; + private int port; + private String username; + private String password; + private String databasename; + private boolean enablessl; + private String cg; + private String cid; + + public int getCbsPollingInterval() { + return cbsPollingInterval; + } + + public void setCbsPollingInterval(int cbsPollingInterval) { + this.cbsPollingInterval = cbsPollingInterval; + } + + public String getCg() { + return cg; + } + + public String getCid() { + return cid; + } + + public void setCg(String cg) { + this.cg = cg; + } + + public void setCid(String cid) { + this.cid = cid; + } + + public List<String> getDmaapServers() { + return dmaapServers; + } + + public void setDmaapServers(List<String> dmaapServers) { + this.dmaapServers = dmaapServers; + } + + public boolean isEnablessl() { + return enablessl; + } + + public void setEnablessl(boolean enablessl) { + this.enablessl = enablessl; + } + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getDatabasename() { + return databasename; + } + + public void setHost(String host) { + this.host = host; + } + + public void setPort(int port) { + this.port = port; + } + + public void setUsername(String username) { + this.username = username; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setDatabasename(String databasename) { + this.databasename = databasename; + } + + /** + * Check if topic is secure. + */ + public boolean isSecured() { + return (aafUsername != null); + + } + + public String getAafUsername() { + return aafUsername; + } + + public void setAafUsername(String aafUsername) { + this.aafUsername = aafUsername; + } + + public String getAafPassword() { + return aafPassword; + } + + public void setAafPassword(String aafPassword) { + this.aafPassword = aafPassword; + } + + public Map<String, Object> getStreamsSubscribes() { + return streamsSubscribes; + } + + public void setStreamsSubscribes(Map<String, Object> streamsSubscribes) { + this.streamsSubscribes = streamsSubscribes; + } + + public Map<String, Object> getStreamsPublishes() { + return streamsPublishes; + } + + public void setStreamsPublishes(Map<String, Object> streamsPublishes) { + this.streamsPublishes = streamsPublishes; + } + + public Configuration() { + + } + + /** + * Get instance of class. + */ + public static Configuration getInstance() { + if (instance == null) { + instance = new Configuration(); + } + return instance; + } + + public int getPollingInterval() { + return pollingInterval; + } + + public void setPollingInterval(int pollingInterval) { + this.pollingInterval = pollingInterval; + } + + public int getPollingTimeout() { + return pollingTimeout; + } + + public void setPollingTimeout(int pollingTimeout) { + this.pollingTimeout = pollingTimeout; + } + + @Override + public String toString() { + return "Configuration [dmaapServers=" + dmaapServers + ", pollingInterval=" + pollingInterval + + ", pollingTimeout=" + pollingTimeout + ", aafUsername=" + aafUsername + ", aafPassword=" + aafPassword + + ", streamsSubscribes=" + streamsSubscribes + ", streamsPublishes=" + streamsPublishes + ", kpiConfig=" + + kpiConfig + "]"; + } + + /** + * updates application configuration. + */ + public void updateConfigurationFromJsonObject(JsonObject jsonObject) { + + log.info("Updating configuration from CBS"); + + Type mapType = new TypeToken<Map<String, Object>>() { + }.getType(); + + JsonObject subscribes = jsonObject.getAsJsonObject("streams_subscribes"); + streamsSubscribes = new Gson().fromJson(subscribes, mapType); + + JsonObject publishes = jsonObject.getAsJsonObject("streams_publishes"); + streamsPublishes = new Gson().fromJson(publishes, mapType); + + pollingInterval = jsonObject.get("pollingInterval").getAsInt(); + pollingTimeout = jsonObject.get("pollingTimeout").getAsInt(); + cbsPollingInterval = jsonObject.get("cbsPollingInterval").getAsInt(); + JsonArray servers = jsonObject.getAsJsonArray("dmaap.server"); + Type listType = new TypeToken<List<String>>() { + }.getType(); + dmaapServers = new Gson().fromJson(servers, listType); + + port = jsonObject.get("mongo.port").getAsInt(); + host = jsonObject.get("mongo.host").getAsString(); +// username = jsonObject.get("mongo.username").getAsString(); +// password = jsonObject.get("mongo.password").getAsString(); + databasename = jsonObject.get("mongo.databasename").getAsString(); + + if (jsonObject.get("aafUsername") == null) { + aafUsername = null; + } else { + aafUsername = jsonObject.get("aafUsername").getAsString(); + } + if (jsonObject.get("aafPassword") == null) { + aafPassword = null; + } else { + aafPassword = jsonObject.get("aafPassword").getAsString(); + } + + kpiConfig = jsonObject.get("kpi.policy").getAsString(); + + log.info("kpi.policy {}", kpiConfig); + // enablessl = jsonObject.get("mongo.enablessl").getAsBoolean(); + cg = jsonObject.get("cg").getAsString(); + cid = jsonObject.get("cid").getAsString(); + log.info("configuration from CBS {}", this); + + } + + public String getKpiConfig() { + return kpiConfig; + } + + public void setKpiConfig(String kpiConfig) { + this.kpiConfig = kpiConfig; + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasDataCollection.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasDataCollection.java new file mode 100644 index 00000000..d750d5f9 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasDataCollection.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.models; + +import java.util.List; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Measment Data Collection. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MeasDataCollection extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * granularityPeriod. + */ + private Long granularityPeriod; + + /** + * measuredEntityUserName. + */ + private String measuredEntityUserName; + + /** + * measuredEntityDn. + */ + private String measuredEntityDn; + + /** + * measuredEntitySoftwareVersion. + */ + private String measuredEntitySoftwareVersion; + + /** + * measInfoList. + */ + private List<MeasInfo> measInfoList; +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasInfo.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasInfo.java new file mode 100644 index 00000000..cbb0170b --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasInfo.java @@ -0,0 +1,58 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import java.util.List; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * MeasInfo. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MeasInfo extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * measInfoId. + */ + private MeasInfoId measInfoId; + + /** + * measTypes. + */ + private MeasTypes measTypes; + + /** + * measValuesList. + */ + private List<MeasValues> measValuesList; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasInfoId.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasInfoId.java new file mode 100644 index 00000000..490e883f --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasInfoId.java @@ -0,0 +1,49 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import com.google.gson.annotations.SerializedName; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * MeasInfo Id. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MeasInfoId extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * sMeasInfoId. + */ + @SerializedName("sMeasTypesList") + private String measInfoId; +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasResult.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasResult.java new file mode 100644 index 00000000..61b4af0d --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasResult.java @@ -0,0 +1,56 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import com.google.gson.annotations.SerializedName; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Measment Result. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MeasResult extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * p. + */ + @SerializedName("p") + private int pvalue; + + /** + * sValue. + */ + @SerializedName("sValue") + private String svalue; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasTypes.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasTypes.java new file mode 100644 index 00000000..4cca4a43 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasTypes.java @@ -0,0 +1,51 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Measment Type. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MeasTypes extends BaseModule { + + /** + * sValue. + */ + private static final long serialVersionUID = 1L; + + /** + * sMeasTypesList. + */ + @SerializedName("sMeasTypesList") + private List<String> measTypesList; +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasValues.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasValues.java new file mode 100644 index 00000000..4603e005 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/MeasValues.java @@ -0,0 +1,59 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import java.util.List; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Measment Values. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class MeasValues extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * measObjInstId. + */ + private String measObjInstId; + + /** + * suspectFlag. + */ + private Boolean suspectFlag; + + /** + * measResults. + */ + private List<MeasResult> measResults; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Perf3gppFields.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Perf3gppFields.java new file mode 100644 index 00000000..f6c36f44 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Perf3gppFields.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.models; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Perf3gppFields. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class Perf3gppFields extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * perf3gppFieldsVersion. + */ + private String perf3gppFieldsVersion; + + /** + * measDataCollection. + */ + private MeasDataCollection measDataCollection; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/PerformanceEvent.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/PerformanceEvent.java new file mode 100644 index 00000000..42ae96fa --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/PerformanceEvent.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.models; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Performance Event. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class PerformanceEvent extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * commonEventHeader. + */ + private CommonEventHeader commonEventHeader; + + /** + * perf3gppFields. + */ + private Perf3gppFields perf3gppFields; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Priority.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Priority.java new file mode 100644 index 00000000..fe71b8b1 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/Priority.java @@ -0,0 +1,30 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +/** + * Common Event Format - Event processing priority. + * + * @author Kai Lu + */ +public enum Priority { + + High, Medium, Normal, Low +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/VesEvent.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/VesEvent.java new file mode 100644 index 00000000..ffee0462 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/models/VesEvent.java @@ -0,0 +1,47 @@ +/* + * ================================================================================ + * Copyright (c) 2021 China Mobile. 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.dcaegen2.kpi.models; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +import org.onap.dcaegen2.kpi.config.BaseModule; + +/** + * Ves Event. + * + * @author Kai Lu + * + */ +@Data +@EqualsAndHashCode(callSuper = true) +public class VesEvent extends BaseModule { + + /** + * serialVersionUID. + */ + private static final long serialVersionUID = 1L; + + /** + * event. + */ + private PerformanceEvent event; + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/BeanUtil.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/BeanUtil.java new file mode 100644 index 00000000..7788b972 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/BeanUtil.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.utils; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Service; + +/** + * This class is used to get/set bean references. + * + * @author Kai Lu + */ +@Service +public class BeanUtil implements ApplicationContextAware { + private static ApplicationContext context; + + /** + * set ApplicationContext. + * + * @param applicationContext applicationContext + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + context = applicationContext; + } + + /** + * Get bean class. + * + * @param <T> T + * @param beanClass beanClass + * @return T + */ + public static <T> T getBean(Class<T> beanClass) { + return context.getBean(beanClass); + } +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/DmaapUtils.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/DmaapUtils.java new file mode 100644 index 00000000..bf252520 --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/DmaapUtils.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.utils; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; +import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; +import com.att.nsa.cambria.client.CambriaConsumer; + +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; + +import org.onap.dcaegen2.kpi.models.Configuration; + +/** + * Utility class to perform actions related to Dmaap. + * + * @author Kai Lu + * + */ +public class DmaapUtils { + + /** + * Build publisher. + */ + public CambriaBatchingPublisher buildPublisher(Configuration config, String topic) { + try { + return builder(config, topic).build(); + } catch (MalformedURLException | GeneralSecurityException e) { + return null; + + } + } + + /** + * Build consumer. + */ + public CambriaConsumer buildConsumer(Configuration config, String topic) { + + try { + return builderConsumer(config, topic).build(); + } catch (MalformedURLException | GeneralSecurityException e) { + return null; + } + + } + + private static PublisherBuilder builder(Configuration config, String topic) { + if (config.isSecured()) { + return authenticatedBuilder(config, topic); + } else { + return unAuthenticatedBuilder(config, topic); + } + } + + private static PublisherBuilder authenticatedBuilder(Configuration config, String topic) { + return unAuthenticatedBuilder(config, topic).usingHttps().authenticatedByHttp(config.getAafUsername(), + config.getAafPassword()); + } + + private static PublisherBuilder unAuthenticatedBuilder(Configuration config, String topic) { + return new CambriaClientBuilders.PublisherBuilder().usingHosts(config.getDmaapServers()).onTopic(topic) + .logSendFailuresAfter(5); + } + + private static ConsumerBuilder builderConsumer(Configuration config, String topic) { + if (config.isSecured()) { + return authenticatedConsumerBuilder(config, topic); + } else { + return unAuthenticatedConsumerBuilder(config, topic); + } + } + + private static ConsumerBuilder unAuthenticatedConsumerBuilder(Configuration config, String topic) { + return new CambriaClientBuilders.ConsumerBuilder().usingHosts(config.getDmaapServers()).onTopic(topic) + .knownAs(config.getCg(), config.getCid()).withSocketTimeout(config.getPollingTimeout() * 1000); + } + + private static ConsumerBuilder authenticatedConsumerBuilder(Configuration config, String topic) { + return unAuthenticatedConsumerBuilder(config, topic).usingHttps().authenticatedByHttp(config.getAafUsername(), + config.getAafPassword()); + } + +} diff --git a/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/VesJsonConversion.java b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/VesJsonConversion.java new file mode 100644 index 00000000..3a6c87da --- /dev/null +++ b/components/kpi-computation-ms/src/main/java/org/onap/dcaegen2/kpi/utils/VesJsonConversion.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.utils; + +import com.google.gson.Gson; +import org.json.JSONObject; +import org.onap.dcaegen2.kpi.models.VesEvent; + +/** + * Ves Json Conversion. + * + * @author Kai Lu + * + */ +public class VesJsonConversion { + + private VesJsonConversion() { + } + + /** + * ves event convert. + * + * @param strVesEvent strVesEvent + * @return ves event + * + */ + public static VesEvent convertVesEvent(String strVesEvent) { + Gson gson = new Gson(); + VesEvent vesEvent = gson.fromJson(strVesEvent, VesEvent.class); + return vesEvent; + } + + /** + * ves event convert. + * + * @param strVesEvent strVesEvent + * @return jsonOject JSONObject + * + */ + public static JSONObject convertToJsonObject(String strVesEvent) { + return new JSONObject(strVesEvent); + } + + /** + * ves event convert. + * + * @param vesEvent vesEvent + * @return Kpi event string list + * + */ + public static String convertVesEventToString(VesEvent vesEvent) { + Gson gson = new Gson(); + String strVesEvent = gson.toJson(vesEvent); + return strVesEvent; + } +} diff --git a/components/kpi-computation-ms/src/main/resources/application.properties b/components/kpi-computation-ms/src/main/resources/application.properties new file mode 100644 index 00000000..6065f6d2 --- /dev/null +++ b/components/kpi-computation-ms/src/main/resources/application.properties @@ -0,0 +1,20 @@ +############################################################################### +# ============LICENSE_START======================================================= +# Copyright (C) 2021 China Mobile. +# ============================================================================== +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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========================================================= +# +############################################################################### + + diff --git a/components/kpi-computation-ms/src/main/resources/logback.xml b/components/kpi-computation-ms/src/main/resources/logback.xml new file mode 100644 index 00000000..e1691f45 --- /dev/null +++ b/components/kpi-computation-ms/src/main/resources/logback.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +/******************************************************************************* + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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========================================================= + * + *******************************************************************************/ + --> + <configuration> + + <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> + <layout class="ch.qos.logback.classic.PatternLayout"> + <Pattern> + %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + </Pattern> + </layout> + </appender> + + <root level="info"> + <appender-ref ref="CONSOLE"/> + </root> + +</configuration> diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/ApplicationTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/ApplicationTest.java new file mode 100644 index 00000000..c0827319 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/ApplicationTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationTest.class) +public class ApplicationTest { + + @Test + public void contextLoads() { + Application.getConfig(); + Application.getStandaloneConfig("src/test/resources/kpi/cbs_config1.json"); + Application.getStandaloneConfig("src/test/resources/config_all.json"); + } +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/FileUtils.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/FileUtils.java new file mode 100644 index 00000000..d40cc02a --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/FileUtils.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020-2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * File read utils. + * + * @author Kai Lu + */ +public class FileUtils { + + /** + * Reads contents of files inside the eventBodyDirectory, combines contents with + * metadata to make an Event Object. Fails test in the event of failure to read + * a file. + * + * @param targetDirectory Path to directory with files. + * @return List of Strings containing the body as acquired from files inside + * targetDirectory. + * @throws IOException in the event it fails to read from the files. + */ + public static List<String> getFilesFromDirectory(Path targetDirectory) throws IOException { + try (Stream<Path> eventFileStream = Files.walk(targetDirectory)) { + return eventFileStream.filter(Files::isRegularFile).filter(Files::isReadable) + .map(FileUtils::getFileContents).collect(Collectors.toList()); + } + } + + /** + * reads contents of file into a string. fails a tests in the event failure + * occurs. + * + * @param path path to file. + * @return string containing files contents + */ + public static String getFileContents(Path path) { + try { + return new String(Files.readAllBytes(path)); + } catch (IOException exception) { + fail("IOException occurred while reading file."); + } + return null; + } + + /** + * Reads contents of resource. fails a test in the event failure occurs. + * + * @param fileName of file in resources to be read. + * @return contents of file + */ + public static String getFileContents(String fileName) { + try { + Path path = Paths.get(ClassLoader.getSystemResource(fileName).toURI()); + return getFileContents(path); + } catch (URISyntaxException exception) { + fail("Exception occurred, failed to acquire resource URI."); + } + return null; + } +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/KpiComputationTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/KpiComputationTest.java new file mode 100644 index 00000000..0bb3b184 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/KpiComputationTest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.junit.Test; +import org.onap.dcaegen2.kpi.computation.KpiComputation; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.kpi.models.VesEvent; + +public class KpiComputationTest { + + private static final String KPI_CONFIG_FILE = "kpi/kpi_config.json"; + private static final String VES_MESSAGE_FILE = "kpi/ves_message.json"; + + @Test + public void testKpiComputation() { + + + String strKpiConfig = FileUtils.getFileContents(KPI_CONFIG_FILE); + + String vesMessage = FileUtils.getFileContents(VES_MESSAGE_FILE); + + Configuration config = mock(Configuration.class); + when(config.getKpiConfig()).thenReturn(strKpiConfig); + List<VesEvent> vesList = new KpiComputation().checkAndDoComputation(vesMessage, config); + + VesEvent vesEvent = vesList.get(0); + assertEquals(vesEvent.getEvent().getPerf3gppFields().getMeasDataCollection().getMeasInfoList().get(0) + .getMeasValuesList().get(0).getMeasResults().get(0).getSvalue(), "40"); + } + +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/KpiTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/KpiTest.java new file mode 100644 index 00000000..94aca96a --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/computation/KpiTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.computation; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.dcaegen2.kpi.config.KpiConfig; +import org.onap.dcaegen2.kpi.config.KpiJsonConversion; +import org.onap.dcaegen2.kpi.models.VesEvent; +import org.onap.dcaegen2.kpi.utils.VesJsonConversion; + +public class KpiTest { + + private static final String KPI_CONFIG_FILE = "kpi/kpi_config.json"; + private static final String VES_MESSAGE_FILE = "kpi/ves_message.json"; + + @Test + public void testKpiConfigValidate() { + + String strKpiConfig = FileUtils.getFileContents(KPI_CONFIG_FILE); + + KpiConfig kpiConfig = KpiJsonConversion.convertKpiConfig(strKpiConfig); + assertEquals(kpiConfig.getDomain(), "measurementsForKpi"); + } + + @Test + public void testVesEventValidate() { + + String vesMessage = FileUtils.getFileContents(VES_MESSAGE_FILE); + + VesEvent vesEvent = VesJsonConversion.convertVesEvent(vesMessage); + assertEquals(vesEvent.getEvent().getCommonEventHeader().getDomain(), "perf3gpp"); + } + +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/DmaapClientTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/DmaapClientTest.java new file mode 100644 index 00000000..8020f938 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/DmaapClientTest.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import static org.mockito.Mockito.when; + +import com.att.nsa.cambria.client.CambriaTopicManager; +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DmaapClientTest.class) +public class DmaapClientTest { + + @Mock + private CambriaTopicManager topicManager; + + @InjectMocks + DmaapClient client; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void getAllTopicsTest() { + Set<String> topics = new HashSet<String>(); + topics.add("topic1"); + topics.add("topic2"); + Configuration configuration = Configuration.getInstance(); + List<String> list = new ArrayList<String>(); + list.add("server"); + configuration.setDmaapServers(list); + configuration.setCg("cg"); + configuration.setCid("cid"); + configuration.setPollingInterval(30); + configuration.setPollingTimeout(100); + + try { + when(topicManager.getTopics()).thenReturn(topics); + + client = Mockito.mock(DmaapClient.class); + client.initClient(); + Mockito.verify(client).initClient(); + // Mockito.verifycreateAndConfigureTopics(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void startClientTest() { + try { + Configuration configuration = Configuration.getInstance(); + String configAllJson = readFromFile("src/test/resources/config_all.json"); + + JsonObject configAll = new Gson().fromJson(configAllJson, JsonObject.class); + + JsonObject config = configAll.getAsJsonObject("config"); + System.out.println(configuration); + configuration.updateConfigurationFromJsonObject(config); + DmaapClient client = new DmaapClient(); + client.initClient(); + // Mockito.verify(client).startClient(); + // Mockito.verifycreateAndConfigureTopics(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static String readFromFile(String file) { + String content = ""; + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + content = bufferedReader.readLine(); + String temp; + while ((temp = bufferedReader.readLine()) != null) { + content = content.concat(temp); + } + content = content.trim(); + } catch (Exception e) { + content = null; + } + return content; + } +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/KpiDmaapClientTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/KpiDmaapClientTest.java new file mode 100644 index 00000000..e8fd9925 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/KpiDmaapClientTest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.onap.dcaegen2.kpi.utils.DmaapUtils; +import org.springframework.boot.test.context.SpringBootTest; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaConsumer; + +@RunWith(MockitoJUnitRunner.class) +@SpringBootTest(classes = KpiDmaapClient.class) +public class KpiDmaapClientTest { + + @Mock + Configuration configurationMock; + + @Mock + DmaapUtils dmaapUtilsMock; + + @InjectMocks + KpiDmaapClient kpiDmaapClient; + + @Mock + CambriaConsumer kpiResponseCambriaConsumerMock; + + @Mock + CambriaBatchingPublisher cambriaBatchingPublisherMock; + + @Mock + NotificationProducer notificationProducerMock; + + @Before + public void setup() { + kpiDmaapClient = new KpiDmaapClient(dmaapUtilsMock, configurationMock); + } + + @Test + public void sendNotificationToPolicyTest() { + Map<String, Object> streamsPublishes = new HashMap<>(); + Map<String, String> topics = new HashMap<>(); + Map<String, Object> dmaapInfo = new HashMap<>(); + topics.put("topic_url", "https://message-router.onap.svc.cluster.local:3905/events/DCAE_KPI_OUTPUT"); + dmaapInfo.put("dmaap_info", topics); + streamsPublishes.put("kpi_topic", dmaapInfo); + Mockito.when(configurationMock.getStreamsPublishes()).thenReturn(streamsPublishes); + Mockito.when(dmaapUtilsMock.buildPublisher(configurationMock, "DCAE_KPI_OUTPUT")) + .thenReturn(cambriaBatchingPublisherMock); + try { + Mockito.when(cambriaBatchingPublisherMock.send("", "hello")).thenReturn(0); + } catch (IOException e) { + e.printStackTrace(); + } + assertTrue(kpiDmaapClient.sendNotificationToDmaap("hello")); + + } +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NewPmNotificationTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NewPmNotificationTest.java new file mode 100644 index 00000000..db52c53d --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NewPmNotificationTest.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class NewPmNotificationTest { + + @Test + public void testNewPmNotif() { + NewPmNotification newPmNotif1 = new NewPmNotification(true); + NewPmNotification newPmNotif2 = new NewPmNotification(); + newPmNotif2.setNewNotif(true); + assertTrue(newPmNotif2.getNewNotif()); + newPmNotif2.init(); + assertEquals(false, newPmNotif2.getNewNotif()); + assertTrue(newPmNotif1.getNewNotif()); + + } +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NotificationConsumerTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NotificationConsumerTest.java new file mode 100644 index 00000000..1d04a627 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NotificationConsumerTest.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.att.nsa.cambria.client.CambriaConsumer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NotificationConsumerTest.class) +public class NotificationConsumerTest { + + @Mock + CambriaConsumer cambriaConsumer; + + @Mock + NotificationCallback notificationCallback; + + @InjectMocks + NotificationConsumer notificationConsumer; + + @Test + public void testNotificationConsumer() { + try { + List<String> notifications = new ArrayList<>(); + notifications.add("notification1"); + when(cambriaConsumer.fetch()).thenReturn(notifications); + Mockito.doNothing().when(notificationCallback).activateCallBack(Mockito.anyString()); + notificationConsumer.run(); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NotificationProducerTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NotificationProducerTest.java new file mode 100644 index 00000000..c835d49b --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/NotificationProducerTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.io.IOException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.dcaegen2.kpi.computation.FileUtils; +import org.onap.dcaegen2.kpi.models.Configuration; +import org.powermock.api.mockito.PowerMockito; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NotificationProducerTest.class) +public class NotificationProducerTest { + + private static final String VES_MESSAGE_FILE = "kpi/ves_message.json"; + private static final String CBS_CONFIG_FILE = "kpi/cbs_config2.json"; + + @Mock + CambriaBatchingPublisher cambriaBatchingPublisher; + + @InjectMocks + NotificationProducer notificationProducer; + + @Test + public void notificationProducerTest() { + + try { + when(cambriaBatchingPublisher.send(Mockito.anyString(), Mockito.anyString())).thenReturn(0); + int result = notificationProducer.sendNotification("msg"); + assertEquals(0, result); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + @Test + public void kpiResultWithoutConfigTest() { + + String vesMessage = FileUtils.getFileContents(VES_MESSAGE_FILE); + KpiComputationCallBack callback = new KpiComputationCallBack(); + callback.activateCallBack(vesMessage); + + } + + @Test + public void kpiResultWithConfigTest() { + + String vesMessage = FileUtils.getFileContents(VES_MESSAGE_FILE); + String strCbsConfig = FileUtils.getFileContents(CBS_CONFIG_FILE); + + JsonObject jsonObject = new JsonParser().parse(strCbsConfig).getAsJsonObject().getAsJsonObject("config"); + Configuration config = new Configuration(); + config.updateConfigurationFromJsonObject(jsonObject); + + KpiComputationCallBack callback = new KpiComputationCallBack(); + callback.kpiComputation(vesMessage, config); + + } + +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/PmNotificationCallbackTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/PmNotificationCallbackTest.java new file mode 100644 index 00000000..5241ecd9 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/dmaap/PmNotificationCallbackTest.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.dmaap; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.onap.dcaegen2.kpi.utils.BeanUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*" }) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ BeanUtil.class }) +@SpringBootTest(classes = PmNotificationCallbackTest.class) +public class PmNotificationCallbackTest { + + @Mock + NewPmNotification newPmNotif; + + @Test + public void testActivateCallBack() { + PowerMockito.mockStatic(BeanUtil.class); + PowerMockito.when(BeanUtil.getBean(NewPmNotification.class)).thenReturn(newPmNotif); + NotificationCallback pmNotificationCallback = new KpiComputationCallBack(); + pmNotificationCallback.activateCallBack("pmNotification"); + } + +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/models/ConfigurationTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/models/ConfigurationTest.java new file mode 100644 index 00000000..07ef51d2 --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/models/ConfigurationTest.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2020 Wipro Limited. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.dcaegen2.kpi.models; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + + +public class ConfigurationTest { + Configuration configuration = Configuration.getInstance(); + + @Test + public void configurationTest() { + + List<String> list = new ArrayList<String>(); + list.add("server"); + Map<String, Object> subscribes = new HashMap<>(); + + configuration.setStreamsSubscribes(subscribes); + configuration.setStreamsPublishes(subscribes); + configuration.setDmaapServers(list); + configuration.setCg("cg"); + configuration.setCid("cid"); + configuration.setAafPassword("password"); + configuration.setAafUsername("user"); + configuration.setPollingInterval(30); + configuration.setPollingTimeout(100); + configuration.setHost("192.168.1.1"); + configuration.setPort(21); + configuration.setPassword("password"); + configuration.setUsername("user"); + configuration.setDatabasename("database"); + configuration.setEnablessl(true); + configuration.setCbsPollingInterval(10); + configuration.setKpiConfig("kpi config"); + + assertEquals("cg", configuration.getCg()); + assertEquals("cid", configuration.getCid()); + assertEquals("user", configuration.getAafUsername()); + assertEquals("password", configuration.getAafPassword()); + assertEquals(30, configuration.getPollingInterval()); + assertEquals(100, configuration.getPollingTimeout()); + assertEquals(list, configuration.getDmaapServers()); + assertEquals("192.168.1.1", configuration.getHost()); + assertEquals(21, configuration.getPort()); + assertEquals("user", configuration.getUsername()); + assertEquals("password", configuration.getPassword()); + assertEquals("database", configuration.getDatabasename()); + assertEquals(true, configuration.isEnablessl()); + assertEquals("kpi config", configuration.getKpiConfig()); + assertEquals(10, configuration.getCbsPollingInterval()); + } +} diff --git a/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/models/ModelsTest.java b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/models/ModelsTest.java new file mode 100644 index 00000000..ad549bec --- /dev/null +++ b/components/kpi-computation-ms/src/test/java/org/onap/dcaegen2/kpi/models/ModelsTest.java @@ -0,0 +1,212 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 China Mobile. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.kpi.models; + +import static org.junit.Assert.assertEquals; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.dcaegen2.kpi.computation.FileUtils; +import org.onap.dcaegen2.kpi.config.BaseDynamicPropertiesProvider; +import org.onap.dcaegen2.kpi.config.Kpi; +import org.onap.dcaegen2.kpi.config.KpiConfig; +import org.onap.dcaegen2.kpi.config.MethodForKpi; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.openpojo.reflection.PojoClass; +import com.openpojo.reflection.impl.PojoClassFactory; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.rule.impl.GetterMustExistRule; +import com.openpojo.validation.rule.impl.SetterMustExistRule; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SerializableTester; +import com.openpojo.validation.test.impl.SetterTester; + +public class ModelsTest { + + private static final String CBS_CONFIG_FILE = "kpi/cbs_config1.json"; + + public void validateMd(PojoClass pojoclass) { + Validator validator = ValidatorBuilder.create() + .with(new SetterMustExistRule()) + .with(new GetterMustExistRule()) + .with(new SetterTester()) + .with(new GetterTester()) + .with(new SerializableTester()) + .build(); + validator.validate(pojoclass); + } + + @Test + public void testGetterSetterPerformanceEvent() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(PerformanceEvent.class); + validateMd(pojoclass); + PerformanceEvent x = new PerformanceEvent(); + PerformanceEvent y = new PerformanceEvent(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testMeasTypes() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasTypes.class); + validateMd(pojoclass); + MeasTypes x = new MeasTypes(); + MeasTypes y = new MeasTypes(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testMeasInfoId() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasInfoId.class); + validateMd(pojoclass); + MeasInfoId x = new MeasInfoId(); + MeasInfoId y = new MeasInfoId(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testVesEvent() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(VesEvent.class); + validateMd(pojoclass); + VesEvent x = new VesEvent(); + VesEvent y = new VesEvent(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testMeasResult() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasResult.class); + validateMd(pojoclass); + MeasResult x = new MeasResult(); + MeasResult y = new MeasResult(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testPerf3gppFields() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(Perf3gppFields.class); + validateMd(pojoclass); + Perf3gppFields x = new Perf3gppFields(); + Perf3gppFields y = new Perf3gppFields(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testMeasInfo() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasInfo.class); + validateMd(pojoclass); + MeasInfo x = new MeasInfo(); + MeasInfo y = new MeasInfo(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testMeasValues() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasValues.class); + validateMd(pojoclass); + MeasValues x = new MeasValues(); + MeasValues y = new MeasValues(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testMeasDataCollection() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MeasDataCollection.class); + validateMd(pojoclass); + MeasDataCollection x = new MeasDataCollection(); + MeasDataCollection y = new MeasDataCollection(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testCommonEventHeader() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(CommonEventHeader.class); + validateMd(pojoclass); + CommonEventHeader x = new CommonEventHeader(); + CommonEventHeader y = new CommonEventHeader(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testGetterSetterKpiConfig() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(KpiConfig.class); + validateMd(pojoclass); + KpiConfig x = new KpiConfig(); + KpiConfig y = new KpiConfig(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testGetterSetterMethodForKpi() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(MethodForKpi.class); + validateMd(pojoclass); + MethodForKpi x = new MethodForKpi(); + MethodForKpi y = new MethodForKpi(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testGetterSetterKpi() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(Kpi.class); + validateMd(pojoclass); + Kpi x = new Kpi(); + Kpi y = new Kpi(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + + @Test + public void testGetterSetterConfiguration() { + + String strCbsConfig = FileUtils.getFileContents(CBS_CONFIG_FILE); + JsonObject jsonObject = new JsonParser().parse(strCbsConfig).getAsJsonObject().getAsJsonObject("config"); + Configuration config = new Configuration(); + config.updateConfigurationFromJsonObject(jsonObject); + + assertEquals(config.getAafPassword(), "demo123456!"); + + } + + @Test + public void testBaseDynamicPropertiesProvider() { + PojoClass pojoclass = PojoClassFactory.getPojoClass(BaseDynamicPropertiesProvider.class); + validateMd(pojoclass); + BaseDynamicPropertiesProvider x = new BaseDynamicPropertiesProvider(); + BaseDynamicPropertiesProvider y = new BaseDynamicPropertiesProvider(); + Assert.assertTrue(x.equals(y) && y.equals(x)); + Assert.assertTrue(x.hashCode() == y.hashCode()); + } + +} diff --git a/components/kpi-computation-ms/src/test/resources/config_all.json b/components/kpi-computation-ms/src/test/resources/config_all.json new file mode 100644 index 00000000..eb84e0d8 --- /dev/null +++ b/components/kpi-computation-ms/src/test/resources/config_all.json @@ -0,0 +1,89 @@ +{ + "config": { + "pollingInterval": 20, + "aafUsername": "dcae@dcae.onap.org", + "cbsPollingInterval": 60, + "mongo.host": "192.168.225.61", + "cid": "kpi-cid", + "trust_store_pass_path": "/opt/app/kpims/etc/cert/trust.pass", + "cg": "kpi-cg", + "mongo.port": 27017, + "mongo.databasename": "datalake", + "streams_subscribes": { + "performance_management_topic": { + "aaf_password": "demo123456!", + "type": "message-router", + "dmaap_info": { + "topic_url": "https://message-router.onap.svc.cluster.local:3905/events/org.onap.dmaap.mr.PERFORMANCE_MEASUREMENTS" + }, + "aaf_username": "dcae@dcae.onap.org" + } + }, + "trust_store_path": "/opt/app/kpims/etc/cert/trust.jks", + "pollingTimeout": 60, + "streams_publishes": { + "kpi_topic": { + "aaf_password": "demo123456!", + "type": "message-router", + "dmaap_info": { + "topic_url": "https://message-router.onap.svc.cluster.local:3905/events/unauthenticated.DCAE_KPI_OUTPUT" + }, + "aaf_username": "dcae@dcae.onap.org" + } + }, + "aafPassword": "demo123456!", + "kpi.policy": "{\"domain\":\"measurementsForKpi\",\"methodForKpi\":[{\"eventName\":\"perf3gpp_CORE-AMF_pmMeasResult\",\"controlLoopSchemaType\":\"SLICE\",\"policyScope\":\"resource=networkSlice;type=configuration\",\"policyName\":\"configuration.dcae.microservice.pm-mapper.xml\",\"policyVersion\":\"v0.0.1\",\"kpis\":[{\"measType\":\"AMFRegNbr\",\"operation\":\"SUM\",\"operands\":\"RM.RegisteredSubNbrMean\"}]},{\"eventName\":\"perf3gpp_AcmeNode-Acme_pmMeasResult\",\"controlLoopSchemaType\":\"SLICE\",\"policyScope\":\"resource=networkSlice;type=configuration\",\"policyName\":\"configuration.dcae.microservice.pm-mapper.xml\",\"policyVersion\":\"v0.0.1\",\"kpis\":[{\"measType\":\"UpstreamThr\",\"operation\":\"SUM\",\"operands\":\"GTP.InDataOctN3UPF\"},{\"measType\":\"DownstreamThr\",\"operation\":\"SUM\",\"operands\":\"GTP.OutDataOctN3UPF\"}]}]}", + "dmaap.server": ["message-router"] + }, + "policies": { + "items": [{ + "policyName": "onap.vfirewall.tca.1-0-0.xml", + "name": "onap.vfirewall.tca", + "config": { + "tca.policy": { + "domain": "measurementsForVfScaling", + "methodForKpi": [{ + "eventName": "perf3gpp_CORE_AMF_pmMeasResult", + "controlLoopSchemaType": "SLICE", + "policyScope": "resource=networkSlice;type=configuration", + "policyName": "configuration.dcae.microservice.pm-mapper.xml", + "policyVersion": "v0.0.1", + "kpis": [{ + "measType": "AMFRegNbr", + "operation": "SUM", + "operands": "RM.RegisteredSubNbrMean" + }] + }, + { + "eventName": "perf3gpp_AcmeNode-Acme_pmMeasResult", + "controlLoopSchemaType": "SLICE", + "policyScope": "resource=networkSlice;type=configuration", + "policyName": "configuration.dcae.microservice.pm-mapper.xml", + "policyVersion": "v0.0.1", + "kpis": [{ + "measType": "UpstreamThr", + "operation": "SUM", + "operands": "GTP.InDataOctN3UPF" + + }, + { + "measType": "DownstreamThr", + "operation": "SUM", + "operands": "GTP.OutDataOctN3UPF" + } + ] + } + ] + } + }, + "type_version": "1.0.0", + "version": "1.0.0", + "policyVersion": "1.0.0", + "type": "onap.policies.monitoring.cdap.tca.hi.lo.app", + "metadata": { + "policy-id": "onap.vfirewall.tca", + "policy-version": "1.0.0" + } + }] +} +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/test/resources/kpi/cbs_config1.json b/components/kpi-computation-ms/src/test/resources/kpi/cbs_config1.json new file mode 100644 index 00000000..bb763db1 --- /dev/null +++ b/components/kpi-computation-ms/src/test/resources/kpi/cbs_config1.json @@ -0,0 +1,38 @@ +{ + "config": { + "pollingInterval": 20, + "aafUsername": "dcae@dcae.onap.org", + "cbsPollingInterval": 60, + "mongo.host": "192.168.225.61", + "cid": "kpi-cid", + "trust_store_pass_path": "/opt/app/kpims/etc/cert/trust.pass", + "cg": "kpi-cg", + "mongo.port": 27017, + "mongo.databasename": "datalake", + "streams_subscribes": { + "performance_management_topic": { + "aaf_password": "demo123456!", + "type": "message-router", + "dmaap_info": { + "topic_url": "https://message-router.onap.svc.cluster.local:3905/events/org.onap.dmaap.mr.PERFORMANCE_MEASUREMENTS" + }, + "aaf_username": "dcae@dcae.onap.org" + } + }, + "trust_store_path": "/opt/app/kpims/etc/cert/trust.jks", + "pollingTimeout": 60, + "streams_publishes": { + "kpi_topic": { + "aaf_password": "demo123456!", + "type": "message-router", + "dmaap_info": { + "topic_url": "https://message-router.onap.svc.cluster.local:3905/events/unauthenticated.DCAE_KPI_OUTPUT" + }, + "aaf_username": "dcae@dcae.onap.org" + } + }, + "aafPassword": "demo123456!", + "kpi.policy": "{\"domain\":\"measurementsForKpi\",\"methodForKpi\":[{\"eventName\":\"perf3gpp_CORE-AMF_pmMeasResult\",\"controlLoopSchemaType\":\"SLICE\",\"policyScope\":\"resource=networkSlice;type=configuration\",\"policyName\":\"configuration.dcae.microservice.pm-mapper.xml\",\"policyVersion\":\"v0.0.1\",\"kpis\":[{\"measType\":\"AMFRegNbr\",\"operation\":\"SUM\",\"operands\":\"RM.RegisteredSubNbrMean\"}]},{\"eventName\":\"perf3gpp_AcmeNode-Acme_pmMeasResult\",\"controlLoopSchemaType\":\"SLICE\",\"policyScope\":\"resource=networkSlice;type=configuration\",\"policyName\":\"configuration.dcae.microservice.pm-mapper.xml\",\"policyVersion\":\"v0.0.1\",\"kpis\":[{\"measType\":\"UpstreamThr\",\"operation\":\"SUM\",\"operands\":\"GTP.InDataOctN3UPF\"},{\"measType\":\"DownstreamThr\",\"operation\":\"SUM\",\"operands\":\"GTP.OutDataOctN3UPF\"}]}]}", + "dmaap.server": ["message-router"] + } +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/test/resources/kpi/cbs_config2.json b/components/kpi-computation-ms/src/test/resources/kpi/cbs_config2.json new file mode 100644 index 00000000..bb763db1 --- /dev/null +++ b/components/kpi-computation-ms/src/test/resources/kpi/cbs_config2.json @@ -0,0 +1,38 @@ +{ + "config": { + "pollingInterval": 20, + "aafUsername": "dcae@dcae.onap.org", + "cbsPollingInterval": 60, + "mongo.host": "192.168.225.61", + "cid": "kpi-cid", + "trust_store_pass_path": "/opt/app/kpims/etc/cert/trust.pass", + "cg": "kpi-cg", + "mongo.port": 27017, + "mongo.databasename": "datalake", + "streams_subscribes": { + "performance_management_topic": { + "aaf_password": "demo123456!", + "type": "message-router", + "dmaap_info": { + "topic_url": "https://message-router.onap.svc.cluster.local:3905/events/org.onap.dmaap.mr.PERFORMANCE_MEASUREMENTS" + }, + "aaf_username": "dcae@dcae.onap.org" + } + }, + "trust_store_path": "/opt/app/kpims/etc/cert/trust.jks", + "pollingTimeout": 60, + "streams_publishes": { + "kpi_topic": { + "aaf_password": "demo123456!", + "type": "message-router", + "dmaap_info": { + "topic_url": "https://message-router.onap.svc.cluster.local:3905/events/unauthenticated.DCAE_KPI_OUTPUT" + }, + "aaf_username": "dcae@dcae.onap.org" + } + }, + "aafPassword": "demo123456!", + "kpi.policy": "{\"domain\":\"measurementsForKpi\",\"methodForKpi\":[{\"eventName\":\"perf3gpp_CORE-AMF_pmMeasResult\",\"controlLoopSchemaType\":\"SLICE\",\"policyScope\":\"resource=networkSlice;type=configuration\",\"policyName\":\"configuration.dcae.microservice.pm-mapper.xml\",\"policyVersion\":\"v0.0.1\",\"kpis\":[{\"measType\":\"AMFRegNbr\",\"operation\":\"SUM\",\"operands\":\"RM.RegisteredSubNbrMean\"}]},{\"eventName\":\"perf3gpp_AcmeNode-Acme_pmMeasResult\",\"controlLoopSchemaType\":\"SLICE\",\"policyScope\":\"resource=networkSlice;type=configuration\",\"policyName\":\"configuration.dcae.microservice.pm-mapper.xml\",\"policyVersion\":\"v0.0.1\",\"kpis\":[{\"measType\":\"UpstreamThr\",\"operation\":\"SUM\",\"operands\":\"GTP.InDataOctN3UPF\"},{\"measType\":\"DownstreamThr\",\"operation\":\"SUM\",\"operands\":\"GTP.OutDataOctN3UPF\"}]}]}", + "dmaap.server": ["message-router"] + } +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/test/resources/kpi/kpi_config.json b/components/kpi-computation-ms/src/test/resources/kpi/kpi_config.json new file mode 100644 index 00000000..64e426cf --- /dev/null +++ b/components/kpi-computation-ms/src/test/resources/kpi/kpi_config.json @@ -0,0 +1,35 @@ +{ + "domain": "measurementsForKpi", + "methodForKpi": [{ + "eventName": "perf3gpp_CORE_AMF_pmMeasResult", + "controlLoopSchemaType": "SLICE", + "policyScope": "resource=networkSlice;type=configuration", + "policyName": "configuration.dcae.microservice.pm-mapper.xml", + "policyVersion": "v0.0.1", + "kpis": [{ + "measType": "AMFRegNbr", + "operation": "SUM", + "operands": "RM.RegisteredSubNbrMean" + }] + }, + { + "eventName": "perf3gpp_AcmeNode-Acme_pmMeasResult", + "controlLoopSchemaType": "SLICE", + "policyScope": "resource=networkSlice;type=configuration", + "policyName": "configuration.dcae.microservice.pm-mapper.xml", + "policyVersion": "v0.0.1", + "kpis": [{ + "measType": "UpstreamThr", + "operation": "SUM", + "operands": "GTP.InDataOctN3UPF" + + }, + { + "measType": "DownstreamThr", + "operation": "SUM", + "operands": "GTP.OutDataOctN3UPF" + } + ] + } + ] +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/src/test/resources/kpi/ves_message.json b/components/kpi-computation-ms/src/test/resources/kpi/ves_message.json new file mode 100644 index 00000000..e16625d9 --- /dev/null +++ b/components/kpi-computation-ms/src/test/resources/kpi/ves_message.json @@ -0,0 +1,83 @@ +{ + "event":{ + "commonEventHeader":{ + "domain":"perf3gpp", + "eventId":"14618daf-c0ce-4ccc-9169-9e1ac79971f2", + "sequence":0, + "eventName":"perf3gpp_AcmeNode-Acme_pmMeasResult", + "sourceName":"oteNB5309", + "reportingEntityName":"", + "priority":"Normal", + "startEpochMicrosec":1591099200000, + "lastEpochMicrosec":1591100100000, + "version":"4.0", + "vesEventListenerVersion":"7.1", + "timeZoneOffset":"UTC+05:00" + }, + "perf3gppFields":{ + "perf3gppFieldsVersion":"1.0", + "measDataCollection":{ + "granularityPeriod":1591100100000, + "measuredEntityUserName":"", + "measuredEntityDn":"UPFMeasurement", + "measuredEntitySoftwareVersion":"r0.1", + "measInfoList":[ + { + "measInfoId":{ + "sMeasInfoId":"UPFFunction0" + }, + "measTypes":{ + "sMeasTypesList":[ + "GTP.InDataOctN3UPF.08_010101", + "GTP.OutDataOctN3UPF.08_010101" + ] + }, + "measValuesList":[ + { + "measObjInstId":"some measObjLdn", + "suspectFlag":"false", + "measResults":[ + { + "p":1, + "sValue":"10" + }, + { + "p":2, + "sValue":"20" + } + ] + } + ] + }, + { + "measInfoId":{ + "sMeasInfoId":"UPFFunction1" + }, + "measTypes":{ + "sMeasTypesList":[ + "GTP.InDataOctN3UPF.08_010101", + "GTP.OutDataOctN3UPF.08_010101" + ] + }, + "measValuesList":[ + { + "measObjInstId":"some measObjLdn", + "suspectFlag":"false", + "measResults":[ + { + "p":1, + "sValue":"30" + }, + { + "p":2, + "sValue":"40" + } + ] + } + ] + } + ] + } + } + } +}
\ No newline at end of file diff --git a/components/kpi-computation-ms/version.properties b/components/kpi-computation-ms/version.properties new file mode 100644 index 00000000..be08607d --- /dev/null +++ b/components/kpi-computation-ms/version.properties @@ -0,0 +1,26 @@ +############################################################################### +# ============LICENSE_START======================================================= +# kpi-ms +# ================================================================================ +# Copyright (C) 2021 China Mobile. +# ============================================================================== +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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========================================================= +# +############################################################################### +major=1 +minor=0 +patch=0 +base_version=${major}.${minor}.${patch} +release_version=${base_version} +snapshot_version=${base_version}-SNAPSHOT |