2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 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.extern.slf4j.Slf4j;
44 import org.apache.commons.codec.digest.DigestUtils;
45 import org.apache.commons.lang3.StringUtils;
46 import org.hibernate.exception.ConstraintViolationException;
47 import org.onap.cps.spi.CpsAdminPersistenceService;
48 import org.onap.cps.spi.CpsModulePersistenceService;
49 import org.onap.cps.spi.entities.SchemaSetEntity;
50 import org.onap.cps.spi.entities.YangResourceEntity;
51 import org.onap.cps.spi.entities.YangResourceModuleReference;
52 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
53 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
54 import org.onap.cps.spi.exceptions.ModelValidationException;
55 import org.onap.cps.spi.model.ModuleReference;
56 import org.onap.cps.spi.repository.AnchorRepository;
57 import org.onap.cps.spi.repository.DataspaceRepository;
58 import org.onap.cps.spi.repository.FragmentRepository;
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.beans.factory.annotation.Autowired;
67 import org.springframework.dao.DataIntegrityViolationException;
68 import org.springframework.retry.annotation.Backoff;
69 import org.springframework.retry.annotation.Retryable;
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);
83 private YangResourceRepository yangResourceRepository;
86 private SchemaSetRepository schemaSetRepository;
89 private DataspaceRepository dataspaceRepository;
92 private AnchorRepository anchorRepository;
95 private FragmentRepository fragmentRepository;
98 private CpsAdminPersistenceService cpsAdminPersistenceService;
101 public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
102 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
103 final var schemaSetEntity =
104 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
105 return schemaSetEntity.getYangResources().stream().collect(
106 Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
110 public Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
111 final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
112 return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
116 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
117 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
118 yangResourceRepository.findAllModuleReferences(dataspaceName);
119 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
120 .collect(Collectors.toList());
124 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
125 final String anchorName) {
126 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
127 yangResourceRepository
128 .findAllModuleReferences(dataspaceName, anchorName);
129 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
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> yangResourcesNameToContentMap) {
141 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
142 final var yangResourceEntities = synchronizeYangResources(yangResourcesNameToContentMap);
143 final var 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);
156 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
157 // can occur in case of specific concurrent requests.
158 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
159 @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
160 public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
161 final Map<String, String> newYangResourcesModuleNameToContentMap,
162 final List<ModuleReference> moduleReferences) {
163 storeSchemaSet(dataspaceName, schemaSetName, newYangResourcesModuleNameToContentMap);
164 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
165 final var schemaSetEntity =
166 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
167 final List<Long> listOfYangResourceIds = new ArrayList<>();
168 moduleReferences.forEach(moduleReference ->
169 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
170 moduleReference.getModuleName(), moduleReference.getRevision())));
171 yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
176 public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
177 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
178 final var schemaSetEntity =
179 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
180 schemaSetRepository.delete(schemaSetEntity);
185 public void deleteUnusedYangResourceModules() {
186 yangResourceRepository.deleteOrphans();
189 private Set<YangResourceEntity> synchronizeYangResources(final Map<String, String> yangResourcesNameToContentMap) {
190 final Map<String, YangResourceEntity> checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream()
192 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
193 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
195 final var yangResourceEntity = new YangResourceEntity();
196 yangResourceEntity.setName(entry.getKey());
197 yangResourceEntity.setContent(entry.getValue());
198 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
199 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
200 yangResourceEntity.setChecksum(checksum);
201 return yangResourceEntity;
203 .collect(Collectors.toMap(
204 YangResourceEntity::getChecksum,
208 final List<YangResourceEntity> existingYangResourceEntities =
209 yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
210 existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
212 final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
213 if (!newYangResourceEntities.isEmpty()) {
215 yangResourceRepository.saveAll(newYangResourceEntities);
216 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
217 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
218 // database constraint violation.
219 // If it is not, then throw the original exception
220 final Optional<DuplicatedYangResourceException> convertedException =
221 convertToDuplicatedYangResourceException(
222 dataIntegrityViolationException, newYangResourceEntities);
223 convertedException.ifPresent(
225 "Cannot persist duplicated yang resource. "
226 + "System will attempt this method up to 5 times.", e));
227 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
231 return ImmutableSet.<YangResourceEntity>builder()
232 .addAll(existingYangResourceEntities)
233 .addAll(newYangResourceEntities)
237 private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
238 final Map<String, String> metaDataMap = new HashMap<>();
239 final var revisionSourceIdentifier =
240 createIdentifierFromSourceName(checkNotNull(sourceName));
242 final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
244 protected MoreObjects.ToStringHelper addToStringAttributes(
245 final MoreObjects.ToStringHelper toStringHelper) {
246 return toStringHelper;
250 public InputStream openStream() {
251 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
255 final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
256 metaDataMap.put("moduleName", dependencyInfo.getName());
257 metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
258 } catch (final YangSyntaxErrorException | IOException e) {
259 throw new ModelValidationException("Yang resource is invalid.",
260 String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
265 private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
266 final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
267 if (matcher.matches()) {
268 return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
270 return RevisionSourceIdentifier.create(sourceName);
274 * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
275 * if the cause of the error is a yang checksum database constraint violation.
277 * @param originalException the original db exception.
278 * @param yangResourceEntities the collection of Yang resources involved in the db failure.
279 * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
280 * cause of the error is not a yang checksum database constraint violation.
282 private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
283 final DataIntegrityViolationException originalException,
284 final Collection<YangResourceEntity> yangResourceEntities) {
286 // The exception result
287 DuplicatedYangResourceException duplicatedYangResourceException = null;
289 final Throwable cause = originalException.getCause();
290 if (cause instanceof ConstraintViolationException) {
291 final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
292 if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
293 // Db constraint related to yang resource checksum uniqueness is not respected
294 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
295 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
296 duplicatedYangResourceException =
297 new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
301 return Optional.ofNullable(duplicatedYangResourceException);
306 * Get the name of the yang resource having the specified checksum.
308 * @param checksum the checksum. Null is supported.
309 * @param yangResourceEntities the list of yang resources to search among.
310 * @return the name found or null if none.
312 private String getNameForChecksum(
313 final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
315 yangResourceEntities.stream()
316 .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
318 .map(YangResourceEntity::getName)
323 * Get the checksum that caused the constraint violation exception.
325 * @param exception the exception having the checksum in error.
326 * @return the checksum in error or null if not found.
328 private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
329 String checksum = null;
330 final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
331 if (matcher.find() && matcher.groupCount() == 1) {
332 checksum = matcher.group(1);
337 private static ModuleReference toModuleReference(
338 final YangResourceModuleReference yangResourceModuleReference) {
339 return ModuleReference.builder()
340 .moduleName(yangResourceModuleReference.getModuleName())
341 .revision(yangResourceModuleReference.getRevision())