2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020-2022 Nordix Foundation
4 * Modifications Copyright (C) 2020-2022 Bell Canada.
5 * Modifications Copyright (C) 2021 Pantheon.tech
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.spi.impl;
25 import static com.google.common.base.Preconditions.checkNotNull;
27 import com.google.common.base.MoreObjects;
28 import com.google.common.collect.ImmutableSet;
29 import java.io.ByteArrayInputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.nio.charset.StandardCharsets;
33 import java.util.ArrayList;
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.Pattern;
41 import java.util.stream.Collectors;
42 import javax.transaction.Transactional;
43 import lombok.AllArgsConstructor;
44 import lombok.extern.slf4j.Slf4j;
45 import org.apache.commons.codec.digest.DigestUtils;
46 import org.apache.commons.lang3.StringUtils;
47 import org.hibernate.exception.ConstraintViolationException;
48 import org.onap.cps.spi.CpsAdminPersistenceService;
49 import org.onap.cps.spi.CpsModulePersistenceService;
50 import org.onap.cps.spi.entities.SchemaSetEntity;
51 import org.onap.cps.spi.entities.YangResourceEntity;
52 import org.onap.cps.spi.entities.YangResourceModuleReference;
53 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
54 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
55 import org.onap.cps.spi.exceptions.ModelValidationException;
56 import org.onap.cps.spi.model.ModuleReference;
57 import org.onap.cps.spi.repository.DataspaceRepository;
58 import org.onap.cps.spi.repository.ModuleReferenceRepository;
59 import org.onap.cps.spi.repository.SchemaSetRepository;
60 import org.onap.cps.spi.repository.YangResourceRepository;
61 import org.opendaylight.yangtools.yang.common.Revision;
62 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
66 import org.springframework.dao.DataIntegrityViolationException;
67 import org.springframework.retry.annotation.Backoff;
68 import org.springframework.retry.annotation.Retryable;
69 import org.springframework.stereotype.Component;
74 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
76 private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
77 private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
78 private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
79 .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
81 private YangResourceRepository yangResourceRepository;
83 private SchemaSetRepository schemaSetRepository;
85 private DataspaceRepository dataspaceRepository;
87 private CpsAdminPersistenceService cpsAdminPersistenceService;
89 private ModuleReferenceRepository moduleReferenceRepository;
92 public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
93 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
94 final var schemaSetEntity =
95 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
96 return schemaSetEntity.getYangResources().stream().collect(
97 Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
101 public Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
102 final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
103 return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
107 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
108 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
109 yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
110 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
111 .collect(Collectors.toList());
115 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
116 final String anchorName) {
117 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
118 yangResourceRepository
119 .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
120 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
121 .collect(Collectors.toList());
126 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
127 // can occur in case of specific concurrent requests.
128 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
129 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
130 public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
131 final Map<String, String> moduleReferenceNameToContentMap) {
132 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
133 final var yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
134 final var schemaSetEntity = new SchemaSetEntity();
135 schemaSetEntity.setName(schemaSetName);
136 schemaSetEntity.setDataspace(dataspaceEntity);
137 schemaSetEntity.setYangResources(yangResourceEntities);
139 schemaSetRepository.save(schemaSetEntity);
140 } catch (final DataIntegrityViolationException e) {
141 throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
147 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
148 // can occur in case of specific concurrent requests.
149 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
150 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
151 public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
152 final Map<String, String> newModuleNameToContentMap,
153 final Collection<ModuleReference> moduleReferences) {
154 storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
155 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
156 final var schemaSetEntity =
157 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
158 final List<Long> listOfYangResourceIds = new ArrayList<>();
159 moduleReferences.forEach(moduleReference ->
160 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
161 moduleReference.getModuleName(), moduleReference.getRevision())));
162 yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
167 public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
168 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
169 final var schemaSetEntity =
170 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
171 schemaSetRepository.delete(schemaSetEntity);
176 public void deleteUnusedYangResourceModules() {
177 yangResourceRepository.deleteOrphans();
181 public Collection<ModuleReference> identifyNewModuleReferences(
182 final Collection<ModuleReference> moduleReferencesToCheck) {
183 return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
186 private Set<YangResourceEntity> synchronizeYangResources(
187 final Map<String, String> moduleReferenceNameToContentMap) {
188 final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
190 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
191 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
193 final var yangResourceEntity = new YangResourceEntity();
194 yangResourceEntity.setName(entry.getKey());
195 yangResourceEntity.setContent(entry.getValue());
196 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
197 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
198 yangResourceEntity.setChecksum(checksum);
199 return yangResourceEntity;
201 .collect(Collectors.toMap(
202 YangResourceEntity::getChecksum,
206 final List<YangResourceEntity> existingYangResourceEntities =
207 yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
208 existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
210 final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
211 if (!newYangResourceEntities.isEmpty()) {
213 yangResourceRepository.saveAll(newYangResourceEntities);
214 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
215 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
216 // database constraint violation.
217 // If it is not, then throw the original exception
218 final Optional<DuplicatedYangResourceException> convertedException =
219 convertToDuplicatedYangResourceException(
220 dataIntegrityViolationException, newYangResourceEntities);
221 convertedException.ifPresent(
223 "Cannot persist duplicated yang resource. "
224 + "System will attempt this method up to 5 times.", e));
225 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
229 return ImmutableSet.<YangResourceEntity>builder()
230 .addAll(existingYangResourceEntities)
231 .addAll(newYangResourceEntities)
235 private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
236 final Map<String, String> metaDataMap = new HashMap<>();
237 final var revisionSourceIdentifier =
238 createIdentifierFromSourceName(checkNotNull(sourceName));
240 final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
242 protected MoreObjects.ToStringHelper addToStringAttributes(
243 final MoreObjects.ToStringHelper toStringHelper) {
244 return toStringHelper;
248 public InputStream openStream() {
249 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
253 final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
254 metaDataMap.put("moduleName", dependencyInfo.getName());
255 metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
256 } catch (final YangSyntaxErrorException | IOException e) {
257 throw new ModelValidationException("Yang resource is invalid.",
258 String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
263 private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
264 final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
265 if (matcher.matches()) {
266 return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
268 return RevisionSourceIdentifier.create(sourceName);
272 * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
273 * if the cause of the error is a yang checksum database constraint violation.
275 * @param originalException the original db exception.
276 * @param yangResourceEntities the collection of Yang resources involved in the db failure.
277 * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
278 * cause of the error is not a yang checksum database constraint violation.
280 private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
281 final DataIntegrityViolationException originalException,
282 final Collection<YangResourceEntity> yangResourceEntities) {
284 // The exception result
285 DuplicatedYangResourceException duplicatedYangResourceException = null;
287 final Throwable cause = originalException.getCause();
288 if (cause instanceof ConstraintViolationException) {
289 final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
290 if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
291 // Db constraint related to yang resource checksum uniqueness is not respected
292 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
293 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
294 duplicatedYangResourceException =
295 new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
299 return Optional.ofNullable(duplicatedYangResourceException);
304 * Get the name of the yang resource having the specified checksum.
306 * @param checksum the checksum. Null is supported.
307 * @param yangResourceEntities the list of yang resources to search among.
308 * @return the name found or null if none.
310 private String getNameForChecksum(
311 final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
313 yangResourceEntities.stream()
314 .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
316 .map(YangResourceEntity::getName)
321 * Get the checksum that caused the constraint violation exception.
323 * @param exception the exception having the checksum in error.
324 * @return the checksum in error or null if not found.
326 private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
327 String checksum = null;
328 final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
329 if (matcher.find() && matcher.groupCount() == 1) {
330 checksum = matcher.group(1);
335 private static ModuleReference toModuleReference(
336 final YangResourceModuleReference yangResourceModuleReference) {
337 return ModuleReference.builder()
338 .moduleName(yangResourceModuleReference.getModuleName())
339 .revision(yangResourceModuleReference.getRevision())