Merge "Fixing SonarQube violations"
[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.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 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             public Optional<String> getSymbolicName() {
266                 return Optional.empty();
267             }
268
269             @Override
270             protected MoreObjects.ToStringHelper addToStringAttributes(
271                     final MoreObjects.ToStringHelper toStringHelper) {
272                 return toStringHelper;
273             }
274
275             @Override
276             public InputStream openStream() {
277                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
278             }
279         };
280         try {
281             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
282             metaDataMap.put("moduleName", dependencyInfo.getName());
283             metaDataMap.put("revision", dependencyInfo.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 var 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     /**
332      * Get the name of the yang resource having the specified checksum.
333      *
334      * @param checksum the checksum. Null is supported.
335      * @param yangResourceEntities the list of yang resources to search among.
336      * @return the name found or null if none.
337      */
338     private String getNameForChecksum(
339             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
340         final Optional<String> optionalFileName = yangResourceEntities.stream()
341                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
342                         .findFirst()
343                         .map(YangResourceEntity::getFileName);
344         if (optionalFileName.isPresent()) {
345             return optionalFileName.get();
346         }
347         return null;
348     }
349
350     /**
351      * Get the checksum that caused the constraint violation exception.
352      *
353      * @param exception the exception having the checksum in error.
354      * @return the checksum in error or null if not found.
355      */
356     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
357         String checksum = null;
358         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
359         if (matcher.find() && matcher.groupCount() == 1) {
360             checksum = matcher.group(1);
361         }
362         return checksum;
363     }
364
365     private static ModuleReference toModuleReference(
366         final YangResourceModuleReference yangResourceModuleReference) {
367         return ModuleReference.builder()
368             .moduleName(yangResourceModuleReference.getModuleName())
369             .revision(yangResourceModuleReference.getRevision())
370             .build();
371     }
372
373     private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
374         return new ModuleDefinition(
375                 yangResourceEntity.getModuleName(),
376                 yangResourceEntity.getRevision(),
377                 yangResourceEntity.getContent());
378     }
379
380     private static SchemaSet toSchemaSet(final SchemaSetEntity schemaSetEntity) {
381         return SchemaSet.builder().name(schemaSetEntity.getName())
382                 .dataspaceName(schemaSetEntity.getDataspace().getName()).build();
383     }
384 }