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