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