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