Rename enrichment coordinator service to information coordinator service
[nonrtric.git] / information-coordinator-service / src / main / java / org / oransc / ics / 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.ics.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.ics.controllers.ErrorResponse;
42 import org.oransc.ics.controllers.VoidResponse;
43 import org.oransc.ics.exceptions.ServiceException;
44 import org.oransc.ics.repository.InfoJob;
45 import org.oransc.ics.repository.InfoJobs;
46 import org.oransc.ics.repository.InfoProducer;
47 import org.oransc.ics.repository.InfoProducers;
48 import org.oransc.ics.repository.InfoType;
49 import org.oransc.ics.repository.InfoTypeSubscriptions;
50 import org.oransc.ics.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 = "Input validation failed", //
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 =
153             new InfoType(infoTypeId, registrationInfo.jobDataSchema, registrationInfo.typeSpecificInformation);
154         this.infoTypes.put(newDefinition);
155         this.typeSubscriptions.notifyTypeRegistered(newDefinition);
156         return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
157     }
158
159     @DeleteMapping(
160         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
161         produces = MediaType.APPLICATION_JSON_VALUE) //
162     @Operation(summary = "Individual Information Type", description = "") //
163     @ApiResponses(
164         value = { //
165             @ApiResponse(
166                 responseCode = "200",
167                 description = "Not used", //
168                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
169             @ApiResponse(
170                 responseCode = "204",
171                 description = "Producer deleted", //
172                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
173             @ApiResponse(
174                 responseCode = "404",
175                 description = "Information type is not found", //
176                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
177             @ApiResponse(
178                 responseCode = "409",
179                 description = "The Information type has one or several active producers", //
180                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
181         })
182     public ResponseEntity<Object> deleteInfoType( //
183         @PathVariable("infoTypeId") String infoTypeId) {
184
185         InfoType type = this.infoTypes.get(infoTypeId);
186         if (type == null) {
187             return ErrorResponse.create("Information type not found", HttpStatus.NOT_FOUND);
188         }
189         if (!this.infoProducers.getProducersForType(type).isEmpty()) {
190             String firstProducerId = this.infoProducers.getProducersForType(type).iterator().next().getId();
191             return ErrorResponse.create("The type has active producers: " + firstProducerId, HttpStatus.CONFLICT);
192         }
193         this.infoTypes.remove(type);
194         infoJobs.getJobsForType(type).forEach(job -> infoJobs.remove(job, infoProducers)); // Delete jobs for the type
195         this.typeSubscriptions.notifyTypeRemoved(type);
196         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
197     }
198
199     @GetMapping(path = ProducerConsts.API_ROOT + "/info-producers", produces = MediaType.APPLICATION_JSON_VALUE)
200     @Operation(summary = "Information producer identifiers", description = "")
201     @ApiResponses(
202         value = { //
203             @ApiResponse(
204                 responseCode = "200",
205                 description = "Information producer identifiers", //
206                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))) //
207         })
208     public ResponseEntity<Object> getInfoProducerIdentifiers( //
209         @Parameter(
210             name = "info_type_id",
211             required = false,
212             description = "If given, only the producers for the EI Data type is returned.") //
213         @RequestParam(name = "info_type_id", required = false) String typeId //
214     ) {
215         List<String> result = new ArrayList<>();
216         for (InfoProducer infoProducer : typeId == null ? this.infoProducers.getAllProducers()
217             : this.infoProducers.getProducersForType(typeId)) {
218             result.add(infoProducer.getId());
219         }
220
221         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
222     }
223
224     @GetMapping(
225         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
226         produces = MediaType.APPLICATION_JSON_VALUE)
227     @Operation(summary = "Individual Information Producer", description = "")
228     @ApiResponses(
229         value = { //
230             @ApiResponse(
231                 responseCode = "200",
232                 description = "Information producer", //
233                 content = @Content(schema = @Schema(implementation = ProducerRegistrationInfo.class))), //
234             @ApiResponse(
235                 responseCode = "404",
236                 description = "Information producer is not found", //
237                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
238         })
239     public ResponseEntity<Object> getInfoProducer( //
240         @PathVariable("infoProducerId") String infoProducerId) {
241         try {
242             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
243             ProducerRegistrationInfo info = toProducerRegistrationInfo(producer);
244             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
245         } catch (Exception e) {
246             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
247         }
248     }
249
250     @GetMapping(
251         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/info-jobs",
252         produces = MediaType.APPLICATION_JSON_VALUE)
253     @Operation(
254         summary = "Information Job definitions",
255         description = "Information Job definitions for one Information Producer")
256     @ApiResponses(
257         value = { //
258             @ApiResponse(
259                 responseCode = "404",
260                 description = "Information producer is not found", //
261                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
262             @ApiResponse(
263                 responseCode = "200",
264                 description = "Information producer", //
265                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProducerJobInfo.class)))), //
266         })
267     public ResponseEntity<Object> getInfoProducerJobs( //
268         @PathVariable("infoProducerId") String infoProducerId) {
269         try {
270             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
271             Collection<ProducerJobInfo> producerJobs = new ArrayList<>();
272             for (InfoType type : producer.getInfoTypes()) {
273                 for (InfoJob infoJob : this.infoJobs.getJobsForType(type)) {
274                     ProducerJobInfo request = new ProducerJobInfo(infoJob);
275                     producerJobs.add(request);
276                 }
277             }
278
279             return new ResponseEntity<>(gson.toJson(producerJobs), HttpStatus.OK);
280         } catch (Exception e) {
281             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
282         }
283     }
284
285     @GetMapping(
286         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/status",
287         produces = MediaType.APPLICATION_JSON_VALUE) //
288     @Operation(summary = "Information producer status") //
289     @ApiResponses(
290         value = { //
291             @ApiResponse(
292                 responseCode = "200",
293                 description = "Information producer status", //
294                 content = @Content(schema = @Schema(implementation = ProducerStatusInfo.class))), //
295             @ApiResponse(
296                 responseCode = "404",
297                 description = "Information producer is not found", //
298                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
299         })
300     public ResponseEntity<Object> getInfoProducerStatus( //
301         @PathVariable("infoProducerId") String infoProducerId) {
302         try {
303             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
304             return new ResponseEntity<>(gson.toJson(producerStatusInfo(producer)), HttpStatus.OK);
305         } catch (Exception e) {
306             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
307         }
308     }
309
310     private ProducerStatusInfo producerStatusInfo(InfoProducer producer) {
311         var opState = producer.isAvailable() ? ProducerStatusInfo.OperationalState.ENABLED
312             : ProducerStatusInfo.OperationalState.DISABLED;
313         return new ProducerStatusInfo(opState);
314     }
315
316     @PutMapping(
317         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}", //
318         produces = MediaType.APPLICATION_JSON_VALUE)
319     @Operation(summary = "Individual Information Producer", description = "")
320     @ApiResponses(
321         value = { //
322             @ApiResponse(
323                 responseCode = "201",
324                 description = "Producer created", //
325                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
326             @ApiResponse(
327                 responseCode = "200",
328                 description = "Producer updated", //
329                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
330             @ApiResponse(
331                 responseCode = "404",
332                 description = "Producer type not found", //
333                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
334             @ApiResponse(
335                 responseCode = "400",
336                 description = "Input validation failed", //
337                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
338         })
339     public ResponseEntity<Object> putInfoProducer( //
340         @PathVariable("infoProducerId") String infoProducerId, //
341         @RequestBody ProducerRegistrationInfo registrationInfo) {
342         try {
343             validateUri(registrationInfo.jobCallbackUrl);
344             validateUri(registrationInfo.producerSupervisionCallbackUrl);
345             InfoProducer previousDefinition = this.infoProducers.get(infoProducerId);
346             this.infoProducers.registerProducer(toProducerRegistrationInfo(infoProducerId, registrationInfo));
347             return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
348         } catch (ServiceException e) {
349             return ErrorResponse.create(e, e.getHttpStatus());
350         }
351     }
352
353     private void validateUri(String url) throws ServiceException {
354         if (url != null && !url.isEmpty()) {
355             try {
356                 URI uri = new URI(url);
357                 if (!uri.isAbsolute()) {
358                     throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.BAD_REQUEST);
359                 }
360             } catch (URISyntaxException e) {
361                 throw new ServiceException(e.getMessage(), HttpStatus.BAD_REQUEST);
362             }
363         } else {
364             throw new ServiceException("Missing required URL", HttpStatus.BAD_REQUEST);
365         }
366     }
367
368     @DeleteMapping(
369         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
370         produces = MediaType.APPLICATION_JSON_VALUE)
371     @Operation(summary = "Individual Information Producer", description = "")
372     @ApiResponses(
373         value = { //
374             @ApiResponse(
375                 responseCode = "200",
376                 description = "Not used", //
377                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
378             @ApiResponse(
379                 responseCode = "204",
380                 description = "Producer deleted", //
381                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
382             @ApiResponse(
383                 responseCode = "404",
384                 description = "Producer is not found", //
385                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
386         })
387     public ResponseEntity<Object> deleteInfoProducer(@PathVariable("infoProducerId") String infoProducerId) {
388         try {
389             final InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
390             this.infoProducers.deregisterProducer(producer);
391             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
392         } catch (ServiceException e) {
393             return ErrorResponse.create(e, e.getHttpStatus());
394         }
395     }
396
397     private ProducerRegistrationInfo toProducerRegistrationInfo(InfoProducer p) {
398         Collection<String> types = new ArrayList<>();
399         for (InfoType type : p.getInfoTypes()) {
400             types.add(type.getId());
401         }
402         return new ProducerRegistrationInfo(types, p.getJobCallbackUrl(), p.getProducerSupervisionCallbackUrl());
403     }
404
405     private ProducerInfoTypeInfo toInfoTypeInfo(InfoType t) {
406         return new ProducerInfoTypeInfo(t.getJobDataSchema(), t.getTypeSpecificInfo());
407     }
408
409     private InfoProducers.InfoProducerRegistrationInfo toProducerRegistrationInfo(String infoProducerId,
410         ProducerRegistrationInfo info) throws ServiceException {
411         Collection<InfoType> supportedTypes = new ArrayList<>();
412         for (String typeId : info.supportedTypeIds) {
413             InfoType type = this.infoTypes.getType(typeId);
414             supportedTypes.add(type);
415         }
416
417         return InfoProducers.InfoProducerRegistrationInfo.builder() //
418             .id(infoProducerId) //
419             .jobCallbackUrl(info.jobCallbackUrl) //
420             .producerSupervisionCallbackUrl(info.producerSupervisionCallbackUrl) //
421             .supportedTypes(supportedTypes) //
422             .build();
423     }
424 }