Upgrade Open daylight yang tool to version 8.0.6
[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.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
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> allModuleReferences) {
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> allYangResourceIds =
171             yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
172         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), allYangResourceIds);
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             public Optional<String> getSymbolicName() {
256                 return Optional.empty();
257             }
258
259             @Override
260             protected MoreObjects.ToStringHelper addToStringAttributes(
261                     final MoreObjects.ToStringHelper toStringHelper) {
262                 return toStringHelper;
263             }
264
265             @Override
266             public InputStream openStream() {
267                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
268             }
269         };
270         try {
271             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
272             metaDataMap.put("moduleName", dependencyInfo.getName());
273             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
274         } catch (final YangSyntaxErrorException | IOException e) {
275             throw new ModelValidationException("Yang resource is invalid.",
276                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
277         }
278         return metaDataMap;
279     }
280
281     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
282         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
283         if (matcher.matches()) {
284             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
285         }
286         return RevisionSourceIdentifier.create(sourceName);
287     }
288
289     /**
290      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
291      * if the cause of the error is a yang checksum database constraint violation.
292      *
293      * @param originalException the original db exception.
294      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
295      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
296      *      cause of the error is not a yang checksum database constraint violation.
297      */
298     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
299             final DataIntegrityViolationException originalException,
300             final Collection<YangResourceEntity> yangResourceEntities) {
301
302         // The exception result
303         DuplicatedYangResourceException duplicatedYangResourceException = null;
304
305         final Throwable cause = originalException.getCause();
306         if (cause instanceof ConstraintViolationException) {
307             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
308             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
309                 // Db constraint related to yang resource checksum uniqueness is not respected
310                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
311                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
312                 duplicatedYangResourceException =
313                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
314             }
315         }
316
317         return Optional.ofNullable(duplicatedYangResourceException);
318
319     }
320
321     /**
322      * Get the name of the yang resource having the specified checksum.
323      *
324      * @param checksum the checksum. Null is supported.
325      * @param yangResourceEntities the list of yang resources to search among.
326      * @return the name found or null if none.
327      */
328     private String getNameForChecksum(
329             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
330         return
331                 yangResourceEntities.stream()
332                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
333                         .findFirst()
334                         .map(YangResourceEntity::getFileName)
335                         .orElse(null);
336     }
337
338     /**
339      * Get the checksum that caused the constraint violation exception.
340      *
341      * @param exception the exception having the checksum in error.
342      * @return the checksum in error or null if not found.
343      */
344     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
345         String checksum = null;
346         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
347         if (matcher.find() && matcher.groupCount() == 1) {
348             checksum = matcher.group(1);
349         }
350         return checksum;
351     }
352
353     private static ModuleReference toModuleReference(
354         final YangResourceModuleReference yangResourceModuleReference) {
355         return ModuleReference.builder()
356             .moduleName(yangResourceModuleReference.getModuleName())
357             .revision(yangResourceModuleReference.getRevision())
358             .build();
359     }
360
361     private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
362         return new ModuleDefinition(
363                 yangResourceEntity.getModuleName(),
364                 yangResourceEntity.getRevision(),
365                 yangResourceEntity.getContent());
366     }
367 }