a3ebec3c541439a48c6961ddabd8d07e436b5970
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / init / AbstractModelLoader.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2023-2024 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.init;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import java.io.InputStream;
25 import java.nio.charset.StandardCharsets;
26 import java.time.OffsetDateTime;
27 import java.util.HashMap;
28 import java.util.Map;
29 import lombok.NonNull;
30 import lombok.RequiredArgsConstructor;
31 import lombok.extern.slf4j.Slf4j;
32 import org.onap.cps.api.CpsAnchorService;
33 import org.onap.cps.api.CpsDataService;
34 import org.onap.cps.api.CpsDataspaceService;
35 import org.onap.cps.api.CpsModuleService;
36 import org.onap.cps.ncmp.api.impl.exception.NcmpStartUpException;
37 import org.onap.cps.spi.CascadeDeleteAllowed;
38 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
39 import org.onap.cps.utils.JsonObjectMapper;
40 import org.springframework.beans.factory.annotation.Value;
41 import org.springframework.boot.SpringApplication;
42 import org.springframework.boot.context.event.ApplicationReadyEvent;
43
44 @Slf4j
45 @RequiredArgsConstructor
46 abstract class AbstractModelLoader implements ModelLoader {
47
48     private final CpsDataspaceService cpsDataspaceService;
49     private final CpsModuleService cpsModuleService;
50     private final CpsAnchorService cpsAnchorService;
51     protected final CpsDataService cpsDataService;
52
53     private static final int EXIT_CODE_ON_ERROR = 1;
54
55     private final JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper());
56
57     @Value("${ncmp.model-loader.maximum-attempt-count:20}")
58     int maximumAttemptCount;
59
60     @Value("${ncmp.timers.model-loader.retry-time-ms:1000}")
61     long retryTimeMs;
62
63     @Override
64     public void onApplicationEvent(@NonNull final ApplicationReadyEvent applicationReadyEvent) {
65         try {
66             onboardOrUpgradeModel();
67         } catch (final NcmpStartUpException ncmpStartUpException) {
68             log.error("Onboarding model for NCMP failed: {} ", ncmpStartUpException.getMessage());
69             SpringApplication.exit(applicationReadyEvent.getApplicationContext(), () -> EXIT_CODE_ON_ERROR);
70         }
71     }
72
73     void waitUntilDataspaceIsAvailable(final String dataspaceName) {
74         log.info("Model Loader start-up, waiting for database to be ready");
75         int attemptCount = 0;
76         while (cpsDataspaceService.getDataspace(dataspaceName) == null) {
77             if (attemptCount < maximumAttemptCount) {
78                 try {
79                     Thread.sleep(attemptCount * retryTimeMs);
80                     log.info("Retrieving dataspace {} ... {} attempt(s) ", dataspaceName, ++attemptCount);
81                 } catch (final InterruptedException e) {
82                     Thread.currentThread().interrupt();
83                 }
84             } else {
85                 throw new NcmpStartUpException("Retrieval of NCMP dataspace failed",
86                     dataspaceName + " not available (yet)");
87             }
88         }
89     }
90
91     void createSchemaSet(final String dataspaceName, final String schemaSetName, final String... resourceNames) {
92         try {
93             final Map<String, String> yangResourcesContentMap = createYangResourcesToContentMap(resourceNames);
94             cpsModuleService.createSchemaSet(dataspaceName, schemaSetName, yangResourcesContentMap);
95         } catch (final AlreadyDefinedException alreadyDefinedException) {
96             log.warn("Creating new schema set failed as schema set already exists");
97         } catch (final Exception exception) {
98             log.error("Creating schema set failed: {} ", exception.getMessage());
99             throw new NcmpStartUpException("Creating schema set failed", exception.getMessage());
100         }
101     }
102
103     void deleteUnusedSchemaSets(final String dataspaceName, final String... schemaSetNames) {
104         for (final String schemaSetName : schemaSetNames) {
105             try {
106                 cpsModuleService.deleteSchemaSet(
107                     dataspaceName, schemaSetName, CascadeDeleteAllowed.CASCADE_DELETE_PROHIBITED);
108             } catch (final Exception exception) {
109                 log.warn("Deleting schema set failed: {} ", exception.getMessage());
110             }
111         }
112     }
113
114     void createAnchor(final String dataspaceName, final String schemaSetName, final String anchorName) {
115         try {
116             cpsAnchorService.createAnchor(dataspaceName, schemaSetName, anchorName);
117         } catch (final AlreadyDefinedException alreadyDefinedException) {
118             log.warn("Creating new anchor failed as anchor already exists");
119         } catch (final Exception exception) {
120             log.error("Creating anchor failed: {} ", exception.getMessage());
121             throw new NcmpStartUpException("Creating anchor failed", exception.getMessage());
122         }
123     }
124
125     void createTopLevelDataNode(final String dataspaceName, final String anchorName, final String dataNodeName) {
126         final String nodeData = jsonObjectMapper.asJsonString(Map.of(dataNodeName, Map.of()));
127         try {
128             cpsDataService.saveData(dataspaceName, anchorName, nodeData, OffsetDateTime.now());
129         } catch (final AlreadyDefinedException exception) {
130             log.warn("Creating new data node '{}' failed as data node already exists", dataNodeName);
131         } catch (final Exception exception) {
132             log.error("Creating data node failed: {}", exception.getMessage());
133             throw new NcmpStartUpException("Creating data node failed", exception.getMessage());
134         }
135     }
136
137     void updateAnchorSchemaSet(final String dataspaceName, final String anchorName, final String schemaSetName) {
138         try {
139             cpsAnchorService.updateAnchorSchemaSet(dataspaceName, anchorName, schemaSetName);
140         } catch (final Exception exception) {
141             log.error("Updating schema set failed: {}", exception.getMessage());
142             throw new NcmpStartUpException("Updating schema set failed", exception.getMessage());
143         }
144     }
145
146     Map<String, String> createYangResourcesToContentMap(final String... resourceNames) {
147         final Map<String, String> yangResourcesToContentMap = new HashMap<>();
148         for (final String resourceName: resourceNames) {
149             yangResourcesToContentMap.put(resourceName, getFileContentAsString("models/" + resourceName));
150         }
151         return yangResourcesToContentMap;
152     }
153
154     private String getFileContentAsString(final String fileName) {
155         try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
156             return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
157         } catch (final Exception exception) {
158             final String message = String.format("Onboarding failed as unable to read file: %s", fileName);
159             log.debug(message);
160             throw new NcmpStartUpException(message, exception.getMessage());
161         }
162     }
163
164 }