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.retry.support.RetrySynchronizationManager;
70 import org.springframework.stereotype.Component;
75 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
77 private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
78 private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
79 private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
80 .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
82 private YangResourceRepository yangResourceRepository;
84 private SchemaSetRepository schemaSetRepository;
86 private DataspaceRepository dataspaceRepository;
88 private CpsAdminPersistenceService cpsAdminPersistenceService;
90 private ModuleReferenceRepository moduleReferenceRepository;
93 public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
94 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
95 final var schemaSetEntity =
96 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
97 return schemaSetEntity.getYangResources().stream().collect(
98 Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
102 public Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
103 final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
104 return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
108 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
109 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
110 yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
111 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
112 .collect(Collectors.toList());
116 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
117 final String anchorName) {
118 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
119 yangResourceRepository
120 .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
121 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
122 .collect(Collectors.toList());
127 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
128 // can occur in case of specific concurrent requests.
129 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
130 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
131 public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
132 final Map<String, String> moduleReferenceNameToContentMap) {
133 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
134 final var yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
135 final var schemaSetEntity = new SchemaSetEntity();
136 schemaSetEntity.setName(schemaSetName);
137 schemaSetEntity.setDataspace(dataspaceEntity);
138 schemaSetEntity.setYangResources(yangResourceEntities);
140 schemaSetRepository.save(schemaSetEntity);
141 } catch (final DataIntegrityViolationException e) {
142 throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
148 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
149 // can occur in case of specific concurrent requests.
150 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
151 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
152 public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
153 final Map<String, String> newModuleNameToContentMap,
154 final Collection<ModuleReference> moduleReferences) {
155 storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
156 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
157 final var schemaSetEntity =
158 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
159 final List<Long> listOfYangResourceIds = new ArrayList<>();
160 moduleReferences.forEach(moduleReference ->
161 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
162 moduleReference.getModuleName(), moduleReference.getRevision())));
163 yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
168 public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
169 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
170 final var schemaSetEntity =
171 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
172 schemaSetRepository.delete(schemaSetEntity);
177 public void deleteUnusedYangResourceModules() {
178 yangResourceRepository.deleteOrphans();
182 public Collection<ModuleReference> identifyNewModuleReferences(
183 final Collection<ModuleReference> moduleReferencesToCheck) {
184 return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
187 private Set<YangResourceEntity> synchronizeYangResources(
188 final Map<String, String> moduleReferenceNameToContentMap) {
189 final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
191 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
192 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
194 final var yangResourceEntity = new YangResourceEntity();
195 yangResourceEntity.setName(entry.getKey());
196 yangResourceEntity.setContent(entry.getValue());
197 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
198 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
199 yangResourceEntity.setChecksum(checksum);
200 return yangResourceEntity;
202 .collect(Collectors.toMap(
203 YangResourceEntity::getChecksum,
207 final List<YangResourceEntity> existingYangResourceEntities =
208 yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
209 existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
211 final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
212 if (!newYangResourceEntities.isEmpty()) {
214 yangResourceRepository.saveAll(newYangResourceEntities);
215 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
216 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
217 // database constraint violation.
218 // If it is not, then throw the original exception
219 final Optional<DuplicatedYangResourceException> convertedException =
220 convertToDuplicatedYangResourceException(
221 dataIntegrityViolationException, newYangResourceEntities);
222 convertedException.ifPresent(
224 int retryCount = RetrySynchronizationManager.getContext() == null ? 0
225 : RetrySynchronizationManager.getContext().getRetryCount();
226 log.warn("Cannot persist duplicated yang resource. System will attempt this method "
227 + "up to 5 times. Current retry count : {}", ++retryCount, e);
229 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
233 return ImmutableSet.<YangResourceEntity>builder()
234 .addAll(existingYangResourceEntities)
235 .addAll(newYangResourceEntities)
239 private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
240 final Map<String, String> metaDataMap = new HashMap<>();
241 final var revisionSourceIdentifier =
242 createIdentifierFromSourceName(checkNotNull(sourceName));
244 final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
246 protected MoreObjects.ToStringHelper addToStringAttributes(
247 final MoreObjects.ToStringHelper toStringHelper) {
248 return toStringHelper;
252 public InputStream openStream() {
253 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
257 final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
258 metaDataMap.put("moduleName", dependencyInfo.getName());
259 metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
260 } catch (final YangSyntaxErrorException | IOException e) {
261 throw new ModelValidationException("Yang resource is invalid.",
262 String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
267 private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
268 final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
269 if (matcher.matches()) {
270 return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
272 return RevisionSourceIdentifier.create(sourceName);
276 * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
277 * if the cause of the error is a yang checksum database constraint violation.
279 * @param originalException the original db exception.
280 * @param yangResourceEntities the collection of Yang resources involved in the db failure.
281 * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
282 * cause of the error is not a yang checksum database constraint violation.
284 private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
285 final DataIntegrityViolationException originalException,
286 final Collection<YangResourceEntity> yangResourceEntities) {
288 // The exception result
289 DuplicatedYangResourceException duplicatedYangResourceException = null;
291 final Throwable cause = originalException.getCause();
292 if (cause instanceof ConstraintViolationException) {
293 final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
294 if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
295 // Db constraint related to yang resource checksum uniqueness is not respected
296 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
297 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
298 duplicatedYangResourceException =
299 new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
303 return Optional.ofNullable(duplicatedYangResourceException);
308 * Get the name of the yang resource having the specified checksum.
310 * @param checksum the checksum. Null is supported.
311 * @param yangResourceEntities the list of yang resources to search among.
312 * @return the name found or null if none.
314 private String getNameForChecksum(
315 final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
317 yangResourceEntities.stream()
318 .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
320 .map(YangResourceEntity::getName)
325 * Get the checksum that caused the constraint violation exception.
327 * @param exception the exception having the checksum in error.
328 * @return the checksum in error or null if not found.
330 private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
331 String checksum = null;
332 final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
333 if (matcher.find() && matcher.groupCount() == 1) {
334 checksum = matcher.group(1);
339 private static ModuleReference toModuleReference(
340 final YangResourceModuleReference yangResourceModuleReference) {
341 return ModuleReference.builder()
342 .moduleName(yangResourceModuleReference.getModuleName())
343 .revision(yangResourceModuleReference.getRevision())