b0f9a2da5245d3e35e0ea5f08f8f4d724e97496e
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsModulePersistenceServiceImpl.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2020-2024 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 jakarta.transaction.Transactional;
31 import java.io.ByteArrayInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.nio.charset.StandardCharsets;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Optional;
42 import java.util.Set;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import java.util.stream.Collectors;
46 import lombok.RequiredArgsConstructor;
47 import lombok.extern.slf4j.Slf4j;
48 import org.apache.commons.codec.digest.DigestUtils;
49 import org.apache.commons.lang3.StringUtils;
50 import org.hibernate.exception.ConstraintViolationException;
51 import org.onap.cps.spi.CpsModulePersistenceService;
52 import org.onap.cps.spi.entities.DataspaceEntity;
53 import org.onap.cps.spi.entities.SchemaSetEntity;
54 import org.onap.cps.spi.entities.YangResourceEntity;
55 import org.onap.cps.spi.entities.YangResourceModuleReference;
56 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
57 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
58 import org.onap.cps.spi.exceptions.ModelValidationException;
59 import org.onap.cps.spi.model.ModuleDefinition;
60 import org.onap.cps.spi.model.ModuleReference;
61 import org.onap.cps.spi.model.SchemaSet;
62 import org.onap.cps.spi.repository.DataspaceRepository;
63 import org.onap.cps.spi.repository.ModuleReferenceRepository;
64 import org.onap.cps.spi.repository.SchemaSetRepository;
65 import org.onap.cps.spi.repository.YangResourceRepository;
66 import org.opendaylight.yangtools.yang.common.Revision;
67 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
68 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
69 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
70 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
71 import org.springframework.dao.DataIntegrityViolationException;
72 import org.springframework.retry.annotation.Backoff;
73 import org.springframework.retry.annotation.Retryable;
74 import org.springframework.retry.support.RetrySynchronizationManager;
75 import org.springframework.stereotype.Component;
76
77 @Slf4j
78 @Component
79 @RequiredArgsConstructor
80 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
81
82     private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
83     private static final String NO_MODULE_NAME_FILTER = null;
84     private static final String NO_MODULE_REVISION = null;
85     private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
86     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
87             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
88
89     private final YangResourceRepository yangResourceRepository;
90
91     private final SchemaSetRepository schemaSetRepository;
92
93     private final DataspaceRepository dataspaceRepository;
94
95     private final ModuleReferenceRepository moduleReferenceRepository;
96
97     @Override
98     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
99         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
100         final SchemaSetEntity schemaSetEntity =
101             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
102         return schemaSetEntity.getYangResources().stream().collect(
103             Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent));
104     }
105
106     @Override
107     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
108         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
109             yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
110         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
111             .collect(Collectors.toList());
112     }
113
114     @Override
115     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
116                                                                        final String anchorName) {
117         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
118                 yangResourceRepository
119                         .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
120         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
121                 .collect(Collectors.toList());
122     }
123
124     @Override
125     public Collection<ModuleDefinition> getYangResourceDefinitions(final String dataspaceName,
126                                                                    final String anchorName) {
127         final Set<YangResourceEntity> yangResourceEntities =
128                 yangResourceRepository.findAllModuleDefinitionsByDataspaceAndAnchorAndModule(dataspaceName, anchorName,
129                     NO_MODULE_NAME_FILTER, NO_MODULE_REVISION);
130         return convertYangResourceEntityToModuleDefinition(yangResourceEntities);
131     }
132
133     @Override
134     public Collection<ModuleDefinition> getYangResourceDefinitionsByAnchorAndModule(final String dataspaceName,
135                                                                                     final String anchorName,
136                                                                                     final String moduleName,
137                                                                                     final String moduleRevision) {
138         final Set<YangResourceEntity> yangResourceEntities =
139             yangResourceRepository.findAllModuleDefinitionsByDataspaceAndAnchorAndModule(dataspaceName, anchorName,
140                 moduleName, moduleRevision);
141         return convertYangResourceEntityToModuleDefinition(yangResourceEntities);
142     }
143
144     private List<ModuleDefinition> convertYangResourceEntityToModuleDefinition(final Set<YangResourceEntity>
145                                                                                    yangResourceEntities) {
146         final List<ModuleDefinition> resultModuleDefinitions = new ArrayList<>(yangResourceEntities.size());
147         for (final YangResourceEntity yangResourceEntity: yangResourceEntities) {
148             resultModuleDefinitions.add(toModuleDefinition(yangResourceEntity));
149         }
150         return resultModuleDefinitions;
151     }
152
153     @Override
154     @Transactional
155     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
156     // can occur in case of specific concurrent requests.
157     @Retryable(retryFor = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
158         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
159     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
160         final Map<String, String> moduleReferenceNameToContentMap) {
161         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
162         final Set<YangResourceEntity> yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
163         final SchemaSetEntity schemaSetEntity = new SchemaSetEntity();
164         schemaSetEntity.setName(schemaSetName);
165         schemaSetEntity.setDataspace(dataspaceEntity);
166         schemaSetEntity.setYangResources(yangResourceEntities);
167         try {
168             schemaSetRepository.save(schemaSetEntity);
169         } catch (final DataIntegrityViolationException e) {
170             throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
171         }
172     }
173
174     @Override
175     public Collection<SchemaSet> getSchemaSetsByDataspaceName(final String dataspaceName) {
176         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
177         final List<SchemaSetEntity> schemaSetEntities = schemaSetRepository.findByDataspace(dataspaceEntity);
178         return schemaSetEntities.stream()
179                 .map(CpsModulePersistenceServiceImpl::toSchemaSet).collect(Collectors.toList());
180     }
181
182     @Override
183     @Transactional
184     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
185     // can occur in case of specific concurrent requests.
186     @Retryable(retryFor = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
187         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
188     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
189                                           final Map<String, String> newModuleNameToContentMap,
190                                           final Collection<ModuleReference> allModuleReferences) {
191         storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
192         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
193         final SchemaSetEntity schemaSetEntity =
194                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
195         final List<Integer> allYangResourceIds =
196             yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
197         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), allYangResourceIds);
198     }
199
200     @Override
201     @Transactional
202     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
203         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
204         final SchemaSetEntity schemaSetEntity =
205             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
206         schemaSetRepository.delete(schemaSetEntity);
207     }
208
209     @Override
210     @Transactional
211     public void deleteSchemaSets(final String dataspaceName, final Collection<String> schemaSetNames) {
212         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
213         schemaSetRepository.deleteByDataspaceAndNameIn(dataspaceEntity, schemaSetNames);
214     }
215
216
217     @Override
218     @Transactional
219     public void updateSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
220                                            final Map<String, String> newModuleNameToContentMap,
221                                            final Collection<ModuleReference> allModuleReferences) {
222         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
223         final SchemaSetEntity schemaSetEntity =
224             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
225         storeAndLinkNewModules(newModuleNameToContentMap, schemaSetEntity);
226         updateAllModuleReferences(allModuleReferences, schemaSetEntity.getId());
227     }
228
229
230
231     @Override
232     @Transactional
233     public void deleteUnusedYangResourceModules() {
234         yangResourceRepository.deleteOrphans();
235     }
236
237     @Override
238     public Collection<ModuleReference> identifyNewModuleReferences(
239         final Collection<ModuleReference> moduleReferencesToCheck) {
240         return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
241     }
242
243     private Set<YangResourceEntity> synchronizeYangResources(
244         final Map<String, String> moduleReferenceNameToContentMap) {
245         final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
246             .map(entry -> {
247                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
248                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
249                             entry.getValue());
250                 final YangResourceEntity yangResourceEntity = new YangResourceEntity();
251                 yangResourceEntity.setFileName(entry.getKey());
252                 yangResourceEntity.setContent(entry.getValue());
253                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
254                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
255                 yangResourceEntity.setChecksum(checksum);
256                 return yangResourceEntity;
257             })
258             .collect(Collectors.toMap(
259                 YangResourceEntity::getChecksum,
260                 entity -> entity
261             ));
262
263         final List<YangResourceEntity> existingYangResourceEntities =
264             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
265         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
266
267         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
268         if (!newYangResourceEntities.isEmpty()) {
269             try {
270                 yangResourceRepository.saveAll(newYangResourceEntities);
271             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
272                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
273                 // database constraint violation.
274                 // If it is not, then throw the original exception
275                 final Optional<DuplicatedYangResourceException> convertedException =
276                         convertToDuplicatedYangResourceException(
277                                 dataIntegrityViolationException, newYangResourceEntities);
278                 convertedException.ifPresent(
279                         e -> {
280                             int retryCount = RetrySynchronizationManager.getContext() == null ? 0
281                                                      : RetrySynchronizationManager.getContext().getRetryCount();
282                             log.warn("Cannot persist duplicated yang resource. System will attempt this method "
283                                     + "up to 5 times. Current retry count : {}", ++retryCount, e);
284                         });
285                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
286             }
287         }
288
289         return ImmutableSet.<YangResourceEntity>builder()
290             .addAll(existingYangResourceEntities)
291             .addAll(newYangResourceEntities)
292             .build();
293     }
294
295     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
296         final Map<String, String> metaDataMap = new HashMap<>();
297         final RevisionSourceIdentifier revisionSourceIdentifier =
298             createIdentifierFromSourceName(checkNotNull(sourceName));
299
300         final YangTextSchemaSource tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
301             @Override
302             public Optional<String> getSymbolicName() {
303                 return Optional.empty();
304             }
305
306             @Override
307             protected MoreObjects.ToStringHelper addToStringAttributes(
308                     final MoreObjects.ToStringHelper toStringHelper) {
309                 return toStringHelper;
310             }
311
312             @Override
313             public InputStream openStream() {
314                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
315             }
316         };
317         try {
318             final YangModelDependencyInfo yangModelDependencyInfo
319                 = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
320             metaDataMap.put("moduleName", yangModelDependencyInfo.getName());
321             metaDataMap.put("revision", yangModelDependencyInfo.getFormattedRevision());
322         } catch (final YangSyntaxErrorException | IOException e) {
323             throw new ModelValidationException("Yang resource is invalid.",
324                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
325         }
326         return metaDataMap;
327     }
328
329     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
330         final Matcher matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
331         if (matcher.matches()) {
332             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
333         }
334         return RevisionSourceIdentifier.create(sourceName);
335     }
336
337     /**
338      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
339      * if the cause of the error is a yang checksum database constraint violation.
340      *
341      * @param originalException the original db exception.
342      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
343      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
344      *      cause of the error is not a yang checksum database constraint violation.
345      */
346     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
347             final DataIntegrityViolationException originalException,
348             final Collection<YangResourceEntity> yangResourceEntities) {
349
350         // The exception result
351         DuplicatedYangResourceException duplicatedYangResourceException = null;
352
353         final Throwable cause = originalException.getCause();
354         if (cause instanceof ConstraintViolationException) {
355             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
356             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
357                 // Db constraint related to yang resource checksum uniqueness is not respected
358                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
359                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
360                 duplicatedYangResourceException =
361                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
362             }
363         }
364
365         return Optional.ofNullable(duplicatedYangResourceException);
366
367     }
368
369     private String getNameForChecksum(final String checksum,
370                                       final Collection<YangResourceEntity> yangResourceEntities) {
371         final Optional<String> optionalFileName = yangResourceEntities.stream()
372                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
373                         .findFirst()
374                         .map(YangResourceEntity::getFileName);
375         return optionalFileName.orElse("no filename");
376     }
377
378     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
379         final Matcher matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
380         if (matcher.find()) {
381             return matcher.group(1);
382         }
383         return "no checksum found";
384     }
385
386     private static ModuleReference toModuleReference(
387         final YangResourceModuleReference yangResourceModuleReference) {
388         return ModuleReference.builder()
389             .moduleName(yangResourceModuleReference.getModuleName())
390             .revision(yangResourceModuleReference.getRevision())
391             .build();
392     }
393
394     private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
395         return new ModuleDefinition(
396                 yangResourceEntity.getModuleName(),
397                 yangResourceEntity.getRevision(),
398                 yangResourceEntity.getContent());
399     }
400
401     private static SchemaSet toSchemaSet(final SchemaSetEntity schemaSetEntity) {
402         return SchemaSet.builder().name(schemaSetEntity.getName())
403                 .dataspaceName(schemaSetEntity.getDataspace().getName()).build();
404     }
405
406     private void storeAndLinkNewModules(final Map<String, String> newModuleNameToContentMap,
407                                         final SchemaSetEntity schemaSetEntity) {
408         final Set<YangResourceEntity> yangResourceEntities
409             = new HashSet<>(synchronizeYangResources(newModuleNameToContentMap));
410         schemaSetEntity.setYangResources(yangResourceEntities);
411         schemaSetRepository.save(schemaSetEntity);
412     }
413
414     private void updateAllModuleReferences(final Collection<ModuleReference> allModuleReferences,
415                                            final Integer schemaSetEntityId) {
416         yangResourceRepository.deleteSchemaSetYangResourceForSchemaSetId(schemaSetEntityId);
417         final List<Integer> allYangResourceIds =
418             yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
419         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntityId, allYangResourceIds);
420     }
421
422 }