Merge "Extend API: Get Module Definitions"
[cps.git] / cps-ncmp-rest / src / main / java / org / onap / cps / ncmp / rest / controller / NetworkCmProxyController.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Pantheon.tech
4  *  Modifications Copyright (C) 2021-2024 Nordix Foundation
5  *  Modifications Copyright (C) 2021 highstreet technologies GmbH
6  *  Modifications Copyright (C) 2021-2022 Bell Canada
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.ncmp.rest.controller;
25
26 import static org.onap.cps.ncmp.api.impl.operations.DatastoreType.OPERATIONAL;
27 import static org.onap.cps.ncmp.api.impl.operations.DatastoreType.PASSTHROUGH_RUNNING;
28 import static org.onap.cps.ncmp.api.impl.operations.OperationType.CREATE;
29 import static org.onap.cps.ncmp.api.impl.operations.OperationType.DELETE;
30 import static org.onap.cps.ncmp.api.impl.operations.OperationType.PATCH;
31 import static org.onap.cps.ncmp.api.impl.operations.OperationType.UPDATE;
32
33 import io.micrometer.core.annotation.Timed;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.stream.Collectors;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
42 import org.onap.cps.ncmp.api.impl.exception.InvalidDatastoreException;
43 import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
44 import org.onap.cps.ncmp.api.impl.operations.DatastoreType;
45 import org.onap.cps.ncmp.api.impl.trustlevel.TrustLevel;
46 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
47 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
48 import org.onap.cps.ncmp.rest.api.NetworkCmProxyApi;
49 import org.onap.cps.ncmp.rest.controller.handlers.NcmpCachedResourceRequestHandler;
50 import org.onap.cps.ncmp.rest.controller.handlers.NcmpDatastoreRequestHandler;
51 import org.onap.cps.ncmp.rest.controller.handlers.NcmpPassthroughResourceRequestHandler;
52 import org.onap.cps.ncmp.rest.mapper.CmHandleStateMapper;
53 import org.onap.cps.ncmp.rest.mapper.DataOperationRequestMapper;
54 import org.onap.cps.ncmp.rest.model.CmHandlePublicProperties;
55 import org.onap.cps.ncmp.rest.model.CmHandleQueryParameters;
56 import org.onap.cps.ncmp.rest.model.DataOperationRequest;
57 import org.onap.cps.ncmp.rest.model.RestModuleDefinition;
58 import org.onap.cps.ncmp.rest.model.RestModuleReference;
59 import org.onap.cps.ncmp.rest.model.RestOutputCmHandle;
60 import org.onap.cps.ncmp.rest.model.RestOutputCmHandleCompositeState;
61 import org.onap.cps.ncmp.rest.model.RestOutputCmHandlePublicProperties;
62 import org.onap.cps.ncmp.rest.util.DeprecationHelper;
63 import org.onap.cps.spi.model.ModuleDefinition;
64 import org.onap.cps.utils.JsonObjectMapper;
65 import org.springframework.http.HttpStatus;
66 import org.springframework.http.ResponseEntity;
67 import org.springframework.util.StringUtils;
68 import org.springframework.web.bind.annotation.RequestMapping;
69 import org.springframework.web.bind.annotation.RestController;
70
71 @Slf4j
72 @RestController
73 @RequestMapping("${rest.api.ncmp-base-path}")
74 @RequiredArgsConstructor
75 public class NetworkCmProxyController implements NetworkCmProxyApi {
76
77     private static final String NO_BODY = null;
78     private final NetworkCmProxyDataService networkCmProxyDataService;
79     private final JsonObjectMapper jsonObjectMapper;
80     private final DeprecationHelper deprecationHelper;
81     private final NcmpRestInputMapper ncmpRestInputMapper;
82     private final CmHandleStateMapper cmHandleStateMapper;
83     private final NcmpCachedResourceRequestHandler ncmpCachedResourceRequestHandler;
84     private final NcmpPassthroughResourceRequestHandler ncmpPassthroughResourceRequestHandler;
85     private final DataOperationRequestMapper dataOperationRequestMapper;
86     private final Map<String, TrustLevel> trustLevelPerCmHandle;
87
88     /**
89      * Get resource data from datastore.
90      *
91      * @param datastoreName        name of the datastore
92      * @param cmHandle             cm handle identifier
93      * @param resourceIdentifier   resource identifier
94      * @param optionsParamInQuery  options query parameter
95      * @param topicParamInQuery    topic query parameter
96      * @param includeDescendants   whether to include descendants or not
97      * @return {@code ResponseEntity} response from dmi plugin
98      */
99     @Override
100     @Timed(value = "cps.ncmp.controller.get", description = "Time taken to get resource data from datastore")
101     public ResponseEntity<Object> getResourceDataForCmHandle(final String datastoreName,
102                                                              final String cmHandle,
103                                                              final String resourceIdentifier,
104                                                              final String optionsParamInQuery,
105                                                              final String topicParamInQuery,
106                                                              final Boolean includeDescendants) {
107         final NcmpDatastoreRequestHandler ncmpDatastoreRequestHandler = getNcmpDatastoreRequestHandler(datastoreName);
108         return ncmpDatastoreRequestHandler.executeRequest(datastoreName, cmHandle, resourceIdentifier,
109                 optionsParamInQuery, topicParamInQuery, includeDescendants);
110     }
111
112     @Override
113     public ResponseEntity<Object> executeDataOperationForCmHandles(final String topicParamInQuery,
114                                                                   final DataOperationRequest
115                                                                           dataOperationRequest) {
116         return ncmpPassthroughResourceRequestHandler.executeRequest(topicParamInQuery,
117                 dataOperationRequestMapper.toDataOperationRequest(dataOperationRequest));
118     }
119
120     /**
121      * Query resource data from datastore.
122      *
123      * @param datastoreName        name of the datastore
124      * @param cmHandle             cm handle identifier
125      * @param cpsPath              CPS Path
126      * @param optionsParamInQuery  options query parameter
127      * @param topicParamInQuery    topic query parameter
128      * @param includeDescendants   whether to include descendants or not
129      * @return {@code ResponseEntity} response from dmi plugin
130      */
131
132     @Override
133     public ResponseEntity<Object> queryResourceDataForCmHandle(final String datastoreName,
134                                                                final String cmHandle,
135                                                                final String cpsPath,
136                                                                final String optionsParamInQuery,
137                                                                final String topicParamInQuery,
138                                                                final Boolean includeDescendants) {
139         validateDataStore(OPERATIONAL, datastoreName);
140         return ncmpCachedResourceRequestHandler.executeRequest(cmHandle, cpsPath, includeDescendants);
141     }
142
143     /**
144      * Patch resource data from passthrough-running.
145      *
146      * @param datastoreName      name of the datastore
147      * @param cmHandle           cm handle identifier
148      * @param resourceIdentifier resource identifier
149      * @param requestBody        the request body
150      * @param contentType        content type of body
151      * @return {@code ResponseEntity} response from dmi plugin
152      */
153
154     @Override
155     public ResponseEntity<Object> patchResourceDataRunningForCmHandle(final String datastoreName,
156                                                                       final String cmHandle,
157                                                                       final String resourceIdentifier,
158                                                                       final Object requestBody,
159                                                                       final String contentType) {
160
161         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
162
163         final Object responseObject = networkCmProxyDataService
164                 .writeResourceDataPassThroughRunningForCmHandle(
165                         cmHandle, resourceIdentifier, PATCH,
166                         jsonObjectMapper.asJsonString(requestBody), contentType);
167         return ResponseEntity.ok(responseObject);
168     }
169
170     /**
171      * Create resource data in datastore pass-through running for given cm-handle.
172      *
173      * @param datastoreName      name of the datastore
174      * @param cmHandle           cm handle identifier
175      * @param resourceIdentifier resource identifier
176      * @param requestBody        the request body
177      * @param contentType        content type of body
178      * @return {@code ResponseEntity} response from dmi plugin
179      */
180     @Override
181     public ResponseEntity<Void> createResourceDataRunningForCmHandle(final String datastoreName,
182                                                                      final String cmHandle,
183                                                                      final String resourceIdentifier,
184                                                                      final Object requestBody,
185                                                                      final String contentType) {
186
187         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
188
189         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
190                 resourceIdentifier, CREATE, jsonObjectMapper.asJsonString(requestBody), contentType);
191         return new ResponseEntity<>(HttpStatus.CREATED);
192     }
193
194     /**
195      * Update resource data in datastore pass-through running for given cm-handle.
196      *
197      * @param datastoreName      name of the datastore
198      * @param cmHandle           cm handle identifier
199      * @param resourceIdentifier resource identifier
200      * @param requestBody        the request body
201      * @param contentType        content type of the body
202      * @return response entity
203      */
204
205     @Override
206     public ResponseEntity<Object> updateResourceDataRunningForCmHandle(final String datastoreName,
207                                                                        final String cmHandle,
208                                                                        final String resourceIdentifier,
209                                                                        final Object requestBody,
210                                                                        final String contentType) {
211         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
212
213         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
214                 resourceIdentifier, UPDATE, jsonObjectMapper.asJsonString(requestBody), contentType);
215         return new ResponseEntity<>(HttpStatus.OK);
216     }
217
218     /**
219      * Delete resource data in datastore pass-through running for a given cm-handle.
220      *
221      * @param datastoreName      name of the datastore
222      * @param cmHandle           cm handle identifier
223      * @param resourceIdentifier resource identifier
224      * @param contentType        content type of the body
225      * @return response entity no content if request is successful
226      */
227     @Override
228     public ResponseEntity<Void> deleteResourceDataRunningForCmHandle(final String datastoreName,
229                                                                      final String cmHandle,
230                                                                      final String resourceIdentifier,
231                                                                      final String contentType) {
232
233         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
234
235         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
236                 resourceIdentifier, DELETE, NO_BODY, contentType);
237         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
238     }
239
240     /**
241      * Query and return cm handles that match the given query parameters.
242      *
243      * @param cmHandleQueryParameters the cm handle query parameters
244      * @return collection of cm handles
245      */
246     @Override
247     @SuppressWarnings("deprecation") // mapOldConditionProperties method will be removed in Release 12
248     public ResponseEntity<List<RestOutputCmHandle>> searchCmHandles(
249             final CmHandleQueryParameters cmHandleQueryParameters) {
250         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
251                 deprecationHelper.mapOldConditionProperties(cmHandleQueryParameters);
252         final Collection<NcmpServiceCmHandle> cmHandles = networkCmProxyDataService
253                 .executeCmHandleSearch(cmHandleQueryApiParameters);
254         final List<RestOutputCmHandle> outputCmHandles =
255                 cmHandles.stream().map(this::toRestOutputCmHandle).collect(Collectors.toList());
256         return ResponseEntity.ok(outputCmHandles);
257     }
258
259     /**
260      * Query and return cm handle ids that match the given query parameters.
261      *
262      * @param cmHandleQueryParameters the cm handle query parameters
263      * @return collection of cm handle ids
264      */
265     @Override
266     public ResponseEntity<List<String>> searchCmHandleIds(
267             final CmHandleQueryParameters cmHandleQueryParameters) {
268         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
269                 jsonObjectMapper.convertToValueType(cmHandleQueryParameters, CmHandleQueryApiParameters.class);
270         final Collection<String> cmHandleIds
271             = networkCmProxyDataService.executeCmHandleIdSearch(cmHandleQueryApiParameters);
272         return ResponseEntity.ok(List.copyOf(cmHandleIds));
273     }
274
275     /**
276      * Search for Cm Handle and Properties by Name.
277      *
278      * @param cmHandleId cm-handle identifier
279      * @return cm handle and its properties
280      */
281     @Override
282     public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
283         final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
284         final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
285         return ResponseEntity.ok(restOutputCmHandle);
286     }
287
288     /**
289      * Get Cm Handle Properties by Cm Handle Id.
290      *
291      * @param cmHandleId cm-handle identifier
292      * @return cm handle properties
293      */
294     @Override
295     public ResponseEntity<RestOutputCmHandlePublicProperties> getCmHandlePublicPropertiesByCmHandleId(
296             final String cmHandleId) {
297         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
298         cmHandlePublicProperties.add(networkCmProxyDataService.getCmHandlePublicProperties(cmHandleId));
299         final RestOutputCmHandlePublicProperties restOutputCmHandlePublicProperties =
300                 new RestOutputCmHandlePublicProperties();
301         restOutputCmHandlePublicProperties.setPublicCmHandleProperties(cmHandlePublicProperties);
302         return ResponseEntity.ok(restOutputCmHandlePublicProperties);
303     }
304
305     /**
306      * Get Cm Handle State by Cm Handle Id.
307      *
308      * @param cmHandleId cm-handle identifier
309      * @return cm handle state
310      */
311     @Override
312     public ResponseEntity<RestOutputCmHandleCompositeState> getCmHandleStateByCmHandleId(
313             final String cmHandleId) {
314         final CompositeState cmHandleState = networkCmProxyDataService.getCmHandleCompositeState(cmHandleId);
315         final RestOutputCmHandleCompositeState restOutputCmHandleCompositeState =
316                 new RestOutputCmHandleCompositeState();
317         restOutputCmHandleCompositeState.setState(
318                 cmHandleStateMapper.toCmHandleCompositeStateExternalLockReason(cmHandleState));
319         return ResponseEntity.ok(restOutputCmHandleCompositeState);
320     }
321
322     /**
323      * Return module definitions.
324      *
325      * @param cmHandleId    cm-handle identifier
326      * @param moduleName    module name
327      * @param revision      the revision of the module
328      * @return list of module definitions (module name, revision, yang resource content)
329      */
330     @Override
331     public ResponseEntity<List<RestModuleDefinition>> getModuleDefinitions(final String cmHandleId,
332                                                                            final String moduleName,
333                                                                            final String revision) {
334         final Collection<ModuleDefinition> moduleDefinitions;
335         if (StringUtils.hasText(moduleName)) {
336             moduleDefinitions =
337                 networkCmProxyDataService.getModuleDefinitionsByCmHandleAndModule(cmHandleId, moduleName, revision);
338         } else {
339             moduleDefinitions = networkCmProxyDataService.getModuleDefinitionsByCmHandleId(cmHandleId);
340             if (StringUtils.hasText(revision)) {
341                 log.warn("Ignoring revision filter as no module name is provided");
342             }
343         }
344         final List<RestModuleDefinition> response = new ArrayList<>();
345         for (final ModuleDefinition moduleDefinition: moduleDefinitions) {
346             response.add(ncmpRestInputMapper.toRestModuleDefinition(moduleDefinition));
347         }
348         return new ResponseEntity<>(response, HttpStatus.OK);
349     }
350
351     /**
352      * Return module references for a cm handle.
353      *
354      * @param cmHandle the cm handle
355      * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
356      */
357     public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
358         final List<RestModuleReference> restModuleReferences =
359                 networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
360                         .map(ncmpRestInputMapper::toRestModuleReference)
361                         .collect(Collectors.toList());
362         return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
363     }
364
365     /**
366      * Set the data sync enabled flag, along with the data sync state for the specified cm handle.
367      *
368      * @param cmHandleId          cm handle id
369      * @param dataSyncEnabledFlag data sync enabled flag
370      * @return response entity ok if request is successful
371      */
372     @Override
373     public ResponseEntity<Object> setDataSyncEnabledFlagForCmHandle(final String cmHandleId,
374                                                                     final Boolean dataSyncEnabledFlag) {
375         networkCmProxyDataService.setDataSyncEnabled(cmHandleId, dataSyncEnabledFlag);
376         return new ResponseEntity<>(HttpStatus.OK);
377     }
378
379
380     private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
381         final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
382         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
383         final TrustLevel cmHandleCurrentTrustLevel = trustLevelPerCmHandle.get(ncmpServiceCmHandle.getCmHandleId());
384         restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleId());
385         cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
386         restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
387         restOutputCmHandle.setState(cmHandleStateMapper.toCmHandleCompositeStateExternalLockReason(
388                 ncmpServiceCmHandle.getCompositeState()));
389         if (cmHandleCurrentTrustLevel != null) {
390             restOutputCmHandle.setTrustLevel(cmHandleCurrentTrustLevel.toString());
391         }
392         return restOutputCmHandle;
393     }
394
395     private void validateDataStore(final DatastoreType acceptableDataStoreType, final String requestedDatastoreName) {
396         final DatastoreType datastoreType = DatastoreType.fromDatastoreName(requestedDatastoreName);
397
398         if (acceptableDataStoreType != datastoreType) {
399             throw new InvalidDatastoreException(requestedDatastoreName + " is not supported");
400         }
401     }
402
403     private NcmpDatastoreRequestHandler getNcmpDatastoreRequestHandler(final String datastoreName) {
404         if (OPERATIONAL.equals(DatastoreType.fromDatastoreName(datastoreName))) {
405             return ncmpCachedResourceRequestHandler;
406         }
407         return ncmpPassthroughResourceRequestHandler;
408     }
409
410
411 }
412