Refactored Delete SchemaSet functionality
[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-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
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.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Optional;
39 import java.util.Set;
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;
71
72
73 @Component
74 @Slf4j
75 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
76
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);
81
82     @Autowired
83     private YangResourceRepository yangResourceRepository;
84
85     @Autowired
86     private SchemaSetRepository schemaSetRepository;
87
88     @Autowired
89     private DataspaceRepository dataspaceRepository;
90
91     @Autowired
92     private AnchorRepository anchorRepository;
93
94     @Autowired
95     private FragmentRepository fragmentRepository;
96
97     @Autowired
98     private CpsAdminPersistenceService cpsAdminPersistenceService;
99
100     @Override
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));
107     }
108
109     @Override
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());
113     }
114
115     @Override
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());
121     }
122
123     @Override
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());
131     }
132
133     @Override
134     @Transactional
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 = 2, backoff = @Backoff(delay = 500))
138     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
139         final Map<String, String> yangResourcesNameToContentMap) {
140
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);
147         try {
148             schemaSetRepository.save(schemaSetEntity);
149         } catch (final DataIntegrityViolationException e) {
150             throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
151         }
152     }
153
154     @Override
155     @Transactional
156     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
157                                           final Map<String, String> newYangResourcesModuleNameToContentMap,
158                                           final List<ModuleReference> moduleReferences) {
159         storeSchemaSet(dataspaceName, schemaSetName, newYangResourcesModuleNameToContentMap);
160         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
161         final var schemaSetEntity =
162                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
163         final List<Long> listOfYangResourceIds = new ArrayList<>();
164         moduleReferences.forEach(moduleReference ->
165                 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
166                         moduleReference.getModuleName(), moduleReference.getRevision())));
167         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
168     }
169
170     @Override
171     @Transactional
172     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
173         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
174         final var schemaSetEntity =
175             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
176         schemaSetRepository.delete(schemaSetEntity);
177     }
178
179     @Override
180     @Transactional
181     public void deleteUnusedYangResourceModules() {
182         yangResourceRepository.deleteOrphans();
183     }
184
185     private Set<YangResourceEntity> synchronizeYangResources(final Map<String, String> yangResourcesNameToContentMap) {
186         final Map<String, YangResourceEntity> checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream()
187             .map(entry -> {
188                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
189                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
190                             entry.getValue());
191                 final var yangResourceEntity = new YangResourceEntity();
192                 yangResourceEntity.setName(entry.getKey());
193                 yangResourceEntity.setContent(entry.getValue());
194                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
195                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
196                 yangResourceEntity.setChecksum(checksum);
197                 return yangResourceEntity;
198             })
199             .collect(Collectors.toMap(
200                 YangResourceEntity::getChecksum,
201                 entity -> entity
202             ));
203
204         final List<YangResourceEntity> existingYangResourceEntities =
205             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
206         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
207
208         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
209         if (!newYangResourceEntities.isEmpty()) {
210             try {
211                 yangResourceRepository.saveAll(newYangResourceEntities);
212             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
213                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
214                 // database constraint violation.
215                 // If it is not, then throw the original exception
216                 final Optional<DuplicatedYangResourceException> convertedException =
217                         convertToDuplicatedYangResourceException(
218                                 dataIntegrityViolationException, newYangResourceEntities);
219                 convertedException.ifPresent(
220                     e ->  log.warn(
221                                 "Cannot persist duplicated yang resource. "
222                                         + "A total of 2 attempts to store the schema set are planned.", e));
223                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
224             }
225         }
226
227         return ImmutableSet.<YangResourceEntity>builder()
228             .addAll(existingYangResourceEntities)
229             .addAll(newYangResourceEntities)
230             .build();
231     }
232
233     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
234         final Map<String, String> metaDataMap = new HashMap<>();
235         final var revisionSourceIdentifier =
236                 createIdentifierFromSourceName(checkNotNull(sourceName));
237
238         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
239             @Override
240             protected MoreObjects.ToStringHelper addToStringAttributes(
241                     final MoreObjects.ToStringHelper toStringHelper) {
242                 return toStringHelper;
243             }
244
245             @Override
246             public InputStream openStream() {
247                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
248             }
249         };
250         try {
251             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
252             metaDataMap.put("moduleName", dependencyInfo.getName());
253             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
254         } catch (final YangSyntaxErrorException | IOException e) {
255             throw new ModelValidationException("Yang resource is invalid.",
256                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
257         }
258         return metaDataMap;
259     }
260
261     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
262         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
263         if (matcher.matches()) {
264             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
265         }
266         return RevisionSourceIdentifier.create(sourceName);
267     }
268
269     /**
270      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
271      * if the cause of the error is a yang checksum database constraint violation.
272      *
273      * @param originalException the original db exception.
274      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
275      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
276      *      cause of the error is not a yang checksum database constraint violation.
277      */
278     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
279             final DataIntegrityViolationException originalException,
280             final Collection<YangResourceEntity> yangResourceEntities) {
281
282         // The exception result
283         DuplicatedYangResourceException duplicatedYangResourceException = null;
284
285         final Throwable cause = originalException.getCause();
286         if (cause instanceof ConstraintViolationException) {
287             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
288             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
289                 // Db constraint related to yang resource checksum uniqueness is not respected
290                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
291                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
292                 duplicatedYangResourceException =
293                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
294             }
295         }
296
297         return Optional.ofNullable(duplicatedYangResourceException);
298
299     }
300
301     /**
302      * Get the name of the yang resource having the specified checksum.
303      *
304      * @param checksum the checksum. Null is supported.
305      * @param yangResourceEntities the list of yang resources to search among.
306      * @return the name found or null if none.
307      */
308     private String getNameForChecksum(
309             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
310         return
311                 yangResourceEntities.stream()
312                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
313                         .findFirst()
314                         .map(YangResourceEntity::getName)
315                         .orElse(null);
316     }
317
318     /**
319      * Get the checksum that caused the constraint violation exception.
320      *
321      * @param exception the exception having the checksum in error.
322      * @return the checksum in error or null if not found.
323      */
324     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
325         String checksum = null;
326         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
327         if (matcher.find() && matcher.groupCount() == 1) {
328             checksum = matcher.group(1);
329         }
330         return checksum;
331     }
332
333     private static ModuleReference toModuleReference(
334         final YangResourceModuleReference yangResourceModuleReference) {
335         return ModuleReference.builder()
336             .moduleName(yangResourceModuleReference.getModuleName())
337             .revision(yangResourceModuleReference.getRevision())
338             .build();
339     }
340 }