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