Merge "Issue with CPSData API to add an item to an existing list node"
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsModulePersistenceServiceImpl.java
1 /*
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
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.spi.impl;
24
25 import static com.google.common.base.Preconditions.checkNotNull;
26
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.Collection;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.regex.Pattern;
40 import java.util.stream.Collectors;
41 import javax.transaction.Transactional;
42 import lombok.extern.slf4j.Slf4j;
43 import org.apache.commons.codec.digest.DigestUtils;
44 import org.apache.commons.lang3.StringUtils;
45 import org.hibernate.exception.ConstraintViolationException;
46 import org.onap.cps.spi.CascadeDeleteAllowed;
47 import org.onap.cps.spi.CpsAdminPersistenceService;
48 import org.onap.cps.spi.CpsModulePersistenceService;
49 import org.onap.cps.spi.entities.AnchorEntity;
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.exceptions.SchemaSetInUseException;
57 import org.onap.cps.spi.model.ModuleReference;
58 import org.onap.cps.spi.repository.AnchorRepository;
59 import org.onap.cps.spi.repository.DataspaceRepository;
60 import org.onap.cps.spi.repository.FragmentRepository;
61 import org.onap.cps.spi.repository.SchemaSetRepository;
62 import org.onap.cps.spi.repository.YangResourceRepository;
63 import org.opendaylight.yangtools.yang.common.Revision;
64 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
65 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.dao.DataIntegrityViolationException;
70 import org.springframework.retry.annotation.Backoff;
71 import org.springframework.retry.annotation.Retryable;
72 import org.springframework.stereotype.Component;
73
74
75 @Component
76 @Slf4j
77 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
78
79     private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
80     private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
81     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
82             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
83
84     @Autowired
85     private YangResourceRepository yangResourceRepository;
86
87     @Autowired
88     private SchemaSetRepository schemaSetRepository;
89
90     @Autowired
91     private DataspaceRepository dataspaceRepository;
92
93     @Autowired
94     private AnchorRepository anchorRepository;
95
96     @Autowired
97     private FragmentRepository fragmentRepository;
98
99     @Autowired
100     private CpsAdminPersistenceService cpsAdminPersistenceService;
101
102     @Override
103     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
104         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
105         final var schemaSetEntity =
106             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
107         return schemaSetEntity.getYangResources().stream().collect(
108             Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
109     }
110
111     @Override
112     public Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
113         final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
114         return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
115     }
116
117     @Override
118     public List<ModuleReference> getAllYangResourcesModuleReferences() {
119         final List<YangResourceModuleReference> yangResourceModuleReferenceList =
120                 yangResourceRepository.findAllModuleNameAndRevision();
121         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
122                 .collect(Collectors.toList());
123     }
124
125     @Override
126     @Transactional
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 = 2, backoff = @Backoff(delay = 500))
130     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
131         final Map<String, String> yangResourcesNameToContentMap) {
132
133         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
134         final var yangResourceEntities = synchronizeYangResources(yangResourcesNameToContentMap);
135         final var schemaSetEntity = new SchemaSetEntity();
136         schemaSetEntity.setName(schemaSetName);
137         schemaSetEntity.setDataspace(dataspaceEntity);
138         schemaSetEntity.setYangResources(yangResourceEntities);
139         try {
140             schemaSetRepository.save(schemaSetEntity);
141         } catch (final DataIntegrityViolationException e) {
142             throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
143         }
144     }
145
146     @Override
147     @Transactional
148     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName,
149         final CascadeDeleteAllowed cascadeDeleteAllowed) {
150         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
151         final var schemaSetEntity =
152             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
153
154         final Collection<AnchorEntity> anchorEntities = anchorRepository.findAllBySchemaSet(schemaSetEntity);
155         if (!anchorEntities.isEmpty()) {
156             if (cascadeDeleteAllowed != CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED) {
157                 throw new SchemaSetInUseException(dataspaceName, schemaSetName);
158             }
159             fragmentRepository.deleteByAnchorIn(anchorEntities);
160             anchorRepository.deleteAll(anchorEntities);
161         }
162         schemaSetRepository.delete(schemaSetEntity);
163         yangResourceRepository.deleteOrphans();
164     }
165
166     private Set<YangResourceEntity> synchronizeYangResources(final Map<String, String> yangResourcesNameToContentMap) {
167         final Map<String, YangResourceEntity> checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream()
168             .map(entry -> {
169                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
170                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
171                             entry.getValue());
172                 final var yangResourceEntity = new YangResourceEntity();
173                 yangResourceEntity.setName(entry.getKey());
174                 yangResourceEntity.setContent(entry.getValue());
175                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
176                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
177                 yangResourceEntity.setChecksum(checksum);
178                 return yangResourceEntity;
179             })
180             .collect(Collectors.toMap(
181                 YangResourceEntity::getChecksum,
182                 entity -> entity
183             ));
184
185         final List<YangResourceEntity> existingYangResourceEntities =
186             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
187         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
188
189         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
190         if (!newYangResourceEntities.isEmpty()) {
191             try {
192                 yangResourceRepository.saveAll(newYangResourceEntities);
193             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
194                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
195                 // database constraint violation.
196                 // If it is not, then throw the original exception
197                 final Optional<DuplicatedYangResourceException> convertedException =
198                         convertToDuplicatedYangResourceException(
199                                 dataIntegrityViolationException, newYangResourceEntities);
200                 convertedException.ifPresent(
201                     e ->  log.warn(
202                                 "Cannot persist duplicated yang resource. "
203                                         + "A total of 2 attempts to store the schema set are planned.", e));
204                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
205             }
206         }
207
208         return ImmutableSet.<YangResourceEntity>builder()
209             .addAll(existingYangResourceEntities)
210             .addAll(newYangResourceEntities)
211             .build();
212     }
213
214     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
215         final Map<String, String> metaDataMap = new HashMap<>();
216         final var revisionSourceIdentifier =
217                 createIdentifierFromSourceName(checkNotNull(sourceName));
218
219         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
220             @Override
221             protected MoreObjects.ToStringHelper addToStringAttributes(
222                     final MoreObjects.ToStringHelper toStringHelper) {
223                 return toStringHelper;
224             }
225
226             @Override
227             public InputStream openStream() {
228                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
229             }
230         };
231         try {
232             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
233             metaDataMap.put("moduleName", dependencyInfo.getName());
234             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
235         } catch (final YangSyntaxErrorException | IOException e) {
236             throw new ModelValidationException("Yang resource is invalid.",
237                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
238         }
239         return metaDataMap;
240     }
241
242     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
243         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
244         if (matcher.matches()) {
245             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
246         }
247         return RevisionSourceIdentifier.create(sourceName);
248     }
249
250     /**
251      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
252      * if the cause of the error is a yang checksum database constraint violation.
253      * @param originalException the original db exception.
254      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
255      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
256      *      cause of the error is not a yang checksum database constraint violation.
257      */
258     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
259             final DataIntegrityViolationException originalException,
260             final Collection<YangResourceEntity> yangResourceEntities) {
261
262         // The exception result
263         DuplicatedYangResourceException duplicatedYangResourceException = null;
264
265         final Throwable cause = originalException.getCause();
266         if (cause instanceof ConstraintViolationException) {
267             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
268             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
269                 // Db constraint related to yang resource checksum uniqueness is not respected
270                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
271                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
272                 duplicatedYangResourceException =
273                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
274             }
275         }
276
277         return Optional.ofNullable(duplicatedYangResourceException);
278
279     }
280
281     /**
282      * Get the name of the yang resource having the specified checksum.
283      * @param checksum the checksum. Null is supported.
284      * @param yangResourceEntities the list of yang resources to search among.
285      * @return the name found or null if none.
286      */
287     private String getNameForChecksum(
288             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
289         return
290                 yangResourceEntities.stream()
291                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
292                         .findFirst()
293                         .map(YangResourceEntity::getName)
294                         .orElse(null);
295     }
296
297     /**
298      * Get the checksum that caused the constraint violation exception.
299      * @param exception the exception having the checksum in error.
300      * @return the checksum in error or null if not found.
301      */
302     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
303         String checksum = null;
304         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
305         if (matcher.find() && matcher.groupCount() == 1) {
306             checksum = matcher.group(1);
307         }
308         return checksum;
309     }
310
311     private static ModuleReference toModuleReference(final YangResourceModuleReference yangResourceModuleReference) {
312         return ModuleReference.builder()
313                 .name(yangResourceModuleReference.getModuleName())
314                 .revision(yangResourceModuleReference.getRevision())
315                 .build();
316     }
317 }