NONRTRIC - Implement DMaaP mediator producer service in Java
[nonrtric.git] / dmaap-adaptor-java / src / main / java / org / oran / dmaapadapter / tasks / ProducerRegstrationTask.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 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.dmaapadapter.tasks;
22
23 import com.google.common.io.CharStreams;
24 import com.google.gson.JsonParser;
25
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.nio.charset.StandardCharsets;
30
31 import lombok.Getter;
32
33 import org.oran.dmaapadapter.clients.AsyncRestClient;
34 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
35 import org.oran.dmaapadapter.configuration.ApplicationConfig;
36 import org.oran.dmaapadapter.controllers.ProducerCallbacksController;
37 import org.oran.dmaapadapter.exceptions.ServiceException;
38 import org.oran.dmaapadapter.r1.ProducerInfoTypeInfo;
39 import org.oran.dmaapadapter.r1.ProducerRegistrationInfo;
40 import org.oran.dmaapadapter.repository.InfoType;
41 import org.oran.dmaapadapter.repository.InfoTypes;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.scheduling.annotation.EnableScheduling;
46 import org.springframework.scheduling.annotation.Scheduled;
47 import org.springframework.stereotype.Component;
48
49 import reactor.core.publisher.Flux;
50 import reactor.core.publisher.Mono;
51
52 /**
53  * Registers the types and this producer in Innformation Coordinator Service.
54  * This is done when needed.
55  */
56 @Component
57 @EnableScheduling
58 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
59 public class ProducerRegstrationTask {
60
61     private static final Logger logger = LoggerFactory.getLogger(ProducerRegstrationTask.class);
62     private final AsyncRestClient restClient;
63     private final ApplicationConfig applicationConfig;
64     private final InfoTypes types;
65     private static com.google.gson.Gson gson = new com.google.gson.GsonBuilder().create();
66
67     private static final String PRODUCER_ID = "DmaapGenericInfoProducer";
68     @Getter
69     private boolean isRegisteredInIcs = false;
70     private static final int REGISTRATION_SUPERVISION_INTERVAL_MS = 1000 * 5;
71
72     public ProducerRegstrationTask(@Autowired ApplicationConfig applicationConfig, @Autowired InfoTypes types) {
73         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
74         this.restClient = restClientFactory.createRestClientNoHttpProxy("");
75         this.applicationConfig = applicationConfig;
76         this.types = types;
77     }
78
79     @Scheduled(fixedRate = REGISTRATION_SUPERVISION_INTERVAL_MS)
80     public void supervisionTask() {
81         checkRegistration() //
82                 .filter(isRegistrationOk -> !isRegistrationOk || !this.isRegisteredInIcs) //
83                 .flatMap(isRegisterred -> registerTypesAndProducer()) //
84                 .subscribe( //
85                         null, //
86                         this::handleRegistrationFailure, //
87                         this::handleRegistrationCompleted);
88     }
89
90     private void handleRegistrationCompleted() {
91         isRegisteredInIcs = true;
92     }
93
94     private void handleRegistrationFailure(Throwable t) {
95         logger.warn("Registration of producer failed {}", t.getMessage());
96     }
97
98     // Returns TRUE if registration is correct
99     private Mono<Boolean> checkRegistration() {
100         final String url = applicationConfig.getIcsBaseUrl() + "/data-producer/v1/info-producers/" + PRODUCER_ID;
101         return restClient.get(url) //
102                 .flatMap(this::isRegisterredInfoCorrect) //
103                 .onErrorResume(t -> Mono.just(Boolean.FALSE));
104     }
105
106     private Mono<Boolean> isRegisterredInfoCorrect(String registerredInfoStr) {
107         ProducerRegistrationInfo registerredInfo = gson.fromJson(registerredInfoStr, ProducerRegistrationInfo.class);
108         if (isEqual(producerRegistrationInfo(), registerredInfo)) {
109             logger.trace("Already registered in ICS");
110             return Mono.just(Boolean.TRUE);
111         } else {
112             return Mono.just(Boolean.FALSE);
113         }
114     }
115
116     private String registerTypeUrl(InfoType type) {
117         return applicationConfig.getIcsBaseUrl() + "/data-producer/v1/info-types/" + type.getId();
118     }
119
120     private Mono<String> registerTypesAndProducer() {
121         final int CONCURRENCY = 20;
122         final String producerUrl =
123                 applicationConfig.getIcsBaseUrl() + "/data-producer/v1/info-producers/" + PRODUCER_ID;
124
125         return Flux.fromIterable(this.types.getAll()) //
126                 .doOnNext(type -> logger.info("Registering type {}", type.getId())) //
127                 .flatMap(type -> restClient.put(registerTypeUrl(type), gson.toJson(typeRegistrationInfo(type))),
128                         CONCURRENCY) //
129                 .collectList() //
130                 .doOnNext(type -> logger.info("Registering producer")) //
131                 .flatMap(resp -> restClient.put(producerUrl, gson.toJson(producerRegistrationInfo())));
132     }
133
134     private Object typeSpecifcInfoObject() {
135         return jsonObject("{}");
136     }
137
138     private ProducerInfoTypeInfo typeRegistrationInfo(InfoType type) {
139         try {
140             return new ProducerInfoTypeInfo(jsonSchemaObject(type), typeSpecifcInfoObject());
141         } catch (Exception e) {
142             logger.error("Fatal error {}", e.getMessage());
143             return null;
144         }
145     }
146
147     private Object jsonSchemaObject(InfoType type) throws IOException, ServiceException {
148         String schemaFile = type.isKafkaTopicDefined() ? "/typeSchemaKafka.json" : "/typeSchemaDmaap.json";
149         return jsonObject(readSchemaFile(schemaFile));
150     }
151
152     private String readSchemaFile(String filePath) throws IOException, ServiceException {
153         InputStream in = getClass().getResourceAsStream(filePath);
154         logger.debug("Reading application schema file from: {} with: {}", filePath, in);
155         if (in == null) {
156             throw new ServiceException("Could not readfile: " + filePath);
157         }
158         return CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
159     }
160
161     @SuppressWarnings("java:S2139") // Log exception
162     private Object jsonObject(String json) {
163         try {
164             return JsonParser.parseString(json).getAsJsonObject();
165         } catch (Exception e) {
166             logger.error("Bug, error in JSON: {} {}", json, e.getMessage());
167             throw new NullPointerException(e.getMessage());
168         }
169     }
170
171     private boolean isEqual(ProducerRegistrationInfo a, ProducerRegistrationInfo b) {
172         return a.jobCallbackUrl.equals(b.jobCallbackUrl) //
173                 && a.producerSupervisionCallbackUrl.equals(b.producerSupervisionCallbackUrl) //
174                 && a.supportedTypeIds.size() == b.supportedTypeIds.size();
175     }
176
177     private ProducerRegistrationInfo producerRegistrationInfo() {
178         return ProducerRegistrationInfo.builder() //
179                 .jobCallbackUrl(baseUrl() + ProducerCallbacksController.JOB_URL) //
180                 .producerSupervisionCallbackUrl(baseUrl() + ProducerCallbacksController.SUPERVISION_URL) //
181                 .supportedTypeIds(this.types.typeIds()) //
182                 .build();
183     }
184
185     private String baseUrl() {
186         return this.applicationConfig.getSelfUrl();
187     }
188 }