8e17ab91669b7233223166923090f9edc1621b0b
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / inventory / sync / ModuleSyncService.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.impl.inventory.sync;
22
23 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME;
24 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
25 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
26 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
27
28 import java.time.OffsetDateTime;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Optional;
36 import lombok.RequiredArgsConstructor;
37 import lombok.extern.slf4j.Slf4j;
38 import org.apache.commons.lang3.StringUtils;
39 import org.onap.cps.api.CpsAdminService;
40 import org.onap.cps.api.CpsDataService;
41 import org.onap.cps.api.CpsModuleService;
42 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries;
43 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState;
44 import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
45 import org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory;
46 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations;
47 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
48 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
49 import org.onap.cps.spi.CascadeDeleteAllowed;
50 import org.onap.cps.spi.FetchDescendantsOption;
51 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException;
52 import org.onap.cps.spi.model.DataNode;
53 import org.onap.cps.spi.model.ModuleReference;
54 import org.onap.cps.utils.JsonObjectMapper;
55 import org.springframework.stereotype.Service;
56
57 @Slf4j
58 @Service
59 @RequiredArgsConstructor
60 public class ModuleSyncService {
61
62     private final DmiModelOperations dmiModelOperations;
63     private final CpsModuleService cpsModuleService;
64     private final CpsAdminService cpsAdminService;
65     private final CmHandleQueries cmHandleQueries;
66     private final CpsDataService cpsDataService;
67     private final JsonObjectMapper jsonObjectMapper;
68
69     /**
70      * This method registers a cm handle and initiates modules sync.
71      *
72      * @param upgradedCmHandle the yang model of cm handle.
73      */
74     public void syncAndCreateOrUpgradeSchemaSetAndAnchor(final YangModelCmHandle upgradedCmHandle) {
75
76         final String moduleSetTag = extractModuleSetTag(upgradedCmHandle.getCompositeState());
77         final Optional<DataNode> existingCmHandleWithSameModuleSetTag
78                 = getFirstReadyDataNodeWithModuleSetTag(moduleSetTag);
79
80         if (existingCmHandleWithSameModuleSetTag.isPresent()) {
81             upgradeUsingModuleSetTag(upgradedCmHandle, moduleSetTag);
82         } else {
83             syncAndCreateSchemaSetAndAnchor(upgradedCmHandle);
84         }
85         setCmHandleModuleSetTag(upgradedCmHandle, moduleSetTag);
86     }
87
88     private void syncAndCreateSchemaSetAndAnchor(final YangModelCmHandle yangModelCmHandle) {
89         final Collection<ModuleReference> allModuleReferencesFromCmHandle =
90                 dmiModelOperations.getModuleReferences(yangModelCmHandle);
91
92         final Collection<ModuleReference> identifiedNewModuleReferencesFromCmHandle = cpsModuleService
93                 .identifyNewModuleReferences(allModuleReferencesFromCmHandle);
94
95         final Map<String, String> newModuleNameToContentMap;
96         if (identifiedNewModuleReferencesFromCmHandle.isEmpty()) {
97             newModuleNameToContentMap = Collections.emptyMap();
98         } else {
99             newModuleNameToContentMap = dmiModelOperations.getNewYangResourcesFromDmi(yangModelCmHandle,
100                     identifiedNewModuleReferencesFromCmHandle);
101         }
102         createSchemaSetAndAnchor(yangModelCmHandle, newModuleNameToContentMap, allModuleReferencesFromCmHandle);
103     }
104
105     private void createSchemaSetAndAnchor(final YangModelCmHandle yangModelCmHandle,
106                                           final Map<String, String> newModuleNameToContentMap,
107                                           final Collection<ModuleReference> allModuleReferencesFromCmHandle) {
108         final String schemaSetAndAnchorName = yangModelCmHandle.getId();
109         cpsModuleService.createOrUpgradeSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,
110                 schemaSetAndAnchorName, newModuleNameToContentMap, allModuleReferencesFromCmHandle);
111         cpsAdminService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetAndAnchorName,
112             schemaSetAndAnchorName);
113     }
114
115     /**
116      * Deletes the SchemaSet for schema set id if the SchemaSet Exists.
117      *
118      * @param schemaSetId the schema set id to be deleted
119      */
120     public void deleteSchemaSetIfExists(final String schemaSetId) {
121         try {
122             cpsModuleService.deleteSchemaSet(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetId,
123                 CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED);
124             log.debug("SchemaSet for {} has been deleted. Ready to be recreated.", schemaSetId);
125         } catch (final SchemaSetNotFoundException e) {
126             log.debug("No SchemaSet for {}. Assuming CmHandle has not been previously Module Synced.", schemaSetId);
127         }
128     }
129
130     private Optional<DataNode> getFirstReadyDataNodeWithModuleSetTag(final String moduleSetTag) {
131         final List<DataNode> dataNodes = StringUtils.isNotBlank(moduleSetTag) ? cmHandleQueries
132                 .queryNcmpRegistryByCpsPath("//cm-handles[@module-set-tag='" + moduleSetTag + "']",
133                         FetchDescendantsOption.OMIT_DESCENDANTS) : Collections.emptyList();
134         return dataNodes.stream().filter(dataNode -> {
135             final String cmHandleId = YangDataConverter.extractCmHandleIdFromXpath(dataNode.getXpath());
136             return cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY);
137         }).findFirst();
138     }
139
140     private void setCmHandleModuleSetTag(final YangModelCmHandle upgradedCmHandle, final String moduleSetTag) {
141         final Map<String, Map<String, String>> dmiRegistryProperties = new HashMap<>(1);
142         final Map<String, String> cmHandleProperties = new HashMap<>(2);
143         cmHandleProperties.put("id", upgradedCmHandle.getId());
144         cmHandleProperties.put("module-set-tag", moduleSetTag);
145         dmiRegistryProperties.put("cm-handles", cmHandleProperties);
146         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
147                 jsonObjectMapper.asJsonString(dmiRegistryProperties), OffsetDateTime.now());
148     }
149
150     private void upgradeUsingModuleSetTag(final YangModelCmHandle upgradedCmHandle, final String moduleSetTag) {
151         log.info("Found cm handle having module set tag: {}", moduleSetTag);
152         final Collection<ModuleReference> moduleReferencesFromExistingCmHandle =
153                 cpsModuleService.getYangResourcesModuleReferences(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR);
154         final String upgradedSchemaSetAndAnchorName = upgradedCmHandle.getId();
155         final Map<String, String> noNewModules = Collections.emptyMap();
156         cpsModuleService.createOrUpgradeSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,
157                 upgradedSchemaSetAndAnchorName, noNewModules, moduleReferencesFromExistingCmHandle);
158     }
159
160     private static String extractModuleSetTag(final CompositeState compositeState) {
161         return compositeState.getLockReason() != null && compositeState.getLockReason().getLockReasonCategory()
162                 == LockReasonCategory.MODULE_UPGRADE
163                 ? Arrays.stream(compositeState.getLockReason().getDetails().split(":")).toList().get(1).trim()
164                 : StringUtils.EMPTY;
165     }
166
167 }