Revert "Migrate CPS to Spring-boot 3.0"
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsModulePersistenceServiceImpl.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2020-2023 Nordix Foundation
4  *  Modifications Copyright (C) 2020-2022 Bell Canada.
5  *  Modifications Copyright (C) 2021 Pantheon.tech
6  *  Modifications Copyright (C) 2022 TechMahindra Ltd.
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.spi.impl;
25
26 import static com.google.common.base.Preconditions.checkNotNull;
27
28 import com.google.common.base.MoreObjects;
29 import com.google.common.collect.ImmutableSet;
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.StandardCharsets;
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.Matcher;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
43 import javax.transaction.Transactional;
44 import lombok.RequiredArgsConstructor;
45 import lombok.extern.slf4j.Slf4j;
46 import org.apache.commons.codec.digest.DigestUtils;
47 import org.apache.commons.lang3.StringUtils;
48 import org.hibernate.exception.ConstraintViolationException;
49 import org.onap.cps.spi.CpsAdminPersistenceService;
50 import org.onap.cps.spi.CpsModulePersistenceService;
51 import org.onap.cps.spi.entities.DataspaceEntity;
52 import org.onap.cps.spi.entities.SchemaSetEntity;
53 import org.onap.cps.spi.entities.YangResourceEntity;
54 import org.onap.cps.spi.entities.YangResourceModuleReference;
55 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
56 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
57 import org.onap.cps.spi.exceptions.ModelValidationException;
58 import org.onap.cps.spi.model.ModuleDefinition;
59 import org.onap.cps.spi.model.ModuleReference;
60 import org.onap.cps.spi.model.SchemaSet;
61 import org.onap.cps.spi.repository.DataspaceRepository;
62 import org.onap.cps.spi.repository.ModuleReferenceRepository;
63 import org.onap.cps.spi.repository.SchemaSetRepository;
64 import org.onap.cps.spi.repository.YangResourceRepository;
65 import org.opendaylight.yangtools.yang.common.Revision;
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.api.YangSyntaxErrorException;
69 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
70 import org.springframework.dao.DataIntegrityViolationException;
71 import org.springframework.retry.annotation.Backoff;
72 import org.springframework.retry.annotation.Retryable;
73 import org.springframework.retry.support.RetrySynchronizationManager;
74 import org.springframework.stereotype.Component;
75
76 @Slf4j
77 @Component
78 @RequiredArgsConstructor
79 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
80
81     private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
82     private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
83     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
84             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
85
86     private final YangResourceRepository yangResourceRepository;
87
88     private final SchemaSetRepository schemaSetRepository;
89
90     private final DataspaceRepository dataspaceRepository;
91
92     private final CpsAdminPersistenceService cpsAdminPersistenceService;
93
94     private final ModuleReferenceRepository moduleReferenceRepository;
95
96     @Override
97     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
98         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
99         final SchemaSetEntity schemaSetEntity =
100             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
101         return schemaSetEntity.getYangResources().stream().collect(
102             Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent));
103     }
104
105     @Override
106     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
107         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
108             yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
109         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
110             .collect(Collectors.toList());
111     }
112
113     @Override
114     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
115                                                                        final String anchorName) {
116         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
117                 yangResourceRepository
118                         .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
119         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
120                 .collect(Collectors.toList());
121     }
122
123     @Override
124     public Collection<ModuleDefinition> getYangResourceDefinitions(final String dataspaceName,
125                                                                    final String anchorName) {
126         final Set<YangResourceEntity> yangResourceEntities =
127                 yangResourceRepository
128                         .findAllModuleDefinitionsByDataspaceAndAnchor(dataspaceName, anchorName);
129         return yangResourceEntities.stream().map(CpsModulePersistenceServiceImpl::toModuleDefinition)
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 = 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> moduleReferenceNameToContentMap) {
141         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
142         final Set<YangResourceEntity> yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
143         final SchemaSetEntity 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     public Collection<SchemaSet> getSchemaSetsByDataspaceName(final String dataspaceName) {
156         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
157         final List<SchemaSetEntity> schemaSetEntities = schemaSetRepository.findByDataspace(dataspaceEntity);
158         return schemaSetEntities.stream()
159                 .map(CpsModulePersistenceServiceImpl::toSchemaSet).collect(Collectors.toList());
160     }
161
162     @Override
163     @Transactional
164     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
165     // can occur in case of specific concurrent requests.
166     @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
167         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
168     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
169                                           final Map<String, String> newModuleNameToContentMap,
170                                           final Collection<ModuleReference> allModuleReferences) {
171         storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
172         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
173         final SchemaSetEntity schemaSetEntity =
174                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
175         final List<Integer> allYangResourceIds =
176             yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
177         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), allYangResourceIds);
178     }
179
180     @Override
181     @Transactional
182     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
183         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
184         final SchemaSetEntity schemaSetEntity =
185             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
186         schemaSetRepository.delete(schemaSetEntity);
187     }
188
189     @Override
190     @Transactional
191     public void deleteSchemaSets(final String dataspaceName, final Collection<String> schemaSetNames) {
192         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
193         schemaSetRepository.deleteByDataspaceAndNameIn(dataspaceEntity, schemaSetNames);
194     }
195
196     @Override
197     @Transactional
198     public void deleteUnusedYangResourceModules() {
199         yangResourceRepository.deleteOrphans();
200     }
201
202     @Override
203     public Collection<ModuleReference> identifyNewModuleReferences(
204         final Collection<ModuleReference> moduleReferencesToCheck) {
205         return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
206     }
207
208     private Set<YangResourceEntity> synchronizeYangResources(
209         final Map<String, String> moduleReferenceNameToContentMap) {
210         final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
211             .map(entry -> {
212                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
213                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
214                             entry.getValue());
215                 final YangResourceEntity yangResourceEntity = new YangResourceEntity();
216                 yangResourceEntity.setFileName(entry.getKey());
217                 yangResourceEntity.setContent(entry.getValue());
218                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
219                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
220                 yangResourceEntity.setChecksum(checksum);
221                 return yangResourceEntity;
222             })
223             .collect(Collectors.toMap(
224                 YangResourceEntity::getChecksum,
225                 entity -> entity
226             ));
227
228         final List<YangResourceEntity> existingYangResourceEntities =
229             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
230         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
231
232         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
233         if (!newYangResourceEntities.isEmpty()) {
234             try {
235                 yangResourceRepository.saveAll(newYangResourceEntities);
236             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
237                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
238                 // database constraint violation.
239                 // If it is not, then throw the original exception
240                 final Optional<DuplicatedYangResourceException> convertedException =
241                         convertToDuplicatedYangResourceException(
242                                 dataIntegrityViolationException, newYangResourceEntities);
243                 convertedException.ifPresent(
244                         e -> {
245                             int retryCount = RetrySynchronizationManager.getContext() == null ? 0
246                                     : RetrySynchronizationManager.getContext().getRetryCount();
247                             log.warn("Cannot persist duplicated yang resource. System will attempt this method "
248                                     + "up to 5 times. Current retry count : {}", ++retryCount, e);
249                         });
250                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
251             }
252         }
253
254         return ImmutableSet.<YangResourceEntity>builder()
255             .addAll(existingYangResourceEntities)
256             .addAll(newYangResourceEntities)
257             .build();
258     }
259
260     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
261         final Map<String, String> metaDataMap = new HashMap<>();
262         final RevisionSourceIdentifier revisionSourceIdentifier =
263             createIdentifierFromSourceName(checkNotNull(sourceName));
264
265         final YangTextSchemaSource tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
266             @Override
267             public Optional<String> getSymbolicName() {
268                 return Optional.empty();
269             }
270
271             @Override
272             protected MoreObjects.ToStringHelper addToStringAttributes(
273                     final MoreObjects.ToStringHelper toStringHelper) {
274                 return toStringHelper;
275             }
276
277             @Override
278             public InputStream openStream() {
279                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
280             }
281         };
282         try {
283             final YangModelDependencyInfo yangModelDependencyInfo
284                 = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
285             metaDataMap.put("moduleName", yangModelDependencyInfo.getName());
286             metaDataMap.put("revision", yangModelDependencyInfo.getFormattedRevision());
287         } catch (final YangSyntaxErrorException | IOException e) {
288             throw new ModelValidationException("Yang resource is invalid.",
289                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
290         }
291         return metaDataMap;
292     }
293
294     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
295         final Matcher matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
296         if (matcher.matches()) {
297             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
298         }
299         return RevisionSourceIdentifier.create(sourceName);
300     }
301
302     /**
303      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
304      * if the cause of the error is a yang checksum database constraint violation.
305      *
306      * @param originalException the original db exception.
307      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
308      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
309      *      cause of the error is not a yang checksum database constraint violation.
310      */
311     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
312             final DataIntegrityViolationException originalException,
313             final Collection<YangResourceEntity> yangResourceEntities) {
314
315         // The exception result
316         DuplicatedYangResourceException duplicatedYangResourceException = null;
317
318         final Throwable cause = originalException.getCause();
319         if (cause instanceof ConstraintViolationException) {
320             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
321             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
322                 // Db constraint related to yang resource checksum uniqueness is not respected
323                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
324                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
325                 duplicatedYangResourceException =
326                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
327             }
328         }
329
330         return Optional.ofNullable(duplicatedYangResourceException);
331
332     }
333
334     private String getNameForChecksum(final String checksum,
335                                       final Collection<YangResourceEntity> yangResourceEntities) {
336         final Optional<String> optionalFileName = yangResourceEntities.stream()
337                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
338                         .findFirst()
339                         .map(YangResourceEntity::getFileName);
340         return optionalFileName.orElse("no filename");
341     }
342
343     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
344         final Matcher matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
345         if (matcher.find()) {
346             return matcher.group(1);
347         }
348         return "no checksum found";
349     }
350
351     private static ModuleReference toModuleReference(
352         final YangResourceModuleReference yangResourceModuleReference) {
353         return ModuleReference.builder()
354             .moduleName(yangResourceModuleReference.getModuleName())
355             .revision(yangResourceModuleReference.getRevision())
356             .build();
357     }
358
359     private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
360         return new ModuleDefinition(
361                 yangResourceEntity.getModuleName(),
362                 yangResourceEntity.getRevision(),
363                 yangResourceEntity.getContent());
364     }
365
366     private static SchemaSet toSchemaSet(final SchemaSetEntity schemaSetEntity) {
367         return SchemaSet.builder().name(schemaSetEntity.getName())
368                 .dataspaceName(schemaSetEntity.getDataspace().getName()).build();
369     }
370 }