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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.ncmp.api.impl;
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;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.LinkedHashMap;
38 import java.util.List;
40 import java.util.UUID;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
43 import lombok.RequiredArgsConstructor;
44 import lombok.extern.slf4j.Slf4j;
45 import org.onap.cps.api.CpsAdminService;
46 import org.onap.cps.api.CpsDataService;
47 import org.onap.cps.api.CpsModuleService;
48 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
49 import org.onap.cps.ncmp.api.impl.exception.HttpClientRequestException;
50 import org.onap.cps.ncmp.api.impl.exception.InvalidTopicException;
51 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
52 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations;
53 import org.onap.cps.ncmp.api.impl.operations.DmiOperations;
54 import org.onap.cps.ncmp.api.impl.operations.YangModelCmHandleRetriever;
55 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
56 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
57 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError;
58 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
59 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
60 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
61 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
62 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
63 import org.onap.cps.spi.exceptions.DataValidationException;
64 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException;
65 import org.onap.cps.spi.model.ModuleReference;
66 import org.onap.cps.utils.CpsValidator;
67 import org.onap.cps.utils.JsonObjectMapper;
68 import org.springframework.http.HttpStatus;
69 import org.springframework.http.ResponseEntity;
70 import org.springframework.stereotype.Service;
74 @RequiredArgsConstructor
75 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
77 private final CpsDataService cpsDataService;
79 private final JsonObjectMapper jsonObjectMapper;
81 private final DmiDataOperations dmiDataOperations;
83 private final DmiModelOperations dmiModelOperations;
85 private final CpsModuleService cpsModuleService;
87 private final CpsAdminService cpsAdminService;
89 private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
91 private final YangModelCmHandleRetriever yangModelCmHandleRetriever;
93 // valid kafka topic name regex
94 private static final Pattern TOPIC_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9]([._-](?![._-])|"
95 + "[a-zA-Z0-9]){0,120}[a-zA-Z0-9]$");
96 private static final String NO_REQUEST_ID = null;
97 private static final String NO_TOPIC = null;
100 public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
101 final DmiPluginRegistration dmiPluginRegistration) {
102 dmiPluginRegistration.validateDmiPluginRegistration();
103 final var dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
104 dmiPluginRegistrationResponse.setRemovedCmHandles(
105 parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration.getRemovedCmHandles()));
106 if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
107 dmiPluginRegistrationResponse.setCreatedCmHandles(
108 parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration));
110 if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
111 dmiPluginRegistrationResponse.setUpdatedCmHandles(
112 networkCmProxyDataServicePropertyHandler
113 .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
115 return dmiPluginRegistrationResponse;
119 public Object getResourceDataOperationalForCmHandle(final String cmHandleId,
120 final String resourceIdentifier,
121 final String optionsParamInQuery,
122 final String topicParamInQuery) {
123 CpsValidator.validateNameCharacters(cmHandleId);
124 return validateTopicNameAndGetResourceData(cmHandleId, resourceIdentifier,
125 DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL, optionsParamInQuery, topicParamInQuery);
129 public Object getResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
130 final String resourceIdentifier,
131 final String optionsParamInQuery,
132 final String topicParamInQuery) {
133 CpsValidator.validateNameCharacters(cmHandleId);
134 return validateTopicNameAndGetResourceData(cmHandleId, resourceIdentifier,
135 DmiOperations.DataStoreEnum.PASSTHROUGH_RUNNING, optionsParamInQuery, topicParamInQuery);
139 public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
140 final String resourceIdentifier,
141 final OperationEnum operation,
142 final String requestData,
143 final String dataType) {
144 CpsValidator.validateNameCharacters(cmHandleId);
145 return handleResponse(
146 dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier, operation,
147 requestData, dataType), operation);
152 public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
153 CpsValidator.validateNameCharacters(cmHandleId);
154 return cpsModuleService.getYangResourcesModuleReferences(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId);
158 * Retrieve cm handle identifiers for the given list of module names.
160 * @param moduleNames module names.
161 * @return a collection of anchor identifiers
164 public Collection<String> executeCmHandleHasAllModulesSearch(final Collection<String> moduleNames) {
165 return cpsAdminService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, moduleNames);
169 * Retrieve cm handle details for a given cm handle.
171 * @param cmHandleId cm handle identifier
172 * @return cm handle details
175 public NcmpServiceCmHandle getNcmpServiceCmHandle(final String cmHandleId) {
176 CpsValidator.validateNameCharacters(cmHandleId);
177 final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
178 final YangModelCmHandle yangModelCmHandle =
179 yangModelCmHandleRetriever.getDmiServiceNamesAndProperties(cmHandleId);
180 final List<YangModelCmHandle.Property> dmiProperties = yangModelCmHandle.getDmiProperties();
181 final List<YangModelCmHandle.Property> publicProperties = yangModelCmHandle.getPublicProperties();
182 ncmpServiceCmHandle.setCmHandleID(yangModelCmHandle.getId());
183 setDmiProperties(dmiProperties, ncmpServiceCmHandle);
184 setPublicProperties(publicProperties, ncmpServiceCmHandle);
185 return ncmpServiceCmHandle;
188 private void setDmiProperties(final List<YangModelCmHandle.Property> dmiProperties,
189 final NcmpServiceCmHandle ncmpServiceCmHandle) {
190 final Map<String, String> dmiPropertiesMap = new LinkedHashMap<>(dmiProperties.size());
191 asPropertiesMap(dmiProperties, dmiPropertiesMap);
192 ncmpServiceCmHandle.setDmiProperties(dmiPropertiesMap);
195 private void setPublicProperties(final List<YangModelCmHandle.Property> publicProperties,
196 final NcmpServiceCmHandle ncmpServiceCmHandle) {
197 final Map<String, String> publicPropertiesMap = new LinkedHashMap<>();
198 asPropertiesMap(publicProperties, publicPropertiesMap);
199 ncmpServiceCmHandle.setPublicProperties(publicPropertiesMap);
202 private void asPropertiesMap(final List<YangModelCmHandle.Property> properties,
203 final Map<String, String> propertiesMap) {
204 for (final YangModelCmHandle.Property property: properties) {
205 propertiesMap.put(property.getName(), property.getValue());
210 * THis method registers a cm handle and initiates modules sync.
212 * @param dmiPluginRegistration dmi plugin registration information.
213 * @return cm-handle registration response for create cm-handle requests.
215 public List<CmHandleRegistrationResponse> parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(
216 final DmiPluginRegistration dmiPluginRegistration) {
217 return dmiPluginRegistration.getCreatedCmHandles().stream()
219 YangModelCmHandle.toYangModelCmHandle(
220 dmiPluginRegistration.getDmiPlugin(),
221 dmiPluginRegistration.getDmiDataPlugin(),
222 dmiPluginRegistration.getDmiModelPlugin(), cmHandle)
224 .map(this::registerAndSyncNewCmHandle)
225 .collect(Collectors.toList());
228 private static Object handleResponse(final ResponseEntity<?> responseEntity, final OperationEnum operation) {
229 if (responseEntity.getStatusCode().is2xxSuccessful()) {
230 return responseEntity.getBody();
232 final String exceptionMessage = "Unable to " + operation.toString() + " resource data.";
233 throw new HttpClientRequestException(exceptionMessage, (String) responseEntity.getBody(),
234 responseEntity.getStatusCodeValue());
238 private CmHandleRegistrationResponse registerAndSyncNewCmHandle(final YangModelCmHandle yangModelCmHandle) {
240 CpsValidator.validateNameCharacters(yangModelCmHandle.getId());
241 final String cmHandleJsonData = String.format("{\"cm-handles\":[%s]}",
242 jsonObjectMapper.asJsonString(yangModelCmHandle));
243 cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
244 cmHandleJsonData, NO_TIMESTAMP);
245 syncModulesAndCreateAnchor(yangModelCmHandle);
246 return CmHandleRegistrationResponse.createSuccessResponse(yangModelCmHandle.getId());
247 } catch (final AlreadyDefinedException alreadyDefinedException) {
248 return CmHandleRegistrationResponse.createFailureResponse(
249 yangModelCmHandle.getId(), RegistrationError.CM_HANDLE_ALREADY_EXIST);
250 } catch (final DataValidationException dataValidationException) {
251 return CmHandleRegistrationResponse.createFailureResponse(yangModelCmHandle.getId(),
252 RegistrationError.CM_HANDLE_INVALID_ID);
253 } catch (final Exception exception) {
254 return CmHandleRegistrationResponse.createFailureResponse(yangModelCmHandle.getId(), exception);
258 protected void syncModulesAndCreateAnchor(final YangModelCmHandle yangModelCmHandle) {
259 syncAndCreateSchemaSet(yangModelCmHandle);
260 createAnchor(yangModelCmHandle);
263 protected List<CmHandleRegistrationResponse> parseAndRemoveCmHandlesInDmiRegistration(
264 final List<String> tobeRemovedCmHandles) {
265 final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
266 new ArrayList<>(tobeRemovedCmHandles.size());
267 for (final String cmHandle : tobeRemovedCmHandles) {
269 CpsValidator.validateNameCharacters(cmHandle);
270 deleteSchemaSetWithCascade(cmHandle);
271 cpsDataService.deleteListOrListElement(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
272 "/dmi-registry/cm-handles[@id='" + cmHandle + "']", NO_TIMESTAMP);
273 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandle));
274 } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
275 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
276 cmHandle, dataNodeNotFoundException.getMessage());
277 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse
278 .createFailureResponse(cmHandle, RegistrationError.CM_HANDLE_DOES_NOT_EXIST));
279 } catch (final DataValidationException dataValidationException) {
280 log.error("Unable to de-register cm-handle id: {}, caused by: {}",
281 cmHandle, dataValidationException.getMessage());
282 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse
283 .createFailureResponse(cmHandle, RegistrationError.CM_HANDLE_INVALID_ID));
284 } catch (final Exception exception) {
285 log.error("Unable to de-register cm-handle id : {} , caused by : {}",
286 cmHandle, exception.getMessage());
287 cmHandleRegistrationResponses.add(
288 CmHandleRegistrationResponse.createFailureResponse(cmHandle, exception));
291 return cmHandleRegistrationResponses;
294 private void deleteSchemaSetWithCascade(final String schemaSetName) {
296 cpsModuleService.deleteSchemaSet(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetName,
297 CASCADE_DELETE_ALLOWED);
298 } catch (final SchemaSetNotFoundException schemaSetNotFoundException) {
299 log.warn("Schema set {} does not exist or already deleted", schemaSetName);
303 private void syncAndCreateSchemaSet(final YangModelCmHandle yangModelCmHandle) {
304 final Collection<ModuleReference> moduleReferencesFromCmHandle =
305 dmiModelOperations.getModuleReferences(yangModelCmHandle);
307 final Collection<ModuleReference> identifiedNewModuleReferencesFromCmHandle = cpsModuleService
308 .identifyNewModuleReferences(moduleReferencesFromCmHandle);
310 final Collection<ModuleReference> existingModuleReferencesFromCmHandle =
311 moduleReferencesFromCmHandle.stream().filter(moduleReferenceFromCmHandle ->
312 !identifiedNewModuleReferencesFromCmHandle.contains(moduleReferenceFromCmHandle)
313 ).collect(Collectors.toList());
315 final Map<String, String> newModuleNameToContentMap;
316 if (identifiedNewModuleReferencesFromCmHandle.isEmpty()) {
317 newModuleNameToContentMap = new HashMap<>();
319 newModuleNameToContentMap = dmiModelOperations.getNewYangResourcesFromDmi(yangModelCmHandle,
320 identifiedNewModuleReferencesFromCmHandle);
323 .createSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, yangModelCmHandle.getId(),
324 newModuleNameToContentMap, existingModuleReferencesFromCmHandle);
327 private void createAnchor(final YangModelCmHandle yangModelCmHandle) {
328 cpsAdminService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, yangModelCmHandle.getId(),
329 yangModelCmHandle.getId());
332 private static boolean hasTopicParameter(final String topicName) {
333 if (topicName == null) {
336 if (TOPIC_NAME_PATTERN.matcher(topicName).matches()) {
339 throw new InvalidTopicException("Topic name " + topicName + " is invalid", "invalid topic");
342 private Map<String, Object> buildDmiResponse(final String requestId) {
343 final Map<String, Object> dmiResponseMap = new HashMap<>();
344 dmiResponseMap.put("requestId", requestId);
345 return dmiResponseMap;
348 private Object validateTopicNameAndGetResourceData(final String cmHandleId,
349 final String resourceIdentifier,
350 final DmiOperations.DataStoreEnum dataStore,
351 final String optionsParamInQuery,
352 final String topicParamInQuery) {
353 final boolean processAsynchronously = hasTopicParameter(topicParamInQuery);
354 if (processAsynchronously) {
355 final String resourceDataRequestId = UUID.randomUUID().toString();
356 return ResponseEntity.status(HttpStatus.OK)
357 .body(buildDmiResponse(resourceDataRequestId));
359 final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(
360 cmHandleId, resourceIdentifier, optionsParamInQuery, dataStore, NO_REQUEST_ID, NO_TOPIC);
361 return handleResponse(responseEntity, OperationEnum.READ);