f8cab4f1cad142956f560c3506de35a05966b520
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServiceImpl.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 highstreet technologies GmbH
4  *  Modifications Copyright (C) 2021-2022 Nordix Foundation
5  *  Modifications Copyright (C) 2021 Pantheon.tech
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.api.impl;
25
26 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DATASPACE_NAME;
27 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_ANCHOR;
28 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_PARENT;
29 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
30 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NO_TIMESTAMP;
31 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum;
32 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED;
33 import static org.onap.cps.utils.CmHandleQueryRestParametersValidator.validateCmHandleQueryParameters;
34
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Set;
41 import java.util.stream.Collectors;
42 import lombok.RequiredArgsConstructor;
43 import lombok.extern.slf4j.Slf4j;
44 import org.onap.cps.api.CpsAdminService;
45 import org.onap.cps.api.CpsDataService;
46 import org.onap.cps.api.CpsModuleService;
47 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandlerQueryService;
48 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
49 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
50 import org.onap.cps.ncmp.api.impl.operations.DmiOperations;
51 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
52 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
53 import org.onap.cps.ncmp.api.inventory.CmHandleState;
54 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
55 import org.onap.cps.ncmp.api.inventory.sync.ModuleSyncService;
56 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
57 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
58 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError;
59 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
60 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
61 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
62 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
63 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
64 import org.onap.cps.spi.exceptions.DataValidationException;
65 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException;
66 import org.onap.cps.spi.model.CmHandleQueryServiceParameters;
67 import org.onap.cps.spi.model.ModuleReference;
68 import org.onap.cps.utils.CpsValidator;
69 import org.onap.cps.utils.JsonObjectMapper;
70 import org.springframework.http.ResponseEntity;
71 import org.springframework.stereotype.Service;
72
73 @Slf4j
74 @Service
75 @RequiredArgsConstructor
76 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
77
78     private final CpsDataService cpsDataService;
79
80     private final JsonObjectMapper jsonObjectMapper;
81
82     private final DmiDataOperations dmiDataOperations;
83
84     private final CpsModuleService cpsModuleService;
85
86     private final CpsAdminService cpsAdminService;
87
88     private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
89
90     private final InventoryPersistence inventoryPersistence;
91
92     private final ModuleSyncService moduleSyncService;
93
94     private final NetworkCmProxyCmHandlerQueryService networkCmProxyCmHandlerQueryService;
95
96     @Override
97     public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
98             final DmiPluginRegistration dmiPluginRegistration) {
99         dmiPluginRegistration.validateDmiPluginRegistration();
100         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
101         dmiPluginRegistrationResponse.setRemovedCmHandles(
102                 parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration.getRemovedCmHandles()));
103         if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
104             dmiPluginRegistrationResponse.setCreatedCmHandles(
105                     parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration));
106         }
107         if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
108             dmiPluginRegistrationResponse.setUpdatedCmHandles(
109                     networkCmProxyDataServicePropertyHandler
110                             .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
111         }
112         return dmiPluginRegistrationResponse;
113     }
114
115     @Override
116     public Object getResourceDataOperationalForCmHandle(final String cmHandleId,
117                                                         final String resourceIdentifier,
118                                                         final String optionsParamInQuery,
119                                                         final String topicParamInQuery,
120                                                         final String requestId) {
121         final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(cmHandleId,
122             resourceIdentifier,
123             optionsParamInQuery,
124             DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
125             requestId, topicParamInQuery);
126         return responseEntity.getBody();
127     }
128
129     @Override
130     public Object getResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
131                                                                final String resourceIdentifier,
132                                                                final String optionsParamInQuery,
133                                                                final String topicParamInQuery,
134                                                                final String requestId) {
135         final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(cmHandleId,
136             resourceIdentifier,
137             optionsParamInQuery,
138             DmiOperations.DataStoreEnum.PASSTHROUGH_RUNNING,
139             requestId, topicParamInQuery);
140         return responseEntity.getBody();
141     }
142
143     @Override
144     public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
145                                                                  final String resourceIdentifier,
146                                                                  final OperationEnum operation,
147                                                                  final String requestData,
148                                                                  final String dataType) {
149         CpsValidator.validateNameCharacters(cmHandleId);
150         return dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier, operation,
151             requestData, dataType);
152     }
153
154
155     @Override
156     public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
157         CpsValidator.validateNameCharacters(cmHandleId);
158         return cpsModuleService.getYangResourcesModuleReferences(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId);
159     }
160
161     /**
162      * Retrieve cm handles with details for the given query parameters.
163      *
164      * @param cmHandleQueryApiParameters cm handle query parameters
165      * @return cm handles with details
166      */
167     @Override
168     public Set<NcmpServiceCmHandle> executeCmHandleSearch(final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
169
170         final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
171                 cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
172
173         validateCmHandleQueryParameters(cmHandleQueryServiceParameters);
174
175         return networkCmProxyCmHandlerQueryService.queryCmHandles(cmHandleQueryServiceParameters).stream()
176                 .map(dataNode -> YangDataConverter
177                         .convertCmHandleToYangModel(dataNode, dataNode.getLeaves().get("id").toString()))
178                 .map(YangDataConverter::convertYangModelCmHandleToNcmpServiceCmHandle).collect(Collectors.toSet());
179     }
180
181     /**
182      * Retrieve cm handle ids for the given query parameters.
183      *
184      * @param cmHandleQueryApiParameters cm handle query parameters
185      * @return cm handle ids
186      */
187     @Override
188     public Set<String> executeCmHandleIdSearch(final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
189         return executeCmHandleSearch(cmHandleQueryApiParameters).stream().map(NcmpServiceCmHandle::getCmHandleId)
190                 .collect(Collectors.toSet());
191     }
192
193     /**
194      * Retrieve cm handle details for a given cm handle.
195      *
196      * @param cmHandleId cm handle identifier
197      * @return cm handle details
198      */
199     @Override
200     public NcmpServiceCmHandle getNcmpServiceCmHandle(final String cmHandleId) {
201         CpsValidator.validateNameCharacters(cmHandleId);
202         return YangDataConverter.convertYangModelCmHandleToNcmpServiceCmHandle(
203                 inventoryPersistence.getYangModelCmHandle(cmHandleId));
204     }
205
206     /**
207      * Get cm handle public properties for a given cm handle id.
208      *
209      * @param cmHandleId cm handle identifier
210      * @return cm handle public properties
211      */
212     @Override
213     public Map<String, String> getCmHandlePublicProperties(final String cmHandleId) {
214         CpsValidator.validateNameCharacters(cmHandleId);
215         final YangModelCmHandle yangModelCmHandle =
216             inventoryPersistence.getYangModelCmHandle(cmHandleId);
217         final List<YangModelCmHandle.Property> yangModelPublicProperties = yangModelCmHandle.getPublicProperties();
218         final Map<String, String> cmHandlePublicProperties = new HashMap<>();
219         YangDataConverter.asPropertiesMap(yangModelPublicProperties, cmHandlePublicProperties);
220         return cmHandlePublicProperties;
221     }
222
223     /**
224      * THis method registers a cm handle and initiates modules sync.
225      *
226      * @param dmiPluginRegistration dmi plugin registration information.
227      * @return cm-handle registration response for create cm-handle requests.
228      */
229     public List<CmHandleRegistrationResponse> parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(
230             final DmiPluginRegistration dmiPluginRegistration) {
231         List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>();
232         try {
233             cmHandleRegistrationResponses = dmiPluginRegistration.getCreatedCmHandles().stream()
234                 .map(cmHandle ->
235                     YangModelCmHandle.toYangModelCmHandle(
236                         dmiPluginRegistration.getDmiPlugin(),
237                         dmiPluginRegistration.getDmiDataPlugin(),
238                         dmiPluginRegistration.getDmiModelPlugin(),
239                         CmHandleState.ADVISED,
240                         cmHandle)
241                 )
242                 .map(this::registerNewCmHandle)
243                 .collect(Collectors.toList());
244         } catch (final DataValidationException dataValidationException) {
245             cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createFailureResponse(dmiPluginRegistration
246                             .getCreatedCmHandles().stream()
247                             .map(NcmpServiceCmHandle::getCmHandleId).findFirst().orElse(null),
248                     RegistrationError.CM_HANDLE_INVALID_ID));
249         }
250         return cmHandleRegistrationResponses;
251     }
252
253     protected List<CmHandleRegistrationResponse> parseAndRemoveCmHandlesInDmiRegistration(
254             final List<String> tobeRemovedCmHandles) {
255         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
256                 new ArrayList<>(tobeRemovedCmHandles.size());
257         for (final String cmHandle : tobeRemovedCmHandles) {
258             try {
259                 CpsValidator.validateNameCharacters(cmHandle);
260                 deleteSchemaSetWithCascade(cmHandle);
261                 cpsDataService.deleteListOrListElement(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
262                         "/dmi-registry/cm-handles[@id='" + cmHandle + "']", NO_TIMESTAMP);
263                 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandle));
264             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
265                 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
266                         cmHandle, dataNodeNotFoundException.getMessage());
267                 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse
268                         .createFailureResponse(cmHandle, RegistrationError.CM_HANDLE_DOES_NOT_EXIST));
269             } catch (final DataValidationException dataValidationException) {
270                 log.error("Unable to de-register cm-handle id: {}, caused by: {}",
271                         cmHandle, dataValidationException.getMessage());
272                 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse
273                         .createFailureResponse(cmHandle, RegistrationError.CM_HANDLE_INVALID_ID));
274             } catch (final Exception exception) {
275                 log.error("Unable to de-register cm-handle id : {} , caused by : {}",
276                         cmHandle, exception.getMessage());
277                 cmHandleRegistrationResponses.add(
278                         CmHandleRegistrationResponse.createFailureResponse(cmHandle, exception));
279             }
280         }
281         return cmHandleRegistrationResponses;
282     }
283
284     private void deleteSchemaSetWithCascade(final String schemaSetName) {
285         try {
286             cpsModuleService.deleteSchemaSet(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetName,
287                     CASCADE_DELETE_ALLOWED);
288         } catch (final SchemaSetNotFoundException schemaSetNotFoundException) {
289             log.warn("Schema set {} does not exist or already deleted", schemaSetName);
290         }
291     }
292
293     private CmHandleRegistrationResponse registerNewCmHandle(final YangModelCmHandle yangModelCmHandle) {
294         try {
295             final String cmHandleJsonData = String.format("{\"cm-handles\":[%s]}",
296                     jsonObjectMapper.asJsonString(yangModelCmHandle));
297             cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
298                     cmHandleJsonData, NO_TIMESTAMP);
299             return CmHandleRegistrationResponse.createSuccessResponse(yangModelCmHandle.getId());
300         } catch (final AlreadyDefinedException alreadyDefinedException) {
301             return CmHandleRegistrationResponse.createFailureResponse(
302                     yangModelCmHandle.getId(), RegistrationError.CM_HANDLE_ALREADY_EXIST);
303         } catch (final Exception exception) {
304             return CmHandleRegistrationResponse.createFailureResponse(yangModelCmHandle.getId(), exception);
305         }
306     }
307 }