ECS, deleting jobs when the type is deleted
[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         infoJobs.getJobsForType(type).forEach(job -> infoJobs.remove(job, infoProducers)); // Delete jobs for the type
194         this.typeSubscriptions.notifyTypeRemoved(type);
195         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
196     }
197
198     @GetMapping(path = ProducerConsts.API_ROOT + "/info-producers", produces = MediaType.APPLICATION_JSON_VALUE)
199     @Operation(summary = "Information producer identifiers", description = "")
200     @ApiResponses(
201         value = { //
202             @ApiResponse(
203                 responseCode = "200",
204                 description = "Information producer identifiers", //
205                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))) //
206         })
207     public ResponseEntity<Object> getInfoProducerIdentifiers( //
208         @Parameter(
209             name = "info_type_id",
210             required = false,
211             description = "If given, only the producers for the EI Data type is returned.") //
212         @RequestParam(name = "info_type_id", required = false) String typeId //
213     ) {
214         List<String> result = new ArrayList<>();
215         for (InfoProducer infoProducer : typeId == null ? this.infoProducers.getAllProducers()
216             : this.infoProducers.getProducersForType(typeId)) {
217             result.add(infoProducer.getId());
218         }
219
220         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
221     }
222
223     @GetMapping(
224         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
225         produces = MediaType.APPLICATION_JSON_VALUE)
226     @Operation(summary = "Individual Information Producer", description = "")
227     @ApiResponses(
228         value = { //
229             @ApiResponse(
230                 responseCode = "200",
231                 description = "Information producer", //
232                 content = @Content(schema = @Schema(implementation = ProducerRegistrationInfo.class))), //
233             @ApiResponse(
234                 responseCode = "404",
235                 description = "Information producer is not found", //
236                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
237         })
238     public ResponseEntity<Object> getInfoProducer( //
239         @PathVariable("infoProducerId") String infoProducerId) {
240         try {
241             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
242             ProducerRegistrationInfo info = toProducerRegistrationInfo(producer);
243             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
244         } catch (Exception e) {
245             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
246         }
247     }
248
249     @GetMapping(
250         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/info-jobs",
251         produces = MediaType.APPLICATION_JSON_VALUE)
252     @Operation(
253         summary = "Information Job definitions",
254         description = "Information Job definitions for one Information Producer")
255     @ApiResponses(
256         value = { //
257             @ApiResponse(
258                 responseCode = "404",
259                 description = "Information producer is not found", //
260                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
261             @ApiResponse(
262                 responseCode = "200",
263                 description = "Information producer", //
264                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProducerJobInfo.class)))), //
265         })
266     public ResponseEntity<Object> getInfoProducerJobs( //
267         @PathVariable("infoProducerId") String infoProducerId) {
268         try {
269             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
270             Collection<ProducerJobInfo> producerJobs = new ArrayList<>();
271             for (InfoType type : producer.getInfoTypes()) {
272                 for (InfoJob infoJob : this.infoJobs.getJobsForType(type)) {
273                     ProducerJobInfo request = new ProducerJobInfo(infoJob);
274                     producerJobs.add(request);
275                 }
276             }
277
278             return new ResponseEntity<>(gson.toJson(producerJobs), HttpStatus.OK);
279         } catch (Exception e) {
280             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
281         }
282     }
283
284     @GetMapping(
285         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/status",
286         produces = MediaType.APPLICATION_JSON_VALUE) //
287     @Operation(summary = "Information producer status") //
288     @ApiResponses(
289         value = { //
290             @ApiResponse(
291                 responseCode = "200",
292                 description = "Information producer status", //
293                 content = @Content(schema = @Schema(implementation = ProducerStatusInfo.class))), //
294             @ApiResponse(
295                 responseCode = "404",
296                 description = "Information producer is not found", //
297                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
298         })
299     public ResponseEntity<Object> getInfoProducerStatus( //
300         @PathVariable("infoProducerId") String infoProducerId) {
301         try {
302             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
303             return new ResponseEntity<>(gson.toJson(producerStatusInfo(producer)), HttpStatus.OK);
304         } catch (Exception e) {
305             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
306         }
307     }
308
309     private ProducerStatusInfo producerStatusInfo(InfoProducer producer) {
310         var opState = producer.isAvailable() ? ProducerStatusInfo.OperationalState.ENABLED
311             : ProducerStatusInfo.OperationalState.DISABLED;
312         return new ProducerStatusInfo(opState);
313     }
314
315     @PutMapping(
316         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}", //
317         produces = MediaType.APPLICATION_JSON_VALUE)
318     @Operation(summary = "Individual Information Producer", description = "")
319     @ApiResponses(
320         value = { //
321             @ApiResponse(
322                 responseCode = "201",
323                 description = "Producer created", //
324                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
325             @ApiResponse(
326                 responseCode = "200",
327                 description = "Producer updated", //
328                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
329             @ApiResponse(
330                 responseCode = "404",
331                 description = "Producer not found", //
332                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
333         })
334     public ResponseEntity<Object> putInfoProducer( //
335         @PathVariable("infoProducerId") String infoProducerId, //
336         @RequestBody ProducerRegistrationInfo registrationInfo) {
337         try {
338             validateUri(registrationInfo.jobCallbackUrl);
339             validateUri(registrationInfo.producerSupervisionCallbackUrl);
340             InfoProducer previousDefinition = this.infoProducers.get(infoProducerId);
341             this.infoProducers.registerProducer(toProducerRegistrationInfo(infoProducerId, registrationInfo));
342             return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
343         } catch (Exception e) {
344             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
345         }
346     }
347
348     private void validateUri(String url) throws URISyntaxException, ServiceException {
349         if (url != null && !url.isEmpty()) {
350             URI uri = new URI(url);
351             if (!uri.isAbsolute()) {
352                 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
353             }
354         } else {
355             throw new ServiceException("Missing required URL", HttpStatus.CONFLICT);
356         }
357     }
358
359     @DeleteMapping(
360         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
361         produces = MediaType.APPLICATION_JSON_VALUE)
362     @Operation(summary = "Individual Information Producer", description = "")
363     @ApiResponses(
364         value = { //
365             @ApiResponse(
366                 responseCode = "200",
367                 description = "Not used", //
368                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
369             @ApiResponse(
370                 responseCode = "204",
371                 description = "Producer deleted", //
372                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
373             @ApiResponse(
374                 responseCode = "404",
375                 description = "Producer is not found", //
376                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
377         })
378     public ResponseEntity<Object> deleteInfoProducer(@PathVariable("infoProducerId") String infoProducerId) {
379         try {
380             final InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
381             this.infoProducers.deregisterProducer(producer);
382             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
383         } catch (Exception e) {
384             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
385         }
386     }
387
388     private ProducerRegistrationInfo toProducerRegistrationInfo(InfoProducer p) {
389         Collection<String> types = new ArrayList<>();
390         for (InfoType type : p.getInfoTypes()) {
391             types.add(type.getId());
392         }
393         return new ProducerRegistrationInfo(types, p.getJobCallbackUrl(), p.getProducerSupervisionCallbackUrl());
394     }
395
396     private ProducerInfoTypeInfo toInfoTypeInfo(InfoType t) {
397         return new ProducerInfoTypeInfo(t.getJobDataSchema());
398     }
399
400     private InfoProducers.InfoProducerRegistrationInfo toProducerRegistrationInfo(String infoProducerId,
401         ProducerRegistrationInfo info) throws ServiceException {
402         Collection<InfoType> supportedTypes = new ArrayList<>();
403         for (String typeId : info.supportedTypeIds) {
404             InfoType type = this.infoTypes.getType(typeId);
405             supportedTypes.add(type);
406         }
407
408         return InfoProducers.InfoProducerRegistrationInfo.builder() //
409             .id(infoProducerId) //
410             .jobCallbackUrl(info.jobCallbackUrl) //
411             .producerSupervisionCallbackUrl(info.producerSupervisionCallbackUrl) //
412             .supportedTypes(supportedTypes) //
413             .build();
414     }
415 }