ec720b8a96b80f45ce5dbcf9e2cc8713fd3c3a11
[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.ModuleReference;
57 import org.onap.cps.spi.repository.DataspaceRepository;
58 import org.onap.cps.spi.repository.ModuleReferenceRepository;
59 import org.onap.cps.spi.repository.SchemaSetRepository;
60 import org.onap.cps.spi.repository.YangResourceRepository;
61 import org.opendaylight.yangtools.yang.common.Revision;
62 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
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.rfc7950.repo.YangModelDependencyInfo;
66 import org.springframework.dao.DataIntegrityViolationException;
67 import org.springframework.retry.annotation.Backoff;
68 import org.springframework.retry.annotation.Retryable;
69 import org.springframework.stereotype.Component;
70
71 @Slf4j
72 @Component
73 @AllArgsConstructor
74 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
75
76     private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
77     private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
78     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
79             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
80
81     private YangResourceRepository yangResourceRepository;
82
83     private SchemaSetRepository schemaSetRepository;
84
85     private DataspaceRepository dataspaceRepository;
86
87     private CpsAdminPersistenceService cpsAdminPersistenceService;
88
89     private ModuleReferenceRepository moduleReferenceRepository;
90
91     @Override
92     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
93         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
94         final var schemaSetEntity =
95             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
96         return schemaSetEntity.getYangResources().stream().collect(
97             Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
98     }
99
100     @Override
101     public Map<String, String> getYangSchemaSetResources(final String dataspaceName, final String anchorName) {
102         final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName);
103         return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName());
104     }
105
106     @Override
107     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
108         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
109             yangResourceRepository.findAllModuleReferences(dataspaceName);
110         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
111             .collect(Collectors.toList());
112     }
113
114     @Override
115     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
116         final String anchorName) {
117         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
118             yangResourceRepository
119                 .findAllModuleReferences(dataspaceName, anchorName);
120         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
121             .collect(Collectors.toList());
122     }
123
124     @Override
125     @Transactional
126     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
127     // can occur in case of specific concurrent requests.
128     @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
129         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
130     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
131         final Map<String, String> moduleReferenceNameToContentMap) {
132         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
133         final var yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
134         final var schemaSetEntity = new SchemaSetEntity();
135         schemaSetEntity.setName(schemaSetName);
136         schemaSetEntity.setDataspace(dataspaceEntity);
137         schemaSetEntity.setYangResources(yangResourceEntities);
138         try {
139             schemaSetRepository.save(schemaSetEntity);
140         } catch (final DataIntegrityViolationException e) {
141             throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
142         }
143     }
144
145     @Override
146     @Transactional
147     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
148     // can occur in case of specific concurrent requests.
149     @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
150         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
151     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
152                                           final Map<String, String> newModuleNameToContentMap,
153                                           final Collection<ModuleReference> moduleReferences) {
154         storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
155         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
156         final var schemaSetEntity =
157                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
158         final List<Long> listOfYangResourceIds = new ArrayList<>();
159         moduleReferences.forEach(moduleReference ->
160                 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
161                         moduleReference.getModuleName(), moduleReference.getRevision())));
162         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
163     }
164
165     @Override
166     @Transactional
167     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
168         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
169         final var schemaSetEntity =
170             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
171         schemaSetRepository.delete(schemaSetEntity);
172     }
173
174     @Override
175     @Transactional
176     public void deleteUnusedYangResourceModules() {
177         yangResourceRepository.deleteOrphans();
178     }
179
180     @Override
181     public Collection<ModuleReference> identifyNewModuleReferences(
182         final Collection<ModuleReference> moduleReferencesToCheck) {
183         return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
184     }
185
186     private Set<YangResourceEntity> synchronizeYangResources(
187         final Map<String, String> moduleReferenceNameToContentMap) {
188         final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
189             .map(entry -> {
190                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
191                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
192                             entry.getValue());
193                 final var yangResourceEntity = new YangResourceEntity();
194                 yangResourceEntity.setName(entry.getKey());
195                 yangResourceEntity.setContent(entry.getValue());
196                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
197                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
198                 yangResourceEntity.setChecksum(checksum);
199                 return yangResourceEntity;
200             })
201             .collect(Collectors.toMap(
202                 YangResourceEntity::getChecksum,
203                 entity -> entity
204             ));
205
206         final List<YangResourceEntity> existingYangResourceEntities =
207             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
208         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
209
210         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
211         if (!newYangResourceEntities.isEmpty()) {
212             try {
213                 yangResourceRepository.saveAll(newYangResourceEntities);
214             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
215                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
216                 // database constraint violation.
217                 // If it is not, then throw the original exception
218                 final Optional<DuplicatedYangResourceException> convertedException =
219                         convertToDuplicatedYangResourceException(
220                                 dataIntegrityViolationException, newYangResourceEntities);
221                 convertedException.ifPresent(
222                     e ->  log.warn(
223                                 "Cannot persist duplicated yang resource. "
224                                         + "System will attempt this method up to 5 times.", e));
225                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
226             }
227         }
228
229         return ImmutableSet.<YangResourceEntity>builder()
230             .addAll(existingYangResourceEntities)
231             .addAll(newYangResourceEntities)
232             .build();
233     }
234
235     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
236         final Map<String, String> metaDataMap = new HashMap<>();
237         final var revisionSourceIdentifier =
238                 createIdentifierFromSourceName(checkNotNull(sourceName));
239
240         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
241             @Override
242             protected MoreObjects.ToStringHelper addToStringAttributes(
243                     final MoreObjects.ToStringHelper toStringHelper) {
244                 return toStringHelper;
245             }
246
247             @Override
248             public InputStream openStream() {
249                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
250             }
251         };
252         try {
253             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
254             metaDataMap.put("moduleName", dependencyInfo.getName());
255             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
256         } catch (final YangSyntaxErrorException | IOException e) {
257             throw new ModelValidationException("Yang resource is invalid.",
258                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
259         }
260         return metaDataMap;
261     }
262
263     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
264         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
265         if (matcher.matches()) {
266             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
267         }
268         return RevisionSourceIdentifier.create(sourceName);
269     }
270
271     /**
272      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
273      * if the cause of the error is a yang checksum database constraint violation.
274      *
275      * @param originalException the original db exception.
276      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
277      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
278      *      cause of the error is not a yang checksum database constraint violation.
279      */
280     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
281             final DataIntegrityViolationException originalException,
282             final Collection<YangResourceEntity> yangResourceEntities) {
283
284         // The exception result
285         DuplicatedYangResourceException duplicatedYangResourceException = null;
286
287         final Throwable cause = originalException.getCause();
288         if (cause instanceof ConstraintViolationException) {
289             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
290             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
291                 // Db constraint related to yang resource checksum uniqueness is not respected
292                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
293                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
294                 duplicatedYangResourceException =
295                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
296             }
297         }
298
299         return Optional.ofNullable(duplicatedYangResourceException);
300
301     }
302
303     /**
304      * Get the name of the yang resource having the specified checksum.
305      *
306      * @param checksum the checksum. Null is supported.
307      * @param yangResourceEntities the list of yang resources to search among.
308      * @return the name found or null if none.
309      */
310     private String getNameForChecksum(
311             final String checksum, final Collection<YangResourceEntity> yangResourceEntities) {
312         return
313                 yangResourceEntities.stream()
314                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
315                         .findFirst()
316                         .map(YangResourceEntity::getName)
317                         .orElse(null);
318     }
319
320     /**
321      * Get the checksum that caused the constraint violation exception.
322      *
323      * @param exception the exception having the checksum in error.
324      * @return the checksum in error or null if not found.
325      */
326     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
327         String checksum = null;
328         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
329         if (matcher.find() && matcher.groupCount() == 1) {
330             checksum = matcher.group(1);
331         }
332         return checksum;
333     }
334
335     private static ModuleReference toModuleReference(
336         final YangResourceModuleReference yangResourceModuleReference) {
337         return ModuleReference.builder()
338             .moduleName(yangResourceModuleReference.getModuleName())
339             .revision(yangResourceModuleReference.getRevision())
340             .build();
341     }
342 }