2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020-2023 Nordix Foundation
4 * Modifications Copyright (C) 2020-2022 Bell Canada.
5 * Modifications Copyright (C) 2021 Pantheon.tech
6 * Modifications Copyright (C) 2022 TechMahindra Ltd.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.spi.impl;
26 import static com.google.common.base.Preconditions.checkNotNull;
28 import com.google.common.base.MoreObjects;
29 import com.google.common.collect.ImmutableSet;
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.StandardCharsets;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.List;
38 import java.util.Optional;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
43 import javax.transaction.Transactional;
44 import lombok.RequiredArgsConstructor;
45 import lombok.extern.slf4j.Slf4j;
46 import org.apache.commons.codec.digest.DigestUtils;
47 import org.apache.commons.lang3.StringUtils;
48 import org.hibernate.exception.ConstraintViolationException;
49 import org.onap.cps.spi.CpsAdminPersistenceService;
50 import org.onap.cps.spi.CpsModulePersistenceService;
51 import org.onap.cps.spi.entities.DataspaceEntity;
52 import org.onap.cps.spi.entities.SchemaSetEntity;
53 import org.onap.cps.spi.entities.YangResourceEntity;
54 import org.onap.cps.spi.entities.YangResourceModuleReference;
55 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
56 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
57 import org.onap.cps.spi.exceptions.ModelValidationException;
58 import org.onap.cps.spi.model.ModuleDefinition;
59 import org.onap.cps.spi.model.ModuleReference;
60 import org.onap.cps.spi.model.SchemaSet;
61 import org.onap.cps.spi.repository.DataspaceRepository;
62 import org.onap.cps.spi.repository.ModuleReferenceRepository;
63 import org.onap.cps.spi.repository.SchemaSetRepository;
64 import org.onap.cps.spi.repository.YangResourceRepository;
65 import org.opendaylight.yangtools.yang.common.Revision;
66 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
68 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
69 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
70 import org.springframework.dao.DataIntegrityViolationException;
71 import org.springframework.retry.annotation.Backoff;
72 import org.springframework.retry.annotation.Retryable;
73 import org.springframework.retry.support.RetrySynchronizationManager;
74 import org.springframework.stereotype.Component;
78 @RequiredArgsConstructor
79 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
81 private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
82 private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
83 private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
84 .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
86 private final YangResourceRepository yangResourceRepository;
88 private final SchemaSetRepository schemaSetRepository;
90 private final DataspaceRepository dataspaceRepository;
92 private final CpsAdminPersistenceService cpsAdminPersistenceService;
94 private final ModuleReferenceRepository moduleReferenceRepository;
97 public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
98 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
99 final SchemaSetEntity schemaSetEntity =
100 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
101 return schemaSetEntity.getYangResources().stream().collect(
102 Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent));
106 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
107 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
108 yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
109 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
110 .collect(Collectors.toList());
114 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
115 final String anchorName) {
116 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
117 yangResourceRepository
118 .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
119 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
120 .collect(Collectors.toList());
124 public Collection<ModuleDefinition> getYangResourceDefinitions(final String dataspaceName,
125 final String anchorName) {
126 final Set<YangResourceEntity> yangResourceEntities =
127 yangResourceRepository
128 .findAllModuleDefinitionsByDataspaceAndAnchor(dataspaceName, anchorName);
129 return yangResourceEntities.stream().map(CpsModulePersistenceServiceImpl::toModuleDefinition)
130 .collect(Collectors.toList());
135 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
136 // can occur in case of specific concurrent requests.
137 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
138 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
139 public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
140 final Map<String, String> moduleReferenceNameToContentMap) {
141 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
142 final Set<YangResourceEntity> yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
143 final SchemaSetEntity schemaSetEntity = new SchemaSetEntity();
144 schemaSetEntity.setName(schemaSetName);
145 schemaSetEntity.setDataspace(dataspaceEntity);
146 schemaSetEntity.setYangResources(yangResourceEntities);
148 schemaSetRepository.save(schemaSetEntity);
149 } catch (final DataIntegrityViolationException e) {
150 throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
155 public Collection<SchemaSet> getSchemaSetsByDataspaceName(final String dataspaceName) {
156 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
157 final List<SchemaSetEntity> schemaSetEntities = schemaSetRepository.findByDataspace(dataspaceEntity);
158 return schemaSetEntities.stream()
159 .map(CpsModulePersistenceServiceImpl::toSchemaSet).collect(Collectors.toList());
164 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
165 // can occur in case of specific concurrent requests.
166 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
167 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
168 public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
169 final Map<String, String> newModuleNameToContentMap,
170 final Collection<ModuleReference> allModuleReferences) {
171 storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
172 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
173 final SchemaSetEntity schemaSetEntity =
174 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
175 final List<Integer> allYangResourceIds =
176 yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
177 yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), allYangResourceIds);
182 public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
183 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
184 final SchemaSetEntity schemaSetEntity =
185 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
186 schemaSetRepository.delete(schemaSetEntity);
191 public void deleteSchemaSets(final String dataspaceName, final Collection<String> schemaSetNames) {
192 final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
193 schemaSetRepository.deleteByDataspaceAndNameIn(dataspaceEntity, schemaSetNames);
198 public void deleteUnusedYangResourceModules() {
199 yangResourceRepository.deleteOrphans();
203 public Collection<ModuleReference> identifyNewModuleReferences(
204 final Collection<ModuleReference> moduleReferencesToCheck) {
205 return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
208 private Set<YangResourceEntity> synchronizeYangResources(
209 final Map<String, String> moduleReferenceNameToContentMap) {
210 final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
212 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
213 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
215 final YangResourceEntity yangResourceEntity = new YangResourceEntity();
216 yangResourceEntity.setFileName(entry.getKey());
217 yangResourceEntity.setContent(entry.getValue());
218 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
219 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
220 yangResourceEntity.setChecksum(checksum);
221 return yangResourceEntity;
223 .collect(Collectors.toMap(
224 YangResourceEntity::getChecksum,
228 final List<YangResourceEntity> existingYangResourceEntities =
229 yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
230 existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
232 final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
233 if (!newYangResourceEntities.isEmpty()) {
235 yangResourceRepository.saveAll(newYangResourceEntities);
236 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
237 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
238 // database constraint violation.
239 // If it is not, then throw the original exception
240 final Optional<DuplicatedYangResourceException> convertedException =
241 convertToDuplicatedYangResourceException(
242 dataIntegrityViolationException, newYangResourceEntities);
243 convertedException.ifPresent(
245 int retryCount = RetrySynchronizationManager.getContext() == null ? 0
246 : RetrySynchronizationManager.getContext().getRetryCount();
247 log.warn("Cannot persist duplicated yang resource. System will attempt this method "
248 + "up to 5 times. Current retry count : {}", ++retryCount, e);
250 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
254 return ImmutableSet.<YangResourceEntity>builder()
255 .addAll(existingYangResourceEntities)
256 .addAll(newYangResourceEntities)
260 private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
261 final Map<String, String> metaDataMap = new HashMap<>();
262 final RevisionSourceIdentifier revisionSourceIdentifier =
263 createIdentifierFromSourceName(checkNotNull(sourceName));
265 final YangTextSchemaSource tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
267 public Optional<String> getSymbolicName() {
268 return Optional.empty();
272 protected MoreObjects.ToStringHelper addToStringAttributes(
273 final MoreObjects.ToStringHelper toStringHelper) {
274 return toStringHelper;
278 public InputStream openStream() {
279 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
283 final YangModelDependencyInfo yangModelDependencyInfo
284 = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
285 metaDataMap.put("moduleName", yangModelDependencyInfo.getName());
286 metaDataMap.put("revision", yangModelDependencyInfo.getFormattedRevision());
287 } catch (final YangSyntaxErrorException | IOException e) {
288 throw new ModelValidationException("Yang resource is invalid.",
289 String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
294 private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
295 final Matcher matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
296 if (matcher.matches()) {
297 return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
299 return RevisionSourceIdentifier.create(sourceName);
303 * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
304 * if the cause of the error is a yang checksum database constraint violation.
306 * @param originalException the original db exception.
307 * @param yangResourceEntities the collection of Yang resources involved in the db failure.
308 * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
309 * cause of the error is not a yang checksum database constraint violation.
311 private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
312 final DataIntegrityViolationException originalException,
313 final Collection<YangResourceEntity> yangResourceEntities) {
315 // The exception result
316 DuplicatedYangResourceException duplicatedYangResourceException = null;
318 final Throwable cause = originalException.getCause();
319 if (cause instanceof ConstraintViolationException) {
320 final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
321 if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
322 // Db constraint related to yang resource checksum uniqueness is not respected
323 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
324 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
325 duplicatedYangResourceException =
326 new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
330 return Optional.ofNullable(duplicatedYangResourceException);
334 private String getNameForChecksum(final String checksum,
335 final Collection<YangResourceEntity> yangResourceEntities) {
336 final Optional<String> optionalFileName = yangResourceEntities.stream()
337 .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
339 .map(YangResourceEntity::getFileName);
340 if (optionalFileName.isPresent()) {
341 return optionalFileName.get();
343 return "no filename";
346 private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
347 final Matcher matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
348 if (matcher.find()) {
349 return matcher.group(1);
351 return "no checksum found";
354 private static ModuleReference toModuleReference(
355 final YangResourceModuleReference yangResourceModuleReference) {
356 return ModuleReference.builder()
357 .moduleName(yangResourceModuleReference.getModuleName())
358 .revision(yangResourceModuleReference.getRevision())
362 private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
363 return new ModuleDefinition(
364 yangResourceEntity.getModuleName(),
365 yangResourceEntity.getRevision(),
366 yangResourceEntity.getContent());
369 private static SchemaSet toSchemaSet(final SchemaSetEntity schemaSetEntity) {
370 return SchemaSet.builder().name(schemaSetEntity.getName())
371 .dataspaceName(schemaSetEntity.getDataspace().getName()).build();