2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Nordix Foundation
4 * Modifications Copyright (C) 2020-2021 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.CascadeDeleteAllowed;
48 import org.onap.cps.spi.CpsAdminPersistenceService;
49 import org.onap.cps.spi.CpsModulePersistenceService;
50 import org.onap.cps.spi.entities.AnchorEntity;
51 import org.onap.cps.spi.entities.SchemaSetEntity;
52 import org.onap.cps.spi.entities.YangResourceEntity;
53 import org.onap.cps.spi.entities.YangResourceModuleReference;
54 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
55 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
56 import org.onap.cps.spi.exceptions.ModelValidationException;
57 import org.onap.cps.spi.exceptions.SchemaSetInUseException;
58 import org.onap.cps.spi.model.ModuleReference;
59 import org.onap.cps.spi.repository.AnchorRepository;
60 import org.onap.cps.spi.repository.DataspaceRepository;
61 import org.onap.cps.spi.repository.FragmentRepository;
62 import org.onap.cps.spi.repository.SchemaSetRepository;
63 import org.onap.cps.spi.repository.YangResourceRepository;
64 import org.opendaylight.yangtools.yang.common.Revision;
65 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
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.rfc7950.repo.YangModelDependencyInfo;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.dao.DataIntegrityViolationException;
71 import org.springframework.retry.annotation.Backoff;
72 import org.springframework.retry.annotation.Retryable;
73 import org.springframework.stereotype.Component;
78 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
80 private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
81 private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
82 private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
83 .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
86 private YangResourceRepository yangResourceRepository;
89 private SchemaSetRepository schemaSetRepository;
92 private DataspaceRepository dataspaceRepository;
95 private AnchorRepository anchorRepository;
98 private FragmentRepository fragmentRepository;
101 private CpsAdminPersistenceService cpsAdminPersistenceService;
104 public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
105 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
106 final var schemaSetEntity =
107 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
108 return schemaSetEntity.getYangResources().stream().collect(
109 Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
113 public Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
114 final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
115 return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
119 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
120 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
121 yangResourceRepository.findAllModuleReferences(dataspaceName);
122 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
123 .collect(Collectors.toList());
127 public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
128 final String anchorName) {
129 final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
130 yangResourceRepository
131 .findAllModuleReferences(dataspaceName, anchorName);
132 return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
133 .collect(Collectors.toList());
138 // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
139 // can occur in case of specific concurrent requests.
140 @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 2, backoff = @Backoff(delay = 500))
141 public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
142 final Map<String, String> yangResourcesNameToContentMap) {
144 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
145 final var yangResourceEntities = synchronizeYangResources(yangResourcesNameToContentMap);
146 final var schemaSetEntity = new SchemaSetEntity();
147 schemaSetEntity.setName(schemaSetName);
148 schemaSetEntity.setDataspace(dataspaceEntity);
149 schemaSetEntity.setYangResources(yangResourceEntities);
151 schemaSetRepository.save(schemaSetEntity);
152 } catch (final DataIntegrityViolationException e) {
153 throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
159 public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
160 final Map<String, String> newYangResourcesModuleNameToContentMap,
161 final List<ModuleReference> moduleReferences) {
162 storeSchemaSet(dataspaceName, schemaSetName, newYangResourcesModuleNameToContentMap);
163 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
164 final var schemaSetEntity =
165 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
166 final List<Long> listOfYangResourceIds = new ArrayList<>();
167 moduleReferences.forEach(moduleReference ->
168 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
169 moduleReference.getModuleName(), moduleReference.getRevision())));
170 yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
175 public void deleteSchemaSet(final String dataspaceName, final String schemaSetName,
176 final CascadeDeleteAllowed cascadeDeleteAllowed) {
177 final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
178 final var schemaSetEntity =
179 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
181 final Collection<AnchorEntity> anchorEntities = anchorRepository.findAllBySchemaSet(schemaSetEntity);
182 if (!anchorEntities.isEmpty()) {
183 if (cascadeDeleteAllowed != CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED) {
184 throw new SchemaSetInUseException(dataspaceName, schemaSetName);
186 fragmentRepository.deleteByAnchorIn(anchorEntities);
187 anchorRepository.deleteAll(anchorEntities);
189 schemaSetRepository.delete(schemaSetEntity);
190 yangResourceRepository.deleteOrphans();
193 private Set<YangResourceEntity> synchronizeYangResources(final Map<String, String> yangResourcesNameToContentMap) {
194 final Map<String, YangResourceEntity> checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream()
196 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
197 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
199 final var yangResourceEntity = new YangResourceEntity();
200 yangResourceEntity.setName(entry.getKey());
201 yangResourceEntity.setContent(entry.getValue());
202 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
203 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
204 yangResourceEntity.setChecksum(checksum);
205 return yangResourceEntity;
207 .collect(Collectors.toMap(
208 YangResourceEntity::getChecksum,
212 final List<YangResourceEntity> existingYangResourceEntities =
213 yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
214 existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
216 final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
217 if (!newYangResourceEntities.isEmpty()) {
219 yangResourceRepository.saveAll(newYangResourceEntities);
220 } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
221 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
222 // database constraint violation.
223 // If it is not, then throw the original exception
224 final Optional<DuplicatedYangResourceException> convertedException =
225 convertToDuplicatedYangResourceException(
226 dataIntegrityViolationException, newYangResourceEntities);
227 convertedException.ifPresent(
229 "Cannot persist duplicated yang resource. "
230 + "A total of 2 attempts to store the schema set are planned.", e));
231 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
235 return ImmutableSet.<YangResourceEntity>builder()
236 .addAll(existingYangResourceEntities)
237 .addAll(newYangResourceEntities)
241 private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
242 final Map<String, String> metaDataMap = new HashMap<>();
243 final var revisionSourceIdentifier =
244 createIdentifierFromSourceName(checkNotNull(sourceName));
246 final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
248 protected MoreObjects.ToStringHelper addToStringAttributes(
249 final MoreObjects.ToStringHelper toStringHelper) {
250 return toStringHelper;
254 public InputStream openStream() {
255 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
259 final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
260 metaDataMap.put("moduleName", dependencyInfo.getName());
261 metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
262 } catch (final YangSyntaxErrorException | IOException e) {
263 throw new ModelValidationException("Yang resource is invalid.",
264 String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
269 private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
270 final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
271 if (matcher.matches()) {
272 return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
274 return RevisionSourceIdentifier.create(sourceName);
278 * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
279 * if the cause of the error is a yang checksum database constraint violation.
280 * @param originalException the original db exception.
281 * @param yangResourceEntities the collection of Yang resources involved in the db failure.
282 * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
283 * cause of the error is not a yang checksum database constraint violation.
285 private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
286 final DataIntegrityViolationException originalException,
287 final Collection<YangResourceEntity> yangResourceEntities) {
289 // The exception result
290 DuplicatedYangResourceException duplicatedYangResourceException = null;
292 final Throwable cause = originalException.getCause();
293 if (cause instanceof ConstraintViolationException) {
294 final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
295 if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
296 // Db constraint related to yang resource checksum uniqueness is not respected
297 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
298 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
299 duplicatedYangResourceException =
300 new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
304 return Optional.ofNullable(duplicatedYangResourceException);
309 * 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.
326 * @param exception the exception having the checksum in error.
327 * @return the checksum in error or null if not found.
329 private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
330 String checksum = null;
331 final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
332 if (matcher.find() && matcher.groupCount() == 1) {
333 checksum = matcher.group(1);
338 private static ModuleReference toModuleReference(
339 final YangResourceModuleReference yangResourceModuleReference) {
340 return ModuleReference.builder()
341 .moduleName(yangResourceModuleReference.getModuleName())
342 .revision(yangResourceModuleReference.getRevision())