ECS, support for notification of available information types
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / controllers / r1producer / ProducerController.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 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.oransc.enrichment.controllers.r1producer;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.ArraySchema;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.responses.ApiResponses;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34
35 import java.net.URI;
36 import java.net.URISyntaxException;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.List;
40
41 import org.oransc.enrichment.controllers.ErrorResponse;
42 import org.oransc.enrichment.controllers.VoidResponse;
43 import org.oransc.enrichment.exceptions.ServiceException;
44 import org.oransc.enrichment.repository.InfoJob;
45 import org.oransc.enrichment.repository.InfoJobs;
46 import org.oransc.enrichment.repository.InfoProducer;
47 import org.oransc.enrichment.repository.InfoProducers;
48 import org.oransc.enrichment.repository.InfoType;
49 import org.oransc.enrichment.repository.InfoTypeSubscriptions;
50 import org.oransc.enrichment.repository.InfoTypes;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.http.MediaType;
54 import org.springframework.http.ResponseEntity;
55 import org.springframework.web.bind.annotation.DeleteMapping;
56 import org.springframework.web.bind.annotation.GetMapping;
57 import org.springframework.web.bind.annotation.PathVariable;
58 import org.springframework.web.bind.annotation.PutMapping;
59 import org.springframework.web.bind.annotation.RequestBody;
60 import org.springframework.web.bind.annotation.RequestParam;
61 import org.springframework.web.bind.annotation.RestController;
62
63 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
64 @RestController("Producer registry")
65 @Tag(name = ProducerConsts.PRODUCER_API_NAME)
66 public class ProducerController {
67
68     private static Gson gson = new GsonBuilder().create();
69
70     @Autowired
71     private InfoJobs infoJobs;
72
73     @Autowired
74     private InfoTypes infoTypes;
75
76     @Autowired
77     private InfoProducers infoProducers;
78
79     @Autowired
80     private InfoTypeSubscriptions typeSubscriptions;
81
82     @GetMapping(path = ProducerConsts.API_ROOT + "/info-types", produces = MediaType.APPLICATION_JSON_VALUE) //
83     @Operation(summary = "Info Type identifiers", description = "") //
84     @ApiResponses(
85         value = { //
86             @ApiResponse(
87                 responseCode = "200",
88                 description = "Info Type identifiers", //
89                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))) //
90         })
91     public ResponseEntity<Object> getInfoTypdentifiers( //
92     ) {
93         List<String> result = new ArrayList<>();
94         for (InfoType infoType : this.infoTypes.getAllInfoTypes()) {
95             result.add(infoType.getId());
96         }
97
98         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
99     }
100
101     @GetMapping(
102         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
103         produces = MediaType.APPLICATION_JSON_VALUE)
104     @Operation(summary = "Individual Information Type", description = "")
105     @ApiResponses(
106         value = { //
107             @ApiResponse(
108                 responseCode = "200",
109                 description = "Info Type", //
110                 content = @Content(schema = @Schema(implementation = ProducerInfoTypeInfo.class))), //
111             @ApiResponse(
112                 responseCode = "404",
113                 description = "Information type is not found", //
114                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))})
115     public ResponseEntity<Object> getInfoType( //
116         @PathVariable("infoTypeId") String infoTypeId) {
117         try {
118             InfoType t = this.infoTypes.getType(infoTypeId);
119             ProducerInfoTypeInfo info = toInfoTypeInfo(t);
120             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
121         } catch (Exception e) {
122             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
123         }
124     }
125
126     @PutMapping(
127         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
128         produces = MediaType.APPLICATION_JSON_VALUE)
129     @ApiResponses(
130         value = { //
131             @ApiResponse(
132                 responseCode = "200",
133                 description = "Type updated", //
134                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
135             @ApiResponse(
136                 responseCode = "201",
137                 description = "Type created", //
138                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
139             @ApiResponse(
140                 responseCode = "400",
141                 description = "Bad request", //
142                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))})
143     @Operation(summary = "Individual Information Type", description = "")
144     public ResponseEntity<Object> putInfoType( //
145         @PathVariable("infoTypeId") String infoTypeId, //
146         @RequestBody ProducerInfoTypeInfo registrationInfo) {
147
148         InfoType previousDefinition = this.infoTypes.get(infoTypeId);
149         if (registrationInfo.jobDataSchema == null) {
150             return ErrorResponse.create("No schema provided", HttpStatus.BAD_REQUEST);
151         }
152         InfoType newDefinition = new InfoType(infoTypeId, registrationInfo.jobDataSchema);
153         this.infoTypes.put(newDefinition);
154         this.typeSubscriptions.notifyTypeRegistered(newDefinition);
155         return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
156     }
157
158     @DeleteMapping(
159         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
160         produces = MediaType.APPLICATION_JSON_VALUE) //
161     @Operation(summary = "Individual Information Type", description = "") //
162     @ApiResponses(
163         value = { //
164             @ApiResponse(
165                 responseCode = "200",
166                 description = "Not used", //
167                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
168             @ApiResponse(
169                 responseCode = "204",
170                 description = "Producer deleted", //
171                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
172             @ApiResponse(
173                 responseCode = "404",
174                 description = "Information type is not found", //
175                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
176             @ApiResponse(
177                 responseCode = "406",
178                 description = "The Information type has one or several active producers", //
179                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
180         })
181     public ResponseEntity<Object> deleteInfoType( //
182         @PathVariable("infoTypeId") String infoTypeId) {
183
184         InfoType type = this.infoTypes.get(infoTypeId);
185         if (type == null) {
186             return ErrorResponse.create("Information type not found", HttpStatus.NOT_FOUND);
187         }
188         if (!this.infoProducers.getProducersForType(type).isEmpty()) {
189             String firstProducerId = this.infoProducers.getProducersForType(type).iterator().next().getId();
190             return ErrorResponse.create("The type has active producers: " + firstProducerId, HttpStatus.NOT_ACCEPTABLE);
191         }
192         this.infoTypes.remove(type);
193         this.typeSubscriptions.notifyTypeRemoved(type);
194         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
195     }
196
197     @GetMapping(path = ProducerConsts.API_ROOT + "/info-producers", produces = MediaType.APPLICATION_JSON_VALUE)
198     @Operation(summary = "Information producer identifiers", description = "")
199     @ApiResponses(
200         value = { //
201             @ApiResponse(
202                 responseCode = "200",
203                 description = "Information producer identifiers", //
204                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))) //
205         })
206     public ResponseEntity<Object> getInfoProducerIdentifiers( //
207         @Parameter(
208             name = "info_type_id",
209             required = false,
210             description = "If given, only the producers for the EI Data type is returned.") //
211         @RequestParam(name = "info_type_id", required = false) String typeId //
212     ) {
213         List<String> result = new ArrayList<>();
214         for (InfoProducer infoProducer : typeId == null ? this.infoProducers.getAllProducers()
215             : this.infoProducers.getProducersForType(typeId)) {
216             result.add(infoProducer.getId());
217         }
218
219         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
220     }
221
222     @GetMapping(
223         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
224         produces = MediaType.APPLICATION_JSON_VALUE)
225     @Operation(summary = "Individual Information Producer", description = "")
226     @ApiResponses(
227         value = { //
228             @ApiResponse(
229                 responseCode = "200",
230                 description = "Information producer", //
231                 content = @Content(schema = @Schema(implementation = ProducerRegistrationInfo.class))), //
232             @ApiResponse(
233                 responseCode = "404",
234                 description = "Information producer is not found", //
235                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
236         })
237     public ResponseEntity<Object> getInfoProducer( //
238         @PathVariable("infoProducerId") String infoProducerId) {
239         try {
240             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
241             ProducerRegistrationInfo info = toProducerRegistrationInfo(producer);
242             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
243         } catch (Exception e) {
244             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
245         }
246     }
247
248     @GetMapping(
249         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/info-jobs",
250         produces = MediaType.APPLICATION_JSON_VALUE)
251     @Operation(
252         summary = "Information Job definitions",
253         description = "Information Job definitions for one Information Producer")
254     @ApiResponses(
255         value = { //
256             @ApiResponse(
257                 responseCode = "404",
258                 description = "Information producer is not found", //
259                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
260             @ApiResponse(
261                 responseCode = "200",
262                 description = "Information producer", //
263                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProducerJobInfo.class)))), //
264         })
265     public ResponseEntity<Object> getInfoProducerJobs( //
266         @PathVariable("infoProducerId") String infoProducerId) {
267         try {
268             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
269             Collection<ProducerJobInfo> producerJobs = new ArrayList<>();
270             for (InfoType type : producer.getInfoTypes()) {
271                 for (InfoJob infoJob : this.infoJobs.getJobsForType(type)) {
272                     ProducerJobInfo request = new ProducerJobInfo(infoJob);
273                     producerJobs.add(request);
274                 }
275             }
276
277             return new ResponseEntity<>(gson.toJson(producerJobs), HttpStatus.OK);
278         } catch (Exception e) {
279             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
280         }
281     }
282
283     @GetMapping(
284         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/status",
285         produces = MediaType.APPLICATION_JSON_VALUE) //
286     @Operation(summary = "Information producer status") //
287     @ApiResponses(
288         value = { //
289             @ApiResponse(
290                 responseCode = "200",
291                 description = "Information producer status", //
292                 content = @Content(schema = @Schema(implementation = ProducerStatusInfo.class))), //
293             @ApiResponse(
294                 responseCode = "404",
295                 description = "Information producer is not found", //
296                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
297         })
298     public ResponseEntity<Object> getInfoProducerStatus( //
299         @PathVariable("infoProducerId") String infoProducerId) {
300         try {
301             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
302             return new ResponseEntity<>(gson.toJson(producerStatusInfo(producer)), HttpStatus.OK);
303         } catch (Exception e) {
304             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
305         }
306     }
307
308     private ProducerStatusInfo producerStatusInfo(InfoProducer producer) {
309         var opState = producer.isAvailable() ? ProducerStatusInfo.OperationalState.ENABLED
310             : ProducerStatusInfo.OperationalState.DISABLED;
311         return new ProducerStatusInfo(opState);
312     }
313
314     @PutMapping(
315         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}", //
316         produces = MediaType.APPLICATION_JSON_VALUE)
317     @Operation(summary = "Individual Information Producer", description = "")
318     @ApiResponses(
319         value = { //
320             @ApiResponse(
321                 responseCode = "201",
322                 description = "Producer created", //
323                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
324             @ApiResponse(
325                 responseCode = "200",
326                 description = "Producer updated", //
327                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
328             @ApiResponse(
329                 responseCode = "404",
330                 description = "Producer not found", //
331                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
332         })
333     public ResponseEntity<Object> putInfoProducer( //
334         @PathVariable("infoProducerId") String infoProducerId, //
335         @RequestBody ProducerRegistrationInfo registrationInfo) {
336         try {
337             validateUri(registrationInfo.jobCallbackUrl);
338             validateUri(registrationInfo.producerSupervisionCallbackUrl);
339             InfoProducer previousDefinition = this.infoProducers.get(infoProducerId);
340             this.infoProducers.registerProducer(toProducerRegistrationInfo(infoProducerId, registrationInfo));
341             return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
342         } catch (Exception e) {
343             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
344         }
345     }
346
347     private void validateUri(String url) throws URISyntaxException, ServiceException {
348         if (url != null && !url.isEmpty()) {
349             URI uri = new URI(url);
350             if (!uri.isAbsolute()) {
351                 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
352             }
353         } else {
354             throw new ServiceException("Missing required URL", HttpStatus.CONFLICT);
355         }
356     }
357
358     @DeleteMapping(
359         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
360         produces = MediaType.APPLICATION_JSON_VALUE)
361     @Operation(summary = "Individual Information Producer", description = "")
362     @ApiResponses(
363         value = { //
364             @ApiResponse(
365                 responseCode = "200",
366                 description = "Not used", //
367                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
368             @ApiResponse(
369                 responseCode = "204",
370                 description = "Producer deleted", //
371                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
372             @ApiResponse(
373                 responseCode = "404",
374                 description = "Producer is not found", //
375                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
376         })
377     public ResponseEntity<Object> deleteInfoProducer(@PathVariable("infoProducerId") String infoProducerId) {
378         try {
379             final InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
380             this.infoProducers.deregisterProducer(producer);
381             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
382         } catch (Exception e) {
383             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
384         }
385     }
386
387     private ProducerRegistrationInfo toProducerRegistrationInfo(InfoProducer p) {
388         Collection<String> types = new ArrayList<>();
389         for (InfoType type : p.getInfoTypes()) {
390             types.add(type.getId());
391         }
392         return new ProducerRegistrationInfo(types, p.getJobCallbackUrl(), p.getProducerSupervisionCallbackUrl());
393     }
394
395     private ProducerInfoTypeInfo toInfoTypeInfo(InfoType t) {
396         return new ProducerInfoTypeInfo(t.getJobDataSchema());
397     }
398
399     private InfoProducers.InfoProducerRegistrationInfo toProducerRegistrationInfo(String infoProducerId,
400         ProducerRegistrationInfo info) throws ServiceException {
401         Collection<InfoType> supportedTypes = new ArrayList<>();
402         for (String typeId : info.supportedTypeIds) {
403             InfoType type = this.infoTypes.getType(typeId);
404             supportedTypes.add(type);
405         }
406
407         return InfoProducers.InfoProducerRegistrationInfo.builder() //
408             .id(infoProducerId) //
409             .jobCallbackUrl(info.jobCallbackUrl) //
410             .producerSupervisionCallbackUrl(info.producerSupervisionCallbackUrl) //
411             .supportedTypes(supportedTypes) //
412             .build();
413     }
414 }