2 * ============LICENSE_START=======================================================
3 * Copyright (C) 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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.ncmp.init;
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;
29 import lombok.NonNull;
30 import lombok.RequiredArgsConstructor;
31 import lombok.extern.slf4j.Slf4j;
32 import org.onap.cps.api.CpsAdminService;
33 import org.onap.cps.api.CpsDataService;
34 import org.onap.cps.api.CpsModuleService;
35 import org.onap.cps.ncmp.api.impl.exception.NcmpStartUpException;
36 import org.onap.cps.spi.CascadeDeleteAllowed;
37 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
38 import org.onap.cps.utils.JsonObjectMapper;
39 import org.springframework.beans.factory.annotation.Value;
40 import org.springframework.boot.SpringApplication;
41 import org.springframework.boot.context.event.ApplicationReadyEvent;
44 @RequiredArgsConstructor
45 abstract class AbstractModelLoader implements ModelLoader {
47 private final CpsAdminService cpsAdminService;
48 private final CpsModuleService cpsModuleService;
49 private final CpsDataService cpsDataService;
51 private static final int EXIT_CODE_ON_ERROR = 1;
53 private final JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper());
55 @Value("${ncmp.model-loader.maximum-attempt-count:20}")
56 int maximumAttemptCount;
58 @Value("${ncmp.timers.model-loader.retry-time-ms:1000}")
62 public void onApplicationEvent(@NonNull final ApplicationReadyEvent applicationReadyEvent) {
64 onboardOrUpgradeModel();
65 } catch (final NcmpStartUpException ncmpStartUpException) {
66 log.error("Onboarding model for NCMP failed: {} ", ncmpStartUpException.getMessage());
67 SpringApplication.exit(applicationReadyEvent.getApplicationContext(), () -> EXIT_CODE_ON_ERROR);
71 void waitUntilDataspaceIsAvailable(final String dataspaceName) {
72 log.info("Model Loader start-up, waiting for database to be ready");
74 while (cpsAdminService.getDataspace(dataspaceName) == null) {
75 if (attemptCount < maximumAttemptCount) {
77 Thread.sleep(attemptCount * retryTimeMs);
78 log.info("Retrieving dataspace {} ... {} attempt(s) ", dataspaceName, ++attemptCount);
79 } catch (final InterruptedException e) {
80 Thread.currentThread().interrupt();
83 throw new NcmpStartUpException("Retrieval of NCMP dataspace failed",
84 dataspaceName + " not available (yet)");
89 void createSchemaSet(final String dataspaceName, final String schemaSetName, final String... resourceNames) {
91 final Map<String, String> yangResourcesContentMap = createYangResourcesToContentMap(resourceNames);
92 cpsModuleService.createSchemaSet(dataspaceName, schemaSetName, yangResourcesContentMap);
93 } catch (final AlreadyDefinedException alreadyDefinedException) {
94 log.warn("Creating new schema set failed as schema set already exists");
95 } catch (final Exception exception) {
96 log.error("Creating schema set failed: {} ", exception.getMessage());
97 throw new NcmpStartUpException("Creating schema set failed", exception.getMessage());
101 void deleteUnusedSchemaSets(final String dataspaceName, final String... schemaSetNames) {
102 for (final String schemaSetName : schemaSetNames) {
104 cpsModuleService.deleteSchemaSet(
105 dataspaceName, schemaSetName, CascadeDeleteAllowed.CASCADE_DELETE_PROHIBITED);
106 } catch (final Exception exception) {
107 log.warn("Deleting schema set failed: {} ", exception.getMessage());
112 void createAnchor(final String dataspaceName, final String schemaSetName, final String anchorName) {
114 cpsAdminService.createAnchor(dataspaceName, schemaSetName, anchorName);
115 } catch (final AlreadyDefinedException alreadyDefinedException) {
116 log.warn("Creating new anchor failed as anchor already exists");
117 } catch (final Exception exception) {
118 log.error("Creating anchor failed: {} ", exception.getMessage());
119 throw new NcmpStartUpException("Creating anchor failed", exception.getMessage());
123 void createTopLevelDataNode(final String dataspaceName, final String anchorName, final String dataNodeName) {
124 final String nodeData = jsonObjectMapper.asJsonString(Map.of(dataNodeName, Map.of()));
126 cpsDataService.saveData(dataspaceName, anchorName, nodeData, OffsetDateTime.now());
127 } catch (final AlreadyDefinedException exception) {
128 log.warn("Creating new data node '{}' failed as data node already exists", dataNodeName);
129 } catch (final Exception exception) {
130 log.error("Creating data node failed: {}", exception.getMessage());
131 throw new NcmpStartUpException("Creating data node failed", exception.getMessage());
135 void updateAnchorSchemaSet(final String dataspaceName, final String anchorName, final String schemaSetName) {
137 cpsAdminService.updateAnchorSchemaSet(dataspaceName, anchorName, schemaSetName);
138 } catch (final Exception exception) {
139 log.error("Updating schema set failed: {}", exception.getMessage());
140 throw new NcmpStartUpException("Updating schema set failed", exception.getMessage());
144 Map<String, String> createYangResourcesToContentMap(final String... resourceNames) {
145 final Map<String, String> yangResourcesToContentMap = new HashMap<>();
146 for (final String resourceName: resourceNames) {
147 yangResourcesToContentMap.put(resourceName, getFileContentAsString("models/" + resourceName));
149 return yangResourcesToContentMap;
152 private String getFileContentAsString(final String fileName) {
153 try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
154 return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
155 } catch (final Exception exception) {
156 final String message = String.format("Onboarding failed as unable to read file: %s", fileName);
158 throw new NcmpStartUpException(message, exception.getMessage());