Add method to get YANG module sources for CM handle
[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.ArrayList;
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.AllArgsConstructor;
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.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 @AllArgsConstructor
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 YangResourceRepository yangResourceRepository;
84
85     private SchemaSetRepository schemaSetRepository;
86
87     private DataspaceRepository dataspaceRepository;
88
89     private CpsAdminPersistenceService cpsAdminPersistenceService;
90
91     private 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::getName, 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 var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
168         final var schemaSetEntity =
169                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
170         final List<Long> listOfYangResourceIds = new ArrayList<>();
171         moduleReferences.forEach(moduleReference ->
172                 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
173                         moduleReference.getModuleName(), moduleReference.getRevision())));
174         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
175     }
176
177     @Override
178     @Transactional
179     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
180         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
181         final var schemaSetEntity =
182             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
183         schemaSetRepository.delete(schemaSetEntity);
184     }
185
186     @Override
187     @Transactional
188     public void deleteUnusedYangResourceModules() {
189         yangResourceRepository.deleteOrphans();
190     }
191
192     @Override
193     public Collection<ModuleReference> identifyNewModuleReferences(
194         final Collection<ModuleReference> moduleReferencesToCheck) {
195         return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
196     }
197
198     private Set<YangResourceEntity> synchronizeYangResources(
199         final Map<String, String> moduleReferenceNameToContentMap) {
200         final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
201             .map(entry -> {
202                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
203                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
204                             entry.getValue());
205                 final var yangResourceEntity = new YangResourceEntity();
206                 yangResourceEntity.setName(entry.getKey());
207                 yangResourceEntity.setContent(entry.getValue());
208                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
209                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
210                 yangResourceEntity.setChecksum(checksum);
211                 return yangResourceEntity;
212             })
213             .collect(Collectors.toMap(
214                 YangResourceEntity::getChecksum,
215                 entity -> entity
216             ));
217
218         final List<YangResourceEntity> existingYangResourceEntities =
219             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
220         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
221
222         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
223         if (!newYangResourceEntities.isEmpty()) {
224             try {
225                 yangResourceRepository.saveAll(newYangResourceEntities);
226             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
227                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
228                 // database constraint violation.
229                 // If it is not, then throw the original exception
230                 final Optional<DuplicatedYangResourceException> convertedException =
231                         convertToDuplicatedYangResourceException(
232                                 dataIntegrityViolationException, newYangResourceEntities);
233                 convertedException.ifPresent(
234                         e -> {
235                             int retryCount = RetrySynchronizationManager.getContext() == null ? 0
236                                     : RetrySynchronizationManager.getContext().getRetryCount();
237                             log.warn("Cannot persist duplicated yang resource. System will attempt this method "
238                                     + "up to 5 times. Current retry count : {}", ++retryCount, e);
239                         });
240                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
241             }
242         }
243
244         return ImmutableSet.<YangResourceEntity>builder()
245             .addAll(existingYangResourceEntities)
246             .addAll(newYangResourceEntities)
247             .build();
248     }
249
250     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
251         final Map<String, String> metaDataMap = new HashMap<>();
252         final var revisionSourceIdentifier =
253                 createIdentifierFromSourceName(checkNotNull(sourceName));
254
255         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
256             @Override
257             protected MoreObjects.ToStringHelper addToStringAttributes(
258                     final MoreObjects.ToStringHelper toStringHelper) {
259                 return toStringHelper;
260             }
261
262             @Override
263             public InputStream openStream() {
264                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
265             }
266         };
267         try {
268             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
269             metaDataMap.put("moduleName", dependencyInfo.getName());
270             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
271         } catch (final YangSyntaxErrorException | IOException e) {
272             throw new ModelValidationException("Yang resource is invalid.",
273                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
274         }
275         return metaDataMap;
276     }
277
278     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
279         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
280         if (matcher.matches()) {
281             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
282         }
283         return RevisionSourceIdentifier.create(sourceName);
284     }
285
286     /**
287      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
288      * if the cause of the error is a yang checksum database constraint violation.
289      *
290      * @param originalException the original db exception.
291      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
292      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
293      *      cause of the error is not a yang checksum database constraint violation.
294      */
295     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
296             final DataIntegrityViolationException originalException,
297             final Collection<YangResourceEntity> yangResourceEntities) {
298
299         // The exception result
300         DuplicatedYangResourceException duplicatedYangResourceException = null;
301
302         final Throwable cause = originalException.getCause();
303         if (cause instanceof ConstraintViolationException) {
304             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
305             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
306                 // Db constraint related to yang resource checksum uniqueness is not respected
307                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
308                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
309                 duplicatedYangResourceException =
310                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
311             }
312         }
313
314         return Optional.ofNullable(duplicatedYangResourceException);
315
316     }
317
318     /**
319      * Get the name of the yang resource having the specified checksum.
320      *
321      * @param checksum the checksum. Null is supported.
322      * @param yangResourceEntities the list of yang resources to search among.
323      * @return the name found or null if none.
324      */
325     private String getNameForChecksum(
326             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
327         return
328                 yangResourceEntities.stream()
329                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
330                         .findFirst()
331                         .map(YangResourceEntity::getName)
332                         .orElse(null);
333     }
334
335     /**
336      * Get the checksum that caused the constraint violation exception.
337      *
338      * @param exception the exception having the checksum in error.
339      * @return the checksum in error or null if not found.
340      */
341     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
342         String checksum = null;
343         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
344         if (matcher.find() && matcher.groupCount() == 1) {
345             checksum = matcher.group(1);
346         }
347         return checksum;
348     }
349
350     private static ModuleReference toModuleReference(
351         final YangResourceModuleReference yangResourceModuleReference) {
352         return ModuleReference.builder()
353             .moduleName(yangResourceModuleReference.getModuleName())
354             .revision(yangResourceModuleReference.getRevision())
355             .build();
356     }
357
358     private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
359         return new ModuleDefinition(
360                 yangResourceEntity.getModuleName(),
361                 yangResourceEntity.getRevision(),
362                 yangResourceEntity.getContent());
363     }
364 }