11c58235ec541ab2d354d5b9891b05044b93d2a9
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  Modifications Copyright (C) 2024 TechMahindra Ltd.
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  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.ncmp.api.impl;
24
25 import static org.onap.cps.ncmp.api.NcmpResponseStatus.ALTERNATE_ID_ALREADY_ASSOCIATED;
26 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
27 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
28 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.DMI_PROPERTY;
29 import static org.onap.cps.ncmp.api.impl.NetworkCmProxyDataServicePropertyHandler.PropertyType.PUBLIC_PROPERTY;
30 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME;
31 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
32 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
33
34 import com.google.common.collect.ImmutableMap;
35 import java.time.OffsetDateTime;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.LinkedHashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import lombok.RequiredArgsConstructor;
46 import lombok.extern.slf4j.Slf4j;
47 import org.onap.cps.api.CpsDataService;
48 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
49 import org.onap.cps.ncmp.api.impl.utils.AlternateIdChecker;
50 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
51 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
52 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
53 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
54 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
55 import org.onap.cps.spi.exceptions.DataValidationException;
56 import org.onap.cps.spi.model.DataNode;
57 import org.onap.cps.spi.model.DataNodeBuilder;
58 import org.onap.cps.utils.ContentType;
59 import org.onap.cps.utils.JsonObjectMapper;
60 import org.springframework.stereotype.Service;
61 import org.springframework.util.StringUtils;
62
63 @Slf4j
64 @Service
65 @RequiredArgsConstructor
66 //Accepting the security hotspot as the string checked is generated from inside code and not user input.
67 @SuppressWarnings("squid:S5852")
68 public class NetworkCmProxyDataServicePropertyHandler {
69
70     private final InventoryPersistence inventoryPersistence;
71     private final CpsDataService cpsDataService;
72     private final JsonObjectMapper jsonObjectMapper;
73     private final AlternateIdChecker alternateIdChecker;
74
75     /**
76      * Iterates over incoming updatedNcmpServiceCmHandles and update the dataNodes based on the updated attributes.
77      * The attributes which are not passed will remain as is.
78      *
79      * @param updatedNcmpServiceCmHandles collection of CmHandles
80      */
81     public List<CmHandleRegistrationResponse> updateCmHandleProperties(
82             final Collection<NcmpServiceCmHandle> updatedNcmpServiceCmHandles) {
83         final Collection<String> rejectedCmHandleIds = alternateIdChecker
84             .getIdsOfCmHandlesWithRejectedAlternateId(updatedNcmpServiceCmHandles, AlternateIdChecker.Operation.UPDATE);
85         final List<CmHandleRegistrationResponse> failureResponses =
86             CmHandleRegistrationResponse.createFailureResponses(rejectedCmHandleIds, ALTERNATE_ID_ALREADY_ASSOCIATED);
87         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>(failureResponses);
88         for (final NcmpServiceCmHandle updatedNcmpServiceCmHandle : updatedNcmpServiceCmHandles) {
89             final String cmHandleId = updatedNcmpServiceCmHandle.getCmHandleId();
90             if (!rejectedCmHandleIds.contains(cmHandleId)) {
91                 try {
92                     final DataNode existingCmHandleDataNode = inventoryPersistence
93                             .getCmHandleDataNodeByCmHandleId(cmHandleId).iterator().next();
94                     processUpdates(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
95                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
96                 } catch (final DataNodeNotFoundException e) {
97                     log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}", cmHandleId,
98                             e.getMessage());
99                     cmHandleRegistrationResponses.add(
100                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
101                 } catch (final DataValidationException e) {
102                     log.error("Unable to update cm handle : {}, caused by : {}", cmHandleId, e.getMessage());
103                     cmHandleRegistrationResponses.add(
104                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
105                 } catch (final Exception exception) {
106                     log.error("Unable to update cmHandle : {} , caused by : {}", cmHandleId, exception.getMessage());
107                     cmHandleRegistrationResponses.add(
108                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception));
109                 }
110             }
111         }
112         return cmHandleRegistrationResponses;
113     }
114
115     private void processUpdates(final DataNode existingCmHandleDataNode,
116                                 final NcmpServiceCmHandle updatedNcmpServiceCmHandle) {
117         setAndUpdateCmHandleField(
118             updatedNcmpServiceCmHandle.getCmHandleId(), "alternate-id", updatedNcmpServiceCmHandle.getAlternateId());
119         updateDataProducerIdentifier(existingCmHandleDataNode, updatedNcmpServiceCmHandle);
120         if (!updatedNcmpServiceCmHandle.getPublicProperties().isEmpty()) {
121             updateProperties(existingCmHandleDataNode, PUBLIC_PROPERTY,
122                 updatedNcmpServiceCmHandle.getPublicProperties());
123         }
124         if (!updatedNcmpServiceCmHandle.getDmiProperties().isEmpty()) {
125             updateProperties(existingCmHandleDataNode, DMI_PROPERTY, updatedNcmpServiceCmHandle.getDmiProperties());
126         }
127     }
128
129     private void updateDataProducerIdentifier(final DataNode cmHandleDataNode,
130                                               final NcmpServiceCmHandle ncmpServiceCmHandle) {
131         final String newDataProducerIdentifier = ncmpServiceCmHandle.getDataProducerIdentifier();
132         if (StringUtils.hasText(newDataProducerIdentifier)) {
133             final YangModelCmHandle yangModelCmHandle =
134                 YangDataConverter.convertCmHandleToYangModel(cmHandleDataNode);
135             final String existingDataProducerIdentifier = yangModelCmHandle.getDataProducerIdentifier();
136             if (StringUtils.hasText(existingDataProducerIdentifier)) {
137                 if (!existingDataProducerIdentifier.equals(newDataProducerIdentifier)) {
138                     log.warn("Unable to update dataProducerIdentifier for cmHandle {}. "
139                             + "Value for dataProducerIdentifier has been set previously.",
140                         ncmpServiceCmHandle.getCmHandleId());
141                 }
142             } else {
143                 setAndUpdateCmHandleField(
144                     yangModelCmHandle.getId(), "data-producer-identifier", newDataProducerIdentifier);
145             }
146         }
147     }
148
149     private void updateProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType,
150                                   final Map<String, String> updatedProperties) {
151         final Collection<DataNode> replacementPropertyDataNodes =
152                 getReplacementDataNodes(existingCmHandleDataNode, propertyType, updatedProperties);
153         replacementPropertyDataNodes.addAll(
154                 getUnchangedPropertyDataNodes(existingCmHandleDataNode, propertyType, updatedProperties));
155         if (replacementPropertyDataNodes.isEmpty()) {
156             removeAllProperties(existingCmHandleDataNode, propertyType);
157         } else {
158             inventoryPersistence.replaceListContent(existingCmHandleDataNode.getXpath(), replacementPropertyDataNodes);
159         }
160     }
161
162     private void removeAllProperties(final DataNode existingCmHandleDataNode, final PropertyType propertyType) {
163         existingCmHandleDataNode.getChildDataNodes().forEach(dataNode -> {
164             final Matcher matcher = propertyType.propertyXpathPattern.matcher(dataNode.getXpath());
165             if (matcher.find()) {
166                 log.info("Deleting dataNode with xpath : [{}]", dataNode.getXpath());
167                 inventoryPersistence.deleteDataNode(dataNode.getXpath());
168             }
169         });
170     }
171
172     private Collection<DataNode> getUnchangedPropertyDataNodes(final DataNode existingCmHandleDataNode,
173                                                                final PropertyType propertyType,
174                                                                final Map<String, String> updatedProperties) {
175         final Collection<DataNode> unchangedPropertyDataNodes = new HashSet<>();
176         for (final DataNode existingPropertyDataNode : existingCmHandleDataNode.getChildDataNodes()) {
177             final Matcher matcher = propertyType.propertyXpathPattern.matcher(existingPropertyDataNode.getXpath());
178             if (matcher.find()) {
179                 final String keyName = matcher.group(2);
180                 if (!updatedProperties.containsKey(keyName)) {
181                     unchangedPropertyDataNodes.add(existingPropertyDataNode);
182                 }
183             }
184         }
185         return unchangedPropertyDataNodes;
186     }
187
188     private Collection<DataNode> getReplacementDataNodes(final DataNode existingCmHandleDataNode,
189                                                          final PropertyType propertyType,
190                                                          final Map<String, String> updatedProperties) {
191         final Collection<DataNode> replacementPropertyDataNodes = new HashSet<>();
192         updatedProperties.forEach((updatedAttributeKey, updatedAttributeValue) -> {
193             final String propertyXpath = getAttributeXpath(existingCmHandleDataNode, propertyType, updatedAttributeKey);
194             if (updatedAttributeValue != null) {
195                 log.info("Creating a new DataNode with xpath {} , key : {} and value : {}", propertyXpath,
196                         updatedAttributeKey, updatedAttributeValue);
197                 replacementPropertyDataNodes.add(
198                         buildDataNode(propertyXpath, updatedAttributeKey, updatedAttributeValue));
199             }
200         });
201         return replacementPropertyDataNodes;
202     }
203
204     private String getAttributeXpath(final DataNode cmHandle, final PropertyType propertyType,
205                                      final String attributeKey) {
206         return cmHandle.getXpath() + "/" + propertyType.xpathPrefix + String.format("[@name='%s']", attributeKey);
207     }
208
209     private DataNode buildDataNode(final String xpath, final String attributeKey, final String attributeValue) {
210         final Map<String, String> updatedLeaves = new LinkedHashMap<>(1);
211         updatedLeaves.put("name", attributeKey);
212         updatedLeaves.put("value", attributeValue);
213         log.debug("Building a new node with xpath {} with leaves (name : {} , value : {})", xpath, attributeKey,
214                 attributeValue);
215         return new DataNodeBuilder().withXpath(xpath).withLeaves(ImmutableMap.copyOf(updatedLeaves)).build();
216     }
217
218     private void setAndUpdateCmHandleField(final String cmHandleIdToUpdate, final String fieldName,
219                                            final String newFieldValue) {
220         final Map<String, Map<String, String>> dmiRegistryData = new HashMap<>(1);
221         final Map<String, String> cmHandleData = new HashMap<>(2);
222         cmHandleData.put("id", cmHandleIdToUpdate);
223         cmHandleData.put(fieldName, newFieldValue);
224         dmiRegistryData.put("cm-handles", cmHandleData);
225         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
226                 jsonObjectMapper.asJsonString(dmiRegistryData), OffsetDateTime.now(), ContentType.JSON);
227         log.debug("Updating {} for cmHandle {} with value : {})", fieldName, cmHandleIdToUpdate, newFieldValue);
228     }
229
230     enum PropertyType {
231         DMI_PROPERTY("additional-properties"), PUBLIC_PROPERTY("public-properties");
232
233         private static final String LIST_INDEX_PATTERN = "\\[@(\\w+)[^\\/]'([^']+)']";
234
235         final String xpathPrefix;
236         final Pattern propertyXpathPattern;
237
238         PropertyType(final String xpathPrefix) {
239             this.xpathPrefix = xpathPrefix;
240             this.propertyXpathPattern = Pattern.compile(xpathPrefix + LIST_INDEX_PATTERN);
241         }
242     }
243 }