cf18f239f9eed739cf88075cb31cc329dd56b04c
[cps/ncmp-dmi-plugin.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2024 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.dmi.rest.stub.controller;
22
23 import static org.onap.cps.ncmp.dmi.rest.stub.utils.ModuleResponseType.MODULE_REFERENCE_RESPONSE;
24 import static org.onap.cps.ncmp.dmi.rest.stub.utils.ModuleResponseType.MODULE_RESOURCE_RESPONSE;
25
26 import com.fasterxml.jackson.core.JsonProcessingException;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import io.cloudevents.CloudEvent;
30 import io.cloudevents.core.builder.CloudEventBuilder;
31 import java.net.URI;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.UUID;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import java.util.stream.Collectors;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.json.simple.parser.JSONParser;
42 import org.json.simple.parser.ParseException;
43 import org.onap.cps.ncmp.dmi.datajobs.model.SubjobWriteRequest;
44 import org.onap.cps.ncmp.dmi.datajobs.model.SubjobWriteResponse;
45 import org.onap.cps.ncmp.dmi.rest.stub.controller.aop.ModuleInitialProcess;
46 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DataOperationRequest;
47 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DmiDataOperationRequest;
48 import org.onap.cps.ncmp.dmi.rest.stub.model.data.operational.DmiOperationCmHandle;
49 import org.onap.cps.ncmp.dmi.rest.stub.service.YangModuleFactory;
50 import org.onap.cps.ncmp.dmi.rest.stub.utils.EventDateTimeFormatter;
51 import org.onap.cps.ncmp.dmi.rest.stub.utils.ModuleResponseType;
52 import org.onap.cps.ncmp.dmi.rest.stub.utils.ResourceFileReaderUtil;
53 import org.onap.cps.ncmp.events.async1_0_0.Data;
54 import org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent;
55 import org.onap.cps.ncmp.events.async1_0_0.Response;
56 import org.springframework.beans.factory.annotation.Value;
57 import org.springframework.context.ApplicationContext;
58 import org.springframework.core.io.ResourceLoader;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.ResponseEntity;
61 import org.springframework.kafka.core.KafkaTemplate;
62 import org.springframework.web.bind.annotation.DeleteMapping;
63 import org.springframework.web.bind.annotation.GetMapping;
64 import org.springframework.web.bind.annotation.PathVariable;
65 import org.springframework.web.bind.annotation.PostMapping;
66 import org.springframework.web.bind.annotation.PutMapping;
67 import org.springframework.web.bind.annotation.RequestBody;
68 import org.springframework.web.bind.annotation.RequestHeader;
69 import org.springframework.web.bind.annotation.RequestMapping;
70 import org.springframework.web.bind.annotation.RequestParam;
71 import org.springframework.web.bind.annotation.RestController;
72
73 @RestController
74 @RequestMapping("${rest.api.dmi-stub-base-path}")
75 @Slf4j
76 @RequiredArgsConstructor
77 public class DmiRestStubController {
78
79     private static final String DEFAULT_PASSTHROUGH_OPERATION = "read";
80     private static final String DATA_OPERATION_EVENT_TYPE = "org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent";
81     private static final Map<String, String> moduleSetTagPerCmHandleId = new HashMap<>();
82     private static final List<String> MODULE_SET_TAGS = YangModuleFactory.generateTags();
83     private static final String DEFAULT_TAG = "tagDefault";
84
85     private final KafkaTemplate<String, CloudEvent> cloudEventKafkaTemplate;
86     private final ObjectMapper objectMapper;
87     private final ApplicationContext applicationContext;
88     private final AtomicInteger subJobWriteRequestCounter = new AtomicInteger();
89     private final YangModuleFactory yangModuleFactory;
90
91     @Value("${app.ncmp.async-m2m.topic}")
92     private String ncmpAsyncM2mTopic;
93     @Value("${delay.module-references-delay-ms}")
94     private long moduleReferencesDelayMs;
95     @Value("${delay.module-resources-delay-ms}")
96     private long moduleResourcesDelayMs;
97     @Value("${delay.read-data-for-cm-handle-delay-ms}")
98     private long readDataForCmHandleDelayMs;
99     @Value("${delay.write-data-for-cm-handle-delay-ms}")
100     private long writeDataForCmHandleDelayMs;
101
102     /**
103      * This code defines a REST API endpoint for adding new the module set tag mapping. The endpoint receives the
104      * cmHandleId and moduleSetTag as request body and add into moduleSetTagPerCmHandleId map with the provided
105      * values.
106      *
107      * @param requestBody map of cmHandleId and moduleSetTag
108      * @return a ResponseEntity object containing the updated moduleSetTagPerCmHandleId map as the response body
109      */
110     @PostMapping("/v1/tagMapping")
111     public ResponseEntity<Map<String, String>> addTagForMapping(@RequestBody final Map<String, String> requestBody) {
112         moduleSetTagPerCmHandleId.putAll(requestBody);
113         return new ResponseEntity<>(requestBody, HttpStatus.CREATED);
114     }
115
116     /**
117      * This code defines a GET endpoint of  module set tag mapping.
118      *
119      * @return The map represents the module set tag mapping.
120      */
121     @GetMapping("/v1/tagMapping")
122     public ResponseEntity<Map<String, String>> getTagMapping() {
123         return ResponseEntity.ok(moduleSetTagPerCmHandleId);
124     }
125
126     /**
127      * This code defines a GET endpoint of  module set tag by cm handle ID.
128      *
129      * @return The map represents the module set tag mapping filtered by cm handle ID.
130      */
131     @GetMapping("/v1/tagMapping/ch/{cmHandleId}")
132     public ResponseEntity<String> getTagMappingByCmHandleId(@PathVariable final String cmHandleId) {
133         return ResponseEntity.ok(moduleSetTagPerCmHandleId.get(cmHandleId));
134     }
135
136     /**
137      * This code defines a REST API endpoint for updating the module set tag mapping. The endpoint receives the
138      * cmHandleId and moduleSetTag as request body and updates the moduleSetTagPerCmHandleId map with the provided
139      * values.
140      *
141      * @param requestBody map of cmHandleId and moduleSetTag
142      * @return a ResponseEntity object containing the updated moduleSetTagPerCmHandleId map as the response body
143      */
144
145     @PutMapping("/v1/tagMapping")
146     public ResponseEntity<Map<String, String>> updateTagMapping(@RequestBody final Map<String, String> requestBody) {
147         moduleSetTagPerCmHandleId.putAll(requestBody);
148         return ResponseEntity.noContent().build();
149     }
150
151     /**
152      * It contains a method to delete an entry from the moduleSetTagPerCmHandleId map.
153      * The method takes a cmHandleId as a parameter and removes the corresponding entry from the map.
154      *
155      * @return a ResponseEntity containing the updated map.
156      */
157     @DeleteMapping("/v1/tagMapping/ch/{cmHandleId}")
158     public ResponseEntity<String> deleteTagMappingByCmHandleId(@PathVariable final String cmHandleId) {
159         moduleSetTagPerCmHandleId.remove(cmHandleId);
160         return ResponseEntity.ok(String.format("Mapping of %s is deleted successfully", cmHandleId));
161     }
162
163     /**
164      * Get all modules for given cm handle.
165      *
166      * @param cmHandleId              The identifier for a network function, network element, subnetwork,
167      *                                or any other cm object by managed Network CM Proxy
168      * @param moduleReferencesRequest module references request body
169      * @return ResponseEntity response entity having module response as json string.
170      */
171     @PostMapping("/v1/ch/{cmHandleId}/modules")
172     @ModuleInitialProcess
173     public ResponseEntity<String> getModuleReferences(@PathVariable("cmHandleId") final String cmHandleId,
174                                                       @RequestBody final Object moduleReferencesRequest) {
175         return processModuleRequest(moduleReferencesRequest, MODULE_REFERENCE_RESPONSE, moduleReferencesDelayMs);
176     }
177
178     /**
179      * Get module resources for a given cmHandleId.
180      *
181      * @param cmHandleId                 The identifier for a network function, network element, subnetwork,
182      *                                   or any other cm object by managed Network CM Proxy
183      * @param moduleResourcesReadRequest module resources read request body
184      * @return ResponseEntity response entity having module resources response as json string.
185      */
186     @PostMapping("/v1/ch/{cmHandleId}/moduleResources")
187     @ModuleInitialProcess
188     public ResponseEntity<String> getModuleResources(
189             @PathVariable("cmHandleId") final String cmHandleId,
190             @RequestBody final Object moduleResourcesReadRequest) {
191         return processModuleRequest(moduleResourcesReadRequest, MODULE_RESOURCE_RESPONSE, moduleResourcesDelayMs);
192     }
193
194     /**
195      * Create resource data from passthrough operational or running for a cm handle.
196      *
197      * @param cmHandleId              The identifier for a network function, network element, subnetwork,
198      *                                or any other cm object by managed Network CM Proxy
199      * @param datastoreName           datastore name
200      * @param resourceIdentifier      resource identifier
201      * @param options                 options
202      * @param topic                   client given topic name
203      * @return (@ code ResponseEntity) response entity
204      */
205     @PostMapping("/v1/ch/{cmHandleId}/data/ds/{datastoreName}")
206     public ResponseEntity<String> getResourceDataForCmHandle(
207             @PathVariable("cmHandleId") final String cmHandleId,
208             @PathVariable("datastoreName") final String datastoreName,
209             @RequestParam(value = "resourceIdentifier") final String resourceIdentifier,
210             @RequestParam(value = "options", required = false) final String options,
211             @RequestParam(value = "topic", required = false) final String topic,
212             @RequestHeader(value = "Authorization", required = false) final String authorization,
213             @RequestBody final String requestBody) {
214         log.info("DMI AUTH HEADER: {}", authorization);
215         final String passthroughOperationType = getPassthroughOperationType(requestBody);
216         if (passthroughOperationType.equals("read")) {
217             delay(readDataForCmHandleDelayMs);
218         } else {
219             delay(writeDataForCmHandleDelayMs);
220         }
221         log.info("Logging request body {}", requestBody);
222
223         final String sampleJson = ResourceFileReaderUtil.getResourceFileContent(applicationContext.getResource(
224                 ResourceLoader.CLASSPATH_URL_PREFIX + "data/ietf-network-topology-sample-rfc8345.json"));
225         return ResponseEntity.ok(sampleJson);
226     }
227
228     /**
229      * This method is not implemented for ONAP DMI plugin.
230      *
231      * @param topic                   client given topic name
232      * @param requestId               requestId generated by NCMP as an ack for client
233      * @param dmiDataOperationRequest list of operation details
234      * @return (@ code ResponseEntity) response entity
235      */
236     @PostMapping("/v1/data")
237     public ResponseEntity<Void> getResourceDataForCmHandleDataOperation(
238             @RequestParam(value = "topic") final String topic,
239             @RequestParam(value = "requestId") final String requestId,
240             @RequestBody final DmiDataOperationRequest dmiDataOperationRequest) {
241         delay(writeDataForCmHandleDelayMs);
242         try {
243             log.info("Request received from the NCMP to DMI Plugin: {}",
244                     objectMapper.writeValueAsString(dmiDataOperationRequest));
245         } catch (final JsonProcessingException jsonProcessingException) {
246             log.info("Unable to process dmi data operation request to json string");
247         }
248         dmiDataOperationRequest.getOperations().forEach(dmiDataOperation -> {
249             final DataOperationEvent dataOperationEvent = getDataOperationEvent(dmiDataOperation);
250             dmiDataOperation.getCmHandles().forEach(dmiOperationCmHandle -> {
251                 log.info("Module Set Tag received: {}", dmiOperationCmHandle.getModuleSetTag());
252                 dataOperationEvent.getData().getResponses().get(0).setIds(List.of(dmiOperationCmHandle.getId()));
253                 final CloudEvent cloudEvent = buildAndGetCloudEvent(topic, requestId, dataOperationEvent);
254                 cloudEventKafkaTemplate.send(ncmpAsyncM2mTopic, UUID.randomUUID().toString(), cloudEvent);
255             });
256         });
257         return new ResponseEntity<>(HttpStatus.ACCEPTED);
258     }
259
260     /**
261      * Consume sub-job write requests from NCMP.
262      *
263      * @param subJobWriteRequest            contains a collection of write requests and metadata.
264      * @param destination                   the destination of the results. ( e.g. S3 Bucket).
265      * @return (@ code ResponseEntity) response for the write request.
266      */
267     @PostMapping("/v1/cmwriteJob")
268     public ResponseEntity<SubjobWriteResponse> consumeWriteSubJobs(
269                                                         @RequestBody final SubjobWriteRequest subJobWriteRequest,
270                                                         @RequestParam("destination") final String destination) {
271         log.debug("Destination: {}", destination);
272         log.debug("Request body: {}", subJobWriteRequest);
273         return ResponseEntity.ok(new SubjobWriteResponse(String.valueOf(subJobWriteRequestCounter.incrementAndGet()),
274                 "some-dmi-service-name", "my-data-producer-id"));
275     }
276
277     /**
278      * Retrieves the status of a given data job identified by {@code requestId} and {@code dataProducerJobId}.
279      *
280      * @param dataProducerId    ID of the producer registered by DMI for the alternateIDs
281      *                          in the operations in this request.
282      * @param dataProducerJobId Identifier of the data producer job.
283      * @return A ResponseEntity with HTTP status 200 (OK) and the data job's status as a string.
284      */
285     @GetMapping("/v1/cmwriteJob/dataProducer/{dataProducerId}/dataProducerJob/{dataProducerJobId}/status")
286     public ResponseEntity<Map<String, String>> retrieveDataJobStatus(
287             @PathVariable("dataProducerId") final String dataProducerId,
288             @PathVariable("dataProducerJobId") final String dataProducerJobId) {
289         log.info("Received request to retrieve data job status. Request ID: {}, Data Producer Job ID: {}",
290                 dataProducerId, dataProducerJobId);
291         return ResponseEntity.ok(Map.of("status", "FINISHED"));
292     }
293
294     /**
295      * Retrieves the result of a given data job identified by {@code requestId} and {@code dataProducerJobId}.
296      *
297      * @param dataProducerId        Identifier for the data producer as a query parameter (required)
298      * @param dataProducerJobId     Identifier for the data producer job (required)
299      * @param destination           The destination of the results, Kafka topic name or s3 bucket name (required)
300      * @return A ResponseEntity with HTTP status 200 (OK) and the data job's result as an Object.
301      */
302     @GetMapping("/v1/cmwriteJob/dataProducer/{dataProducerId}/dataProducerJob/{dataProducerJobId}/result")
303     public ResponseEntity<Object> retrieveDataJobResult(
304             @PathVariable("dataProducerId") final String dataProducerId,
305             @PathVariable("dataProducerJobId") final String dataProducerJobId,
306             @RequestParam(name = "destination") final String destination) {
307         log.debug("Received request to retrieve data job result. Data Producer ID: {}, "
308                         + "Data Producer Job ID: {}, Destination: {}",
309                 dataProducerId, dataProducerJobId, destination);
310         return ResponseEntity.ok(Map.of("result", "some status"));
311     }
312
313     private CloudEvent buildAndGetCloudEvent(final String topic, final String requestId,
314                                              final DataOperationEvent dataOperationEvent) {
315         CloudEvent cloudEvent = null;
316         try {
317             cloudEvent = CloudEventBuilder.v1()
318                     .withId(UUID.randomUUID().toString())
319                     .withSource(URI.create("DMI"))
320                     .withType(DATA_OPERATION_EVENT_TYPE)
321                     .withDataSchema(URI.create("urn:cps:" + DATA_OPERATION_EVENT_TYPE + ":1.0.0"))
322                     .withTime(EventDateTimeFormatter.toIsoOffsetDateTime(
323                             EventDateTimeFormatter.getCurrentIsoFormattedDateTime()))
324                     .withData(objectMapper.writeValueAsBytes(dataOperationEvent))
325                     .withExtension("destination", topic)
326                     .withExtension("correlationid", requestId)
327                     .build();
328         } catch (final JsonProcessingException jsonProcessingException) {
329             log.error("Unable to parse event into bytes. cause : {}", jsonProcessingException.getMessage());
330         }
331         return cloudEvent;
332     }
333
334     private DataOperationEvent getDataOperationEvent(final DataOperationRequest dataOperationRequest) {
335         final Response response = new Response();
336
337         response.setOperationId(dataOperationRequest.getOperationId());
338         response.setStatusCode("0");
339         response.setStatusMessage("Successfully applied changes");
340         response.setIds(dataOperationRequest.getCmHandles().stream().map(DmiOperationCmHandle::getId)
341                 .collect(Collectors.toList()));
342         response.setResourceIdentifier(dataOperationRequest.getResourceIdentifier());
343         response.setOptions(dataOperationRequest.getOptions());
344         final String ietfNetworkTopologySample = ResourceFileReaderUtil.getResourceFileContent(
345                 applicationContext.getResource(ResourceLoader.CLASSPATH_URL_PREFIX
346                         + "data/ietf-network-topology-sample-rfc8345.json"));
347         final JSONParser jsonParser = new JSONParser();
348         try {
349             response.setResult(jsonParser.parse(ietfNetworkTopologySample));
350         } catch (final ParseException parseException) {
351             log.error("Unable to parse event result as json object. cause : {}", parseException.getMessage());
352         }
353         final List<Response> responseList = new ArrayList<>(1);
354         responseList.add(response);
355         final Data data = new Data();
356         data.setResponses(responseList);
357         final DataOperationEvent dataOperationEvent = new DataOperationEvent();
358         dataOperationEvent.setData(data);
359         return dataOperationEvent;
360     }
361
362     private ResponseEntity<String> processModuleRequest(final Object moduleRequest,
363                                                         final ModuleResponseType moduleResponseType,
364                                                         final long simulatedResponseDelay) {
365         logRequestBody(moduleRequest);
366         String moduleResponseContent = "";
367         String moduleSetTag = extractModuleSetTagFromRequest(moduleRequest);
368
369         moduleSetTag = (!isModuleSetTagNullOrEmpty(moduleSetTag)
370             && MODULE_SET_TAGS.contains(moduleSetTag)) ? moduleSetTag : DEFAULT_TAG;
371
372         if (MODULE_RESOURCE_RESPONSE == moduleResponseType) {
373             moduleResponseContent = yangModuleFactory.getModuleResourcesJson(moduleSetTag);
374         } else {
375             moduleResponseContent = yangModuleFactory.getModuleReferencesJson(moduleSetTag);
376         }
377
378         delay(simulatedResponseDelay);
379         return ResponseEntity.ok(moduleResponseContent);
380     }
381
382     private String extractModuleSetTagFromRequest(final Object moduleReferencesRequest) {
383         final JsonNode rootNode = objectMapper.valueToTree(moduleReferencesRequest);
384         return rootNode.path("moduleSetTag").asText(null);
385     }
386
387     private boolean isModuleSetTagNullOrEmpty(final String moduleSetTag) {
388         return moduleSetTag == null || moduleSetTag.trim().isEmpty();
389     }
390
391     private void logRequestBody(final Object request) {
392         try {
393             log.info("Incoming DMI request body: {}", objectMapper.writeValueAsString(request));
394         } catch (final JsonProcessingException jsonProcessingException) {
395             log.info("Unable to parse DMI request to json string");
396         }
397     }
398
399     private String getPassthroughOperationType(final String requestBody) {
400         try {
401             final JsonNode rootNode = objectMapper.readTree(requestBody);
402             return rootNode.path("operation").asText();
403         } catch (final JsonProcessingException jsonProcessingException) {
404             log.error("Invalid JSON format. cause : {}", jsonProcessingException.getMessage());
405         }
406         return DEFAULT_PASSTHROUGH_OPERATION;
407     }
408
409     private void delay(final long milliseconds) {
410         try {
411             Thread.sleep(milliseconds);
412         } catch (final InterruptedException e) {
413             log.error("Thread sleep interrupted: {}", e.getMessage());
414             Thread.currentThread().interrupt();
415         }
416     }
417 }