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