Performance Improvement: Retreive Yang Resources
[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  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  SPDX-License-Identifier: Apache-2.0
20  *  ============LICENSE_END=========================================================
21  */
22
23 package org.onap.cps.spi.impl;
24
25 import static com.google.common.base.Preconditions.checkNotNull;
26
27 import com.google.common.base.MoreObjects;
28 import com.google.common.collect.ImmutableSet;
29 import java.io.ByteArrayInputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.nio.charset.StandardCharsets;
33 import java.util.Collection;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.regex.Pattern;
40 import java.util.stream.Collectors;
41 import javax.transaction.Transactional;
42 import lombok.RequiredArgsConstructor;
43 import lombok.extern.slf4j.Slf4j;
44 import org.apache.commons.codec.digest.DigestUtils;
45 import org.apache.commons.lang3.StringUtils;
46 import org.hibernate.exception.ConstraintViolationException;
47 import org.onap.cps.spi.CpsAdminPersistenceService;
48 import org.onap.cps.spi.CpsModulePersistenceService;
49 import org.onap.cps.spi.entities.DataspaceEntity;
50 import org.onap.cps.spi.entities.SchemaSetEntity;
51 import org.onap.cps.spi.entities.YangResourceEntity;
52 import org.onap.cps.spi.entities.YangResourceModuleReference;
53 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
54 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
55 import org.onap.cps.spi.exceptions.ModelValidationException;
56 import org.onap.cps.spi.model.ModuleDefinition;
57 import org.onap.cps.spi.model.ModuleReference;
58 import org.onap.cps.spi.repository.DataspaceRepository;
59 import org.onap.cps.spi.repository.ModuleReferenceRepository;
60 import org.onap.cps.spi.repository.SchemaSetRepository;
61 import org.onap.cps.spi.repository.YangResourceRepository;
62 import org.opendaylight.yangtools.yang.common.Revision;
63 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
64 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
66 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
67 import org.springframework.dao.DataIntegrityViolationException;
68 import org.springframework.retry.annotation.Backoff;
69 import org.springframework.retry.annotation.Retryable;
70 import org.springframework.retry.support.RetrySynchronizationManager;
71 import org.springframework.stereotype.Component;
72
73 @Slf4j
74 @Component
75 @RequiredArgsConstructor
76 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
77
78     private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
79     private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
80     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
81             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
82
83     private final YangResourceRepository yangResourceRepository;
84
85     private final SchemaSetRepository schemaSetRepository;
86
87     private final DataspaceRepository dataspaceRepository;
88
89     private final CpsAdminPersistenceService cpsAdminPersistenceService;
90
91     private final ModuleReferenceRepository moduleReferenceRepository;
92
93     @Override
94     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
95         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
96         final var 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 Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
104         final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
105         return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
106     }
107
108     @Override
109     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
110         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
111             yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
112         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
113             .collect(Collectors.toList());
114     }
115
116     @Override
117     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
118                                                                        final String anchorName) {
119         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
120                 yangResourceRepository
121                         .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
122         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
123                 .collect(Collectors.toList());
124     }
125
126     @Override
127     public Collection<ModuleDefinition> getYangResourceDefinitions(final String dataspaceName,
128                                                                    final String anchorName) {
129         final Set<YangResourceEntity> yangResourceEntities =
130                 yangResourceRepository
131                         .findAllModuleDefinitionsByDataspaceAndAnchor(dataspaceName, anchorName);
132         return yangResourceEntities.stream().map(CpsModulePersistenceServiceImpl::toModuleDefinition)
133                 .collect(Collectors.toList());
134     }
135
136     @Override
137     @Transactional
138     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
139     // can occur in case of specific concurrent requests.
140     @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
141         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
142     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
143         final Map<String, String> moduleReferenceNameToContentMap) {
144         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
145         final var yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
146         final var schemaSetEntity = new SchemaSetEntity();
147         schemaSetEntity.setName(schemaSetName);
148         schemaSetEntity.setDataspace(dataspaceEntity);
149         schemaSetEntity.setYangResources(yangResourceEntities);
150         try {
151             schemaSetRepository.save(schemaSetEntity);
152         } catch (final DataIntegrityViolationException e) {
153             throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
154         }
155     }
156
157     @Override
158     @Transactional
159     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
160     // can occur in case of specific concurrent requests.
161     @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
162         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
163     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
164                                           final Map<String, String> newModuleNameToContentMap,
165                                           final Collection<ModuleReference> moduleReferences) {
166         storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
167         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
168         final SchemaSetEntity schemaSetEntity =
169                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
170         final List<Long> listOfYangResourceIds =
171             yangResourceRepository.getResourceIdsByModuleReferences(moduleReferences);
172         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
173     }
174
175     @Override
176     @Transactional
177     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
178         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
179         final var schemaSetEntity =
180             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
181         schemaSetRepository.delete(schemaSetEntity);
182     }
183
184     @Override
185     @Transactional
186     public void deleteUnusedYangResourceModules() {
187         yangResourceRepository.deleteOrphans();
188     }
189
190     @Override
191     public Collection<ModuleReference> identifyNewModuleReferences(
192         final Collection<ModuleReference> moduleReferencesToCheck) {
193         return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
194     }
195
196     private Set<YangResourceEntity> synchronizeYangResources(
197         final Map<String, String> moduleReferenceNameToContentMap) {
198         final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
199             .map(entry -> {
200                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
201                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
202                             entry.getValue());
203                 final var yangResourceEntity = new YangResourceEntity();
204                 yangResourceEntity.setFileName(entry.getKey());
205                 yangResourceEntity.setContent(entry.getValue());
206                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
207                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
208                 yangResourceEntity.setChecksum(checksum);
209                 return yangResourceEntity;
210             })
211             .collect(Collectors.toMap(
212                 YangResourceEntity::getChecksum,
213                 entity -> entity
214             ));
215
216         final List<YangResourceEntity> existingYangResourceEntities =
217             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
218         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
219
220         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
221         if (!newYangResourceEntities.isEmpty()) {
222             try {
223                 yangResourceRepository.saveAll(newYangResourceEntities);
224             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
225                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
226                 // database constraint violation.
227                 // If it is not, then throw the original exception
228                 final Optional<DuplicatedYangResourceException> convertedException =
229                         convertToDuplicatedYangResourceException(
230                                 dataIntegrityViolationException, newYangResourceEntities);
231                 convertedException.ifPresent(
232                         e -> {
233                             int retryCount = RetrySynchronizationManager.getContext() == null ? 0
234                                     : RetrySynchronizationManager.getContext().getRetryCount();
235                             log.warn("Cannot persist duplicated yang resource. System will attempt this method "
236                                     + "up to 5 times. Current retry count : {}", ++retryCount, e);
237                         });
238                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
239             }
240         }
241
242         return ImmutableSet.<YangResourceEntity>builder()
243             .addAll(existingYangResourceEntities)
244             .addAll(newYangResourceEntities)
245             .build();
246     }
247
248     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
249         final Map<String, String> metaDataMap = new HashMap<>();
250         final var revisionSourceIdentifier =
251                 createIdentifierFromSourceName(checkNotNull(sourceName));
252
253         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
254             @Override
255             protected MoreObjects.ToStringHelper addToStringAttributes(
256                     final MoreObjects.ToStringHelper toStringHelper) {
257                 return toStringHelper;
258             }
259
260             @Override
261             public InputStream openStream() {
262                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
263             }
264         };
265         try {
266             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
267             metaDataMap.put("moduleName", dependencyInfo.getName());
268             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
269         } catch (final YangSyntaxErrorException | IOException e) {
270             throw new ModelValidationException("Yang resource is invalid.",
271                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
272         }
273         return metaDataMap;
274     }
275
276     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
277         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
278         if (matcher.matches()) {
279             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
280         }
281         return RevisionSourceIdentifier.create(sourceName);
282     }
283
284     /**
285      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
286      * if the cause of the error is a yang checksum database constraint violation.
287      *
288      * @param originalException the original db exception.
289      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
290      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
291      *      cause of the error is not a yang checksum database constraint violation.
292      */
293     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
294             final DataIntegrityViolationException originalException,
295             final Collection<YangResourceEntity> yangResourceEntities) {
296
297         // The exception result
298         DuplicatedYangResourceException duplicatedYangResourceException = null;
299
300         final Throwable cause = originalException.getCause();
301         if (cause instanceof ConstraintViolationException) {
302             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
303             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
304                 // Db constraint related to yang resource checksum uniqueness is not respected
305                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
306                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
307                 duplicatedYangResourceException =
308                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
309             }
310         }
311
312         return Optional.ofNullable(duplicatedYangResourceException);
313
314     }
315
316     /**
317      * Get the name of the yang resource having the specified checksum.
318      *
319      * @param checksum the checksum. Null is supported.
320      * @param yangResourceEntities the list of yang resources to search among.
321      * @return the name found or null if none.
322      */
323     private String getNameForChecksum(
324             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
325         return
326                 yangResourceEntities.stream()
327                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
328                         .findFirst()
329                         .map(YangResourceEntity::getFileName)
330                         .orElse(null);
331     }
332
333     /**
334      * Get the checksum that caused the constraint violation exception.
335      *
336      * @param exception the exception having the checksum in error.
337      * @return the checksum in error or null if not found.
338      */
339     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
340         String checksum = null;
341         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
342         if (matcher.find() && matcher.groupCount() == 1) {
343             checksum = matcher.group(1);
344         }
345         return checksum;
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 }