840298d486315e02a7cc406ff3bc929a17038a40
[nonrtric.git] / pmlog / src / test / java / org / oran / pmlog / Integration.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2023 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oran.pmlog;
22
23 import java.nio.charset.Charset;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.util.HashMap;
27 import java.util.Map;
28
29 import org.apache.kafka.clients.producer.ProducerConfig;
30 import org.apache.kafka.clients.producer.ProducerRecord;
31 import org.apache.kafka.common.serialization.ByteArraySerializer;
32 import org.junit.jupiter.api.AfterEach;
33 import org.junit.jupiter.api.BeforeEach;
34 import org.junit.jupiter.api.Test;
35 import org.oran.pmlog.configuration.ApplicationConfig;
36 import org.oran.pmlog.configuration.ConsumerJobInfo;
37 import org.oran.pmlog.configuration.ConsumerJobInfo.PmFilterData;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.boot.test.context.SpringBootTest;
42 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
43 import org.springframework.boot.test.context.TestConfiguration;
44 import org.springframework.boot.test.web.server.LocalServerPort;
45 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
46 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
47 import org.springframework.context.annotation.Bean;
48 import org.springframework.test.context.TestPropertySource;
49
50 import reactor.core.publisher.Flux;
51 import reactor.kafka.sender.KafkaSender;
52 import reactor.kafka.sender.SenderOptions;
53 import reactor.kafka.sender.SenderRecord;
54
55 @SuppressWarnings("java:S3577") // Rename class
56 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
57 @TestPropertySource(properties = { //
58         "server.ssl.key-store=./config/keystore.jks", //
59         "app.webclient.trust-store=./config/truststore.jks", //
60         "app.configuration-filepath=./src/test/resources/test_application_configuration.json", //
61         "app.pm-files-path=./src/test/resources/" //
62 }) //
63 class Integration {
64
65     @Autowired
66     private ApplicationConfig applicationConfig;
67
68     private static com.google.gson.Gson gson = new com.google.gson.GsonBuilder().disableHtmlEscaping().create();
69
70     private final Logger logger = LoggerFactory.getLogger(Integration.class);
71
72     @LocalServerPort
73     int localServerHttpPort;
74
75     static class TestApplicationConfig extends ApplicationConfig {
76         String thisProcessUrl() {
77             final String url = "https://localhost:" + getLocalServerHttpsPort();
78             return url;
79         }
80     }
81
82     /**
83      * Overrides the BeanFactory.
84      */
85     @TestConfiguration
86     static class TestBeanFactory extends BeanFactory {
87
88         @Override
89         @Bean
90         public ServletWebServerFactory servletContainer() {
91             return new TomcatServletWebServerFactory();
92         }
93
94         @Override
95         @Bean
96         public ApplicationConfig getApplicationConfig() {
97             TestApplicationConfig cfg = new TestApplicationConfig();
98             return cfg;
99         }
100     }
101
102     @BeforeEach
103     void init() {}
104
105     @AfterEach
106     void reset() {}
107
108     private SenderOptions<byte[], byte[]> kafkaSenderOptions() {
109         String bootstrapServers = this.applicationConfig.getKafkaBootStrapServers();
110
111         Map<String, Object> props = new HashMap<>();
112         props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
113         // props.put(ProducerConfig.CLIENT_ID_CONFIG, "sample-producerx");
114         props.put(ProducerConfig.ACKS_CONFIG, "all");
115         props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
116         props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
117         return SenderOptions.create(props);
118     }
119
120     private SenderRecord<byte[], byte[], Integer> kafkaSenderRecord(String data, String key) {
121         String topic = this.applicationConfig.getKafkaInputTopic();
122         int correlationMetadata = 2;
123         return SenderRecord.create(new ProducerRecord<>(topic, key.getBytes(), data.getBytes()), correlationMetadata);
124     }
125
126     private void sendDataToKafka(Flux<SenderRecord<byte[], byte[], Integer>> dataToSend) {
127         final KafkaSender<byte[], byte[]> sender = KafkaSender.create(kafkaSenderOptions());
128
129         sender.send(dataToSend) //
130                 .doOnError(e -> logger.error("Send failed", e)) //
131                 .blockLast();
132
133         sender.close();
134     }
135
136     @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
137     private static void waitForKafkaListener() throws InterruptedException {
138         Thread.sleep(4000);
139     }
140
141     private String generateCounterValue(int sequenceValue, int noOfObjects, String counterName, String resourceFdn) {
142         long value = (random.nextInt() % 100) * sequenceValue + (counterName.hashCode() % 5000);
143         return Long.toString(value);
144     }
145
146     static java.util.Random random = new java.util.Random(System.currentTimeMillis());
147
148     private long currentEpochMicroSeconds() {
149         return java.util.concurrent.TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
150     }
151
152     private String measType(PmReport.MeasResult measResult, PmReport.MeasInfoList measInfoList) {
153         return measInfoList.getMeasTypes().getMeasType(measResult.getP());
154     }
155
156     // Set end time. Now - (GP * sequenceValue)
157     private void setEndTime(PmReport report, int sequenceValue, int noOfObjects) {
158         long gpMicro = report.event.getPerf3gppFields().getMeasDataCollection().getGranularityPeriod() * 1000 * 1000;
159         long endTime = currentEpochMicroSeconds() - ((noOfObjects - sequenceValue - 1) * gpMicro);
160         report.event.getCommonEventHeader().setLastEpochMicrosec(endTime);
161
162     }
163
164     final String PM_REPORT_FILE_BIG = "./src/test/resources/A20000626.2315+0200-2330+0200_HTTPS-6-73.json";
165     final String PM_REPORT_FILE = "./src/test/resources/pm_report.json";
166
167     String pmReport(int sequenceValue, int noOfObjects) {
168         try {
169             String str = Files.readString(Path.of(PM_REPORT_FILE), Charset.defaultCharset());
170             PmReport report = gson.fromJson(str, PmReport.class);
171             PmReport.MeasDataCollection measDataCollection = report.event.getPerf3gppFields().getMeasDataCollection();
172
173             setEndTime(report, sequenceValue, noOfObjects);
174
175             // Fill it with generated values
176             for (PmReport.MeasInfoList measInfoList : measDataCollection.getMeasInfoList()) {
177                 for (PmReport.MeasValuesList measValueList : measInfoList.getMeasValuesList()) {
178                     for (PmReport.MeasResult measResult : measValueList.getMeasResults()) {
179                         String value = this.generateCounterValue(sequenceValue, noOfObjects,
180                                 measType(measResult, measInfoList), report.fullDistinguishedName(measValueList));
181                         measResult.setSValue(value);
182                     }
183                 }
184             }
185             return gson.toJson(report);
186         } catch (Exception e) {
187             logger.error("Could not loadPM report {}", e.getMessage(), e);
188             return null;
189         }
190
191     }
192
193     @Test
194     void testStoreReportsInflux() throws Exception {
195         final int NO_OF_OBJECTS = 24 * 4;
196         InfluxStore influxStore = new InfluxStore(this.applicationConfig);
197
198         Flux<DataFromKafkaTopic> input = Flux.range(0, NO_OF_OBJECTS) //
199                 .map(i -> pmReport(i, NO_OF_OBJECTS)) //
200                 .map(str -> new DataFromKafkaTopic(null, null, str.getBytes()));
201
202         influxStore.start(input);
203
204     }
205
206     @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
207     @Test
208     void sendPmReportsThroughKafka() throws Exception {
209         waitForKafkaListener();
210
211         final int NO_OF_OBJECTS = 20;
212
213         var dataToSend = Flux.range(0, NO_OF_OBJECTS).map(i -> kafkaSenderRecord(pmReport(i, NO_OF_OBJECTS), "key"));
214         sendDataToKafka(dataToSend);
215
216         Thread.sleep(1000 * 1000);
217     }
218
219     @Test
220     void printConfiguration() {
221         PmFilterData f = new PmFilterData();
222         f.getMeasObjInstIds().add("measObj");
223         PmFilterData.MeasTypeSpec spec = new PmFilterData.MeasTypeSpec();
224         spec.setMeasuredObjClass("measuredObjClass");
225         spec.getMeasTypes().add("measType");
226         f.getMeasTypeSpecs().add(spec);
227         f.getSourceNames().add("sourceName");
228         ConsumerJobInfo.KafkaDeliveryInfo deliveryInfo = ConsumerJobInfo.KafkaDeliveryInfo.builder() //
229                 .topic("topic").bootStrapServers("bootStrapServers") //
230                 .build();
231         ConsumerJobInfo.PmJobParameters params = ConsumerJobInfo.PmJobParameters.builder() //
232                 .filter(f) //
233                 .deliveryInfo(deliveryInfo).build();
234
235         ConsumerJobInfo info = new ConsumerJobInfo("type", params, "owner");
236         String str = gson.toJson(info);
237         System.out.print(str);
238     }
239
240     @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
241     @Test
242     void tet() throws Exception {
243         Thread.sleep(1000 * 1000);
244     }
245
246 }