446e45b2b88f57484a2ceb42d1798c6bbdb97a87
[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 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
34 import com.fasterxml.jackson.core.JsonProcessingException;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.stream.Collectors;
40 import lombok.RequiredArgsConstructor;
41 import lombok.extern.slf4j.Slf4j;
42 import org.onap.cps.api.CpsAdminService;
43 import org.onap.cps.api.CpsDataService;
44 import org.onap.cps.api.CpsModuleService;
45 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
46 import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException;
47 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
48 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations;
49 import org.onap.cps.ncmp.api.impl.operations.DmiOperations;
50 import org.onap.cps.ncmp.api.models.CmHandle;
51 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
52 import org.onap.cps.ncmp.api.models.PersistenceCmHandle;
53 import org.onap.cps.ncmp.api.models.PersistenceCmHandlesList;
54 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
55 import org.onap.cps.spi.exceptions.DataValidationException;
56 import org.onap.cps.spi.model.ModuleReference;
57 import org.onap.cps.utils.JsonObjectMapper;
58 import org.springframework.http.ResponseEntity;
59 import org.springframework.stereotype.Service;
60
61 @Slf4j
62 @Service
63 @RequiredArgsConstructor
64 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
65
66     private final CpsDataService cpsDataService;
67
68     private final JsonObjectMapper jsonObjectMapper;
69
70     private final DmiDataOperations dmiDataOperations;
71
72     private final DmiModelOperations dmiModelOperations;
73
74     private final CpsModuleService cpsModuleService;
75
76     private final CpsAdminService cpsAdminService;
77
78     private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
79
80     @Override
81     public void updateDmiRegistrationAndSyncModule(final DmiPluginRegistration dmiPluginRegistration) {
82         dmiPluginRegistration.validateDmiPluginRegistration();
83         try {
84             if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
85                 parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration);
86             }
87             if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
88                 parseAndUpdateCmHandlesInDmiRegistration(dmiPluginRegistration);
89             }
90             parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration);
91         } catch (final JsonProcessingException | DataNodeNotFoundException e) {
92             final String errorMessage = String.format(
93                     "Error occurred while processing the CM-handle registration request, caused by : [%s]",
94                     e.getMessage());
95             throw new DataValidationException(errorMessage, e.getMessage(), e);
96         }
97     }
98
99     @Override
100     public Object getResourceDataOperationalForCmHandle(final String cmHandle,
101                                                         final String resourceIdentifier,
102                                                         final String acceptParamInHeader,
103                                                         final String optionsParamInQuery) {
104         return handleResponse(dmiDataOperations.getResourceDataFromDmi(
105             cmHandle,
106             resourceIdentifier,
107             optionsParamInQuery,
108             acceptParamInHeader,
109             DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL), "Not able to get resource data.");
110     }
111
112     @Override
113     public Object getResourceDataPassThroughRunningForCmHandle(final String cmHandle,
114                                                                final String resourceIdentifier,
115                                                                final String acceptParamInHeader,
116                                                                final String optionsParamInQuery) {
117         return handleResponse(dmiDataOperations.getResourceDataFromDmi(
118             cmHandle,
119             resourceIdentifier,
120             optionsParamInQuery,
121             acceptParamInHeader,
122             DmiOperations.DataStoreEnum.PASSTHROUGH_RUNNING), "Not able to get resource data.");
123     }
124
125     @Override
126     public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandle,
127                                                                final String resourceIdentifier,
128                                                                final OperationEnum operation,
129                                                                final String requestData,
130                                                                final String dataType) {
131         return handleResponse(
132             dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(
133                 cmHandle, resourceIdentifier, operation, requestData, dataType),
134             "Not able to " + operation + " resource data.");
135     }
136
137
138     @Override
139     public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandle) {
140         return cpsModuleService.getYangResourcesModuleReferences(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandle);
141     }
142
143     /**
144      * Retrieve cm handle identifiers for the given list of module names.
145      *
146      * @param moduleNames module names.
147      * @return a collection of anchor identifiers
148      */
149     @Override
150     public Collection<String> executeCmHandleHasAllModulesSearch(final Collection<String> moduleNames) {
151         return cpsAdminService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, moduleNames);
152     }
153
154     /**
155      * THis method registers a cm handle and intiates modules sync.
156      *
157      * @param dmiPluginRegistration dmi plugin registration information.
158      * @throws JsonProcessingException thrown if json is malformed or missing.
159      */
160     public void parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(
161         final DmiPluginRegistration dmiPluginRegistration) throws JsonProcessingException {
162         final PersistenceCmHandlesList createdPersistenceCmHandlesList =
163             getUpdatedPersistenceCmHandlesList(dmiPluginRegistration, dmiPluginRegistration.getCreatedCmHandles());
164         registerAndSyncNewCmHandles(createdPersistenceCmHandlesList);
165     }
166
167     private static Object handleResponse(final ResponseEntity<?> responseEntity,
168                                          final String exceptionMessage) {
169         if (responseEntity.getStatusCode().is2xxSuccessful()) {
170             return responseEntity.getBody();
171         } else {
172             throw new ServerNcmpException(exceptionMessage,
173                     "DMI status code: " + responseEntity.getStatusCodeValue()
174                             + ", DMI response body: " + responseEntity.getBody());
175         }
176     }
177
178     private void parseAndUpdateCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration) {
179         networkCmProxyDataServicePropertyHandler.updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles());
180     }
181
182     private PersistenceCmHandlesList getUpdatedPersistenceCmHandlesList(
183         final DmiPluginRegistration dmiPluginRegistration,
184         final List<CmHandle> updatedCmHandles) {
185         return PersistenceCmHandlesList.toPersistenceCmHandlesList(
186             dmiPluginRegistration.getDmiPlugin(),
187             dmiPluginRegistration.getDmiDataPlugin(),
188             dmiPluginRegistration.getDmiModelPlugin(),
189             updatedCmHandles);
190     }
191
192     private void registerAndSyncNewCmHandles(final PersistenceCmHandlesList persistenceCmHandlesList) {
193         final String cmHandleJsonData = jsonObjectMapper.asJsonString(persistenceCmHandlesList);
194         cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
195                 cmHandleJsonData, NO_TIMESTAMP);
196
197         for (final PersistenceCmHandle persistenceCmHandle : persistenceCmHandlesList.getPersistenceCmHandles()) {
198             syncModulesAndCreateAnchor(persistenceCmHandle);
199         }
200     }
201
202     protected void syncModulesAndCreateAnchor(final PersistenceCmHandle persistenceCmHandle) {
203         syncAndCreateSchemaSet(persistenceCmHandle);
204         createAnchor(persistenceCmHandle);
205     }
206
207     private void parseAndRemoveCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration) {
208         for (final String cmHandle : dmiPluginRegistration.getRemovedCmHandles()) {
209             try {
210                 attemptToDeleteSchemaSetWithCascade(cmHandle);
211                 cpsDataService.deleteListOrListElement(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
212                     "/dmi-registry/cm-handles[@id='" + cmHandle + "']", NO_TIMESTAMP);
213             } catch (final DataNodeNotFoundException e) {
214                 log.warn("Datanode {} not deleted message {}", cmHandle, e.getMessage());
215             }
216         }
217     }
218
219     private void attemptToDeleteSchemaSetWithCascade(final String schemaSetName) {
220         try {
221             cpsModuleService.deleteSchemaSet(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetName,
222                 CASCADE_DELETE_ALLOWED);
223         } catch (final Exception e) {
224             log.warn("Schema set {} delete failed, reason {}", schemaSetName, e.getMessage());
225         }
226     }
227
228     private void syncAndCreateSchemaSet(final PersistenceCmHandle persistenceCmHandle) {
229         final Collection<ModuleReference> moduleReferencesFromCmHandle =
230             dmiModelOperations.getModuleReferences(persistenceCmHandle);
231
232         final Collection<ModuleReference> identifiedNewModuleReferencesFromCmHandle = cpsModuleService
233             .identifyNewModuleReferences(moduleReferencesFromCmHandle);
234
235         final Collection<ModuleReference> existingModuleReferencesFromCmHandle =
236             moduleReferencesFromCmHandle.stream().filter(moduleReferenceFromCmHandle ->
237                 !identifiedNewModuleReferencesFromCmHandle.contains(moduleReferenceFromCmHandle)
238             ).collect(Collectors.toList());
239
240         final Map<String, String> newModuleNameToContentMap;
241         if (identifiedNewModuleReferencesFromCmHandle.isEmpty()) {
242             newModuleNameToContentMap = new HashMap<>();
243         } else {
244             newModuleNameToContentMap = dmiModelOperations.getNewYangResourcesFromDmi(persistenceCmHandle,
245                 identifiedNewModuleReferencesFromCmHandle);
246         }
247         cpsModuleService
248             .createSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, persistenceCmHandle.getId(),
249                 newModuleNameToContentMap, existingModuleReferencesFromCmHandle);
250     }
251
252     private void createAnchor(final PersistenceCmHandle persistenceCmHandle) {
253         cpsAdminService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, persistenceCmHandle.getId(),
254             persistenceCmHandle.getId());
255     }
256 }