Added support for EiJob status
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / controllers / consumer / ConsumerController.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.consumer;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26
27 import io.swagger.annotations.Api;
28 import io.swagger.annotations.ApiOperation;
29 import io.swagger.annotations.ApiParam;
30 import io.swagger.annotations.ApiResponse;
31 import io.swagger.annotations.ApiResponses;
32
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
36 import java.util.Vector;
37
38 import org.everit.json.schema.Schema;
39 import org.everit.json.schema.loader.SchemaLoader;
40 import org.json.JSONObject;
41 import org.oransc.enrichment.configuration.ApplicationConfig;
42 import org.oransc.enrichment.controllers.ErrorResponse;
43 import org.oransc.enrichment.controllers.VoidResponse;
44 import org.oransc.enrichment.controllers.producer.ProducerCallbacks;
45 import org.oransc.enrichment.exceptions.ServiceException;
46 import org.oransc.enrichment.repository.EiJob;
47 import org.oransc.enrichment.repository.EiJobs;
48 import org.oransc.enrichment.repository.EiProducer;
49 import org.oransc.enrichment.repository.EiType;
50 import org.oransc.enrichment.repository.EiTypes;
51 import org.oransc.enrichment.repository.ImmutableEiJob;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.http.HttpStatus;
54 import org.springframework.http.MediaType;
55 import org.springframework.http.ResponseEntity;
56 import org.springframework.web.bind.annotation.DeleteMapping;
57 import org.springframework.web.bind.annotation.GetMapping;
58 import org.springframework.web.bind.annotation.PathVariable;
59 import org.springframework.web.bind.annotation.PutMapping;
60 import org.springframework.web.bind.annotation.RequestBody;
61 import org.springframework.web.bind.annotation.RequestMapping;
62 import org.springframework.web.bind.annotation.RequestParam;
63 import org.springframework.web.bind.annotation.RestController;
64 import reactor.core.publisher.Mono;
65
66 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
67 @RestController("ConsumerController")
68 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
69 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
70 public class ConsumerController {
71
72     @Autowired
73     ApplicationConfig applicationConfig;
74
75     @Autowired
76     private EiJobs eiJobs;
77
78     @Autowired
79     private EiTypes eiTypes;
80
81     @Autowired
82     ProducerCallbacks producerCallbacks;
83
84     private static Gson gson = new GsonBuilder().create();
85
86     @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
87     @ApiOperation(value = "EI type identifiers", notes = "")
88     @ApiResponses(
89         value = { //
90             @ApiResponse(
91                 code = 200,
92                 message = "EI type identifiers",
93                 response = String.class,
94                 responseContainer = "List"), //
95         })
96     public ResponseEntity<Object> getEiTypeIdentifiers( //
97     ) {
98         List<String> result = new ArrayList<>();
99         for (EiType eiType : this.eiTypes.getAllEiTypes()) {
100             result.add(eiType.getId());
101         }
102
103         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
104     }
105
106     @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
107     @ApiOperation(value = "Individual EI type", notes = "")
108     @ApiResponses(
109         value = { //
110             @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
111             @ApiResponse(
112                 code = 404,
113                 message = "Enrichment Information type is not found",
114                 response = ErrorResponse.ErrorInfo.class)})
115     public ResponseEntity<Object> getEiType( //
116         @PathVariable("eiTypeId") String eiTypeId) {
117         try {
118             this.eiTypes.getType(eiTypeId); // Make sure that the type exists
119             ConsumerEiTypeInfo info = toEiTypeInfo();
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     @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
127     @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
128     @ApiResponses(
129         value = { //
130             @ApiResponse(
131                 code = 200,
132                 message = "EI job identifiers",
133                 response = String.class,
134                 responseContainer = "List"), //
135             @ApiResponse(
136                 code = 404,
137                 message = "Enrichment Information type is not found",
138                 response = ErrorResponse.ErrorInfo.class)})
139     public ResponseEntity<Object> getEiJobIds( //
140         @ApiParam(
141             name = ConsumerConsts.EI_TYPE_ID_PARAM,
142             required = false, //
143             value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
144         @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
145         @ApiParam(
146             name = ConsumerConsts.OWNER_PARAM,
147             required = false, //
148             value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
149         @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
150         try {
151             List<String> result = new ArrayList<>();
152             if (owner != null) {
153                 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
154                     if (eiTypeId == null || job.typeId().equals(eiTypeId)) {
155                         result.add(job.id());
156                     }
157                 }
158             } else if (eiTypeId != null) {
159                 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.id()));
160             } else {
161                 this.eiJobs.getJobs().forEach(job -> result.add(job.id()));
162             }
163             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
164         } catch (
165
166         Exception e) {
167             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
168         }
169     }
170
171     @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
172     @ApiOperation(value = "Individual EI job", notes = "")
173     @ApiResponses(
174         value = { //
175             @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
176             @ApiResponse(
177                 code = 404,
178                 message = "Enrichment Information job is not found",
179                 response = ErrorResponse.ErrorInfo.class)})
180     public ResponseEntity<Object> getIndividualEiJob( //
181         @PathVariable("eiJobId") String eiJobId) {
182         try {
183             EiJob job = this.eiJobs.getJob(eiJobId);
184             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
185         } catch (Exception e) {
186             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
187         }
188     }
189
190     @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
191     @ApiOperation(value = "EI job status", notes = "")
192     @ApiResponses(
193         value = { //
194             @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
195             @ApiResponse(
196                 code = 404,
197                 message = "Enrichment Information job is not found",
198                 response = ErrorResponse.ErrorInfo.class)})
199     public ResponseEntity<Object> getEiJobStatus( //
200         @PathVariable("eiJobId") String eiJobId) {
201         try {
202             EiJob job = this.eiJobs.getJob(eiJobId);
203             return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
204         } catch (Exception e) {
205             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
206         }
207     }
208
209     private Collection<EiProducer> getProducers(EiJob eiJob) {
210         try {
211             return this.eiTypes.getType(eiJob.typeId()).getProducers();
212         } catch (Exception e) {
213             return new Vector<>();
214         }
215     }
216
217     private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
218         for (EiProducer producer : getProducers(job)) {
219             if (producer.isAvailable()) {
220                 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
221             }
222         }
223         return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
224     }
225
226     @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
227     @ApiOperation(value = "Individual EI job", notes = "")
228     @ApiResponses(
229         value = { //
230             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
231             @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
232             @ApiResponse(
233                 code = 404,
234                 message = "Enrichment Information job is not found",
235                 response = ErrorResponse.ErrorInfo.class)})
236     public ResponseEntity<Object> deleteIndividualEiJob( //
237         @PathVariable("eiJobId") String eiJobId) {
238         try {
239             EiJob job = this.eiJobs.getJob(eiJobId);
240             this.eiJobs.remove(job);
241             this.producerCallbacks.notifyProducersJobDeleted(job);
242             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
243         } catch (Exception e) {
244             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
245         }
246     }
247
248     @PutMapping(
249         path = "/eijobs/{eiJobId}", //
250         produces = MediaType.APPLICATION_JSON_VALUE, //
251         consumes = MediaType.APPLICATION_JSON_VALUE)
252     @ApiOperation(value = "Individual EI job", notes = "")
253     @ApiResponses(
254         value = { //
255             @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
256             @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
257             @ApiResponse(
258                 code = 404,
259                 message = "Enrichment Information type is not found",
260                 response = ErrorResponse.ErrorInfo.class)})
261     public Mono<ResponseEntity<Object>> putIndividualEiJob( //
262         @PathVariable("eiJobId") String eiJobId, //
263         @RequestBody ConsumerEiJobInfo eiJobObject) {
264
265         final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
266
267         return validatePutEiJob(eiJobId, eiJobObject) //
268             .flatMap(this::notifyProducersNewJob) //
269             .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
270             .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
271             .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
272     }
273
274     private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
275         return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
276             .flatMap(noOfAcceptingProducers -> {
277                 if (noOfAcceptingProducers.intValue() > 0) {
278                     return Mono.just(newEiJob);
279                 } else {
280                     return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
281                 }
282             });
283     }
284
285     private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
286         try {
287             EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
288             validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
289             EiJob existingEiJob = this.eiJobs.get(eiJobId);
290
291             if (existingEiJob != null && !existingEiJob.typeId().equals(eiJobInfo.eiTypeId)) {
292                 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
293             }
294             return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
295         } catch (Exception e) {
296             return Mono.error(e);
297         }
298     }
299
300     private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
301         if (schemaObj != null) { // schema is optional for now
302             try {
303                 ObjectMapper mapper = new ObjectMapper();
304
305                 String schemaAsString = mapper.writeValueAsString(schemaObj);
306                 JSONObject schemaJSON = new JSONObject(schemaAsString);
307                 Schema schema = SchemaLoader.load(schemaJSON);
308
309                 String objectAsString = mapper.writeValueAsString(object);
310                 JSONObject json = new JSONObject(objectAsString);
311                 schema.validate(json);
312             } catch (Exception e) {
313                 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
314             }
315         }
316     }
317
318     private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
319         return ImmutableEiJob.builder() //
320             .id(id) //
321             .typeId(type.getId()) //
322             .owner(info.owner) //
323             .jobData(info.jobData) //
324             .targetUrl(info.targetUri) //
325             .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
326             .build();
327     }
328
329     private ConsumerEiTypeInfo toEiTypeInfo() {
330         return new ConsumerEiTypeInfo();
331     }
332
333     private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
334         return new ConsumerEiJobInfo(s.typeId(), s.jobData(), s.owner(), s.targetUrl(), s.jobStatusUrl());
335     }
336 }