Merge "[k6] Refactor k6 tests for CM handle searches"
[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-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2024 TechMahindra Ltd.
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.impl.inventory.sync;
23
24 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DATASPACE_NAME;
25 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_ANCHOR;
26 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
27 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
28
29 import java.time.OffsetDateTime;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Map;
34 import lombok.AllArgsConstructor;
35 import lombok.RequiredArgsConstructor;
36 import lombok.extern.slf4j.Slf4j;
37 import org.apache.commons.lang3.StringUtils;
38 import org.onap.cps.api.CpsAnchorService;
39 import org.onap.cps.api.CpsDataService;
40 import org.onap.cps.api.CpsModuleService;
41 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries;
42 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState;
43 import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations;
44 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
45 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
46 import org.onap.cps.spi.CascadeDeleteAllowed;
47 import org.onap.cps.spi.FetchDescendantsOption;
48 import org.onap.cps.spi.exceptions.SchemaSetNotFoundException;
49 import org.onap.cps.spi.model.DataNode;
50 import org.onap.cps.spi.model.ModuleReference;
51 import org.onap.cps.utils.ContentType;
52 import org.onap.cps.utils.JsonObjectMapper;
53 import org.springframework.stereotype.Service;
54
55 @Slf4j
56 @Service
57 @RequiredArgsConstructor
58 public class ModuleSyncService {
59
60     private final DmiModelOperations dmiModelOperations;
61     private final CpsModuleService cpsModuleService;
62     private final CmHandleQueries cmHandleQueries;
63     private final CpsDataService cpsDataService;
64     private final CpsAnchorService cpsAnchorService;
65     private final JsonObjectMapper jsonObjectMapper;
66     private static final Map<String, String> NO_NEW_MODULES = Collections.emptyMap();
67
68     @AllArgsConstructor
69     private static final class ModuleDelta {
70         Collection<ModuleReference> allModuleReferences;
71         Map<String, String> newModuleNameToContentMap;
72     }
73
74     /**
75      * This method creates a cm handle and initiates modules sync.
76      *
77      * @param yangModelCmHandle the yang model of cm handle.
78      */
79     public void syncAndCreateSchemaSetAndAnchor(final YangModelCmHandle yangModelCmHandle) {
80         final ModuleDelta moduleDelta = getModuleDelta(yangModelCmHandle, yangModelCmHandle.getModuleSetTag());
81         final String cmHandleId = yangModelCmHandle.getId();
82         cpsModuleService.createSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId,
83                 moduleDelta.newModuleNameToContentMap, moduleDelta.allModuleReferences);
84         cpsAnchorService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId, cmHandleId);
85     }
86
87     /**
88      * This method upgrades a cm handle and initiates modules sync.
89      *
90      * @param yangModelCmHandle the yang model of cm handle.
91      */
92     public void syncAndUpgradeSchemaSet(final YangModelCmHandle yangModelCmHandle) {
93         final String upgradedModuleSetTag = ModuleOperationsUtils.getUpgradedModuleSetTagFromLockReason(
94                 yangModelCmHandle.getCompositeState().getLockReason());
95         final ModuleDelta moduleDelta = getModuleDelta(yangModelCmHandle, upgradedModuleSetTag);
96         cpsModuleService.upgradeSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME,
97                 yangModelCmHandle.getId(), moduleDelta.newModuleNameToContentMap, moduleDelta.allModuleReferences);
98         setCmHandleModuleSetTag(yangModelCmHandle, upgradedModuleSetTag);
99     }
100
101     /**
102      * Deletes the SchemaSet for schema set id if the SchemaSet Exists.
103      *
104      * @param schemaSetId the schema set id to be deleted
105      */
106     public void deleteSchemaSetIfExists(final String schemaSetId) {
107         try {
108             cpsModuleService.deleteSchemaSet(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetId,
109                 CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED);
110             log.debug("SchemaSet for {} has been deleted. Ready to be recreated.", schemaSetId);
111         } catch (final SchemaSetNotFoundException e) {
112             log.debug("No SchemaSet for {}. Assuming CmHandle has not been previously Module Synced.", schemaSetId);
113         }
114     }
115
116     private ModuleDelta getModuleDelta(final YangModelCmHandle yangModelCmHandle, final String targetModuleSetTag) {
117         final Collection<ModuleReference> allModuleReferences;
118         final Map<String, String> newYangResources;
119
120         final YangModelCmHandle cmHandleWithSameModuleSetTag = getAnyReadyCmHandleByModuleSetTag(targetModuleSetTag);
121         if (cmHandleWithSameModuleSetTag == null) {
122             allModuleReferences = dmiModelOperations.getModuleReferences(yangModelCmHandle);
123             newYangResources = dmiModelOperations.getNewYangResourcesFromDmi(yangModelCmHandle,
124                     cpsModuleService.identifyNewModuleReferences(allModuleReferences));
125         } else {
126             log.info("Found other cm handle having same module set tag: {}", targetModuleSetTag);
127             allModuleReferences = cpsModuleService.getYangResourcesModuleReferences(
128                     NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleWithSameModuleSetTag.getId());
129             newYangResources = NO_NEW_MODULES;
130         }
131         return new ModuleDelta(allModuleReferences, newYangResources);
132     }
133
134     private YangModelCmHandle getAnyReadyCmHandleByModuleSetTag(final String moduleSetTag) {
135         if (StringUtils.isBlank(moduleSetTag)) {
136             return null;
137         }
138         final String escapedModuleSetTag = moduleSetTag.replace("'", "''");
139         final List<DataNode> dataNodes = cmHandleQueries.queryNcmpRegistryByCpsPath(
140                 NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@module-set-tag='" + escapedModuleSetTag + "']",
141                 FetchDescendantsOption.DIRECT_CHILDREN_ONLY);
142         return dataNodes.stream().map(YangDataConverter::convertCmHandleToYangModel)
143                 .filter(cmHandle -> cmHandle.getCompositeState().getCmHandleState() == CmHandleState.READY)
144                 .findFirst().orElse(null);
145     }
146
147     private void setCmHandleModuleSetTag(final YangModelCmHandle yangModelCmHandle, final String newModuleSetTag) {
148         final String jsonForUpdate = jsonObjectMapper.asJsonString(Map.of(
149                 "cm-handles", Map.of("id", yangModelCmHandle.getId(), "module-set-tag", newModuleSetTag)));
150         cpsDataService.updateNodeLeaves(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
151                 jsonForUpdate, OffsetDateTime.now(), ContentType.JSON);
152     }
153 }