e0f54265ab8ff92fdbc0fc15c31113b34e81160f
[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 Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
120         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
121             yangResourceRepository.findAllModuleReferences(dataspaceName);
122         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
123             .collect(Collectors.toList());
124     }
125
126     @Override
127     public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
128         final String anchorName) {
129         final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
130             yangResourceRepository
131                 .findAllModuleReferences(dataspaceName, anchorName);
132         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
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 = 2, backoff = @Backoff(delay = 500))
141     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
142         final Map<String, String> yangResourcesNameToContentMap) {
143
144         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
145         final var yangResourceEntities = synchronizeYangResources(yangResourcesNameToContentMap);
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     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
160                                           final Map<String, String> newYangResourcesModuleNameToContentMap,
161                                           final List<ModuleReference> moduleReferences) {
162         storeSchemaSet(dataspaceName, schemaSetName, newYangResourcesModuleNameToContentMap);
163         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
164         final var schemaSetEntity =
165                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
166         final List<Long> listOfYangResourceIds = new ArrayList<>();
167         moduleReferences.forEach(moduleReference ->
168                 listOfYangResourceIds.add(yangResourceRepository.getIdByModuleNameAndRevision(
169                         moduleReference.getModuleName(), moduleReference.getRevision())));
170         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), listOfYangResourceIds);
171     }
172
173     @Override
174     @Transactional
175     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName,
176         final CascadeDeleteAllowed cascadeDeleteAllowed) {
177         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
178         final var schemaSetEntity =
179             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
180
181         final Collection<AnchorEntity> anchorEntities = anchorRepository.findAllBySchemaSet(schemaSetEntity);
182         if (!anchorEntities.isEmpty()) {
183             if (cascadeDeleteAllowed != CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED) {
184                 throw new SchemaSetInUseException(dataspaceName, schemaSetName);
185             }
186             fragmentRepository.deleteByAnchorIn(anchorEntities);
187             anchorRepository.deleteAll(anchorEntities);
188         }
189         schemaSetRepository.delete(schemaSetEntity);
190         yangResourceRepository.deleteOrphans();
191     }
192
193     private Set<YangResourceEntity> synchronizeYangResources(final Map<String, String> yangResourcesNameToContentMap) {
194         final Map<String, YangResourceEntity> checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream()
195             .map(entry -> {
196                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
197                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
198                             entry.getValue());
199                 final var yangResourceEntity = new YangResourceEntity();
200                 yangResourceEntity.setName(entry.getKey());
201                 yangResourceEntity.setContent(entry.getValue());
202                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
203                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
204                 yangResourceEntity.setChecksum(checksum);
205                 return yangResourceEntity;
206             })
207             .collect(Collectors.toMap(
208                 YangResourceEntity::getChecksum,
209                 entity -> entity
210             ));
211
212         final List<YangResourceEntity> existingYangResourceEntities =
213             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
214         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
215
216         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
217         if (!newYangResourceEntities.isEmpty()) {
218             try {
219                 yangResourceRepository.saveAll(newYangResourceEntities);
220             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
221                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
222                 // database constraint violation.
223                 // If it is not, then throw the original exception
224                 final Optional<DuplicatedYangResourceException> convertedException =
225                         convertToDuplicatedYangResourceException(
226                                 dataIntegrityViolationException, newYangResourceEntities);
227                 convertedException.ifPresent(
228                     e ->  log.warn(
229                                 "Cannot persist duplicated yang resource. "
230                                         + "A total of 2 attempts to store the schema set are planned.", e));
231                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
232             }
233         }
234
235         return ImmutableSet.<YangResourceEntity>builder()
236             .addAll(existingYangResourceEntities)
237             .addAll(newYangResourceEntities)
238             .build();
239     }
240
241     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
242         final Map<String, String> metaDataMap = new HashMap<>();
243         final var revisionSourceIdentifier =
244                 createIdentifierFromSourceName(checkNotNull(sourceName));
245
246         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
247             @Override
248             protected MoreObjects.ToStringHelper addToStringAttributes(
249                     final MoreObjects.ToStringHelper toStringHelper) {
250                 return toStringHelper;
251             }
252
253             @Override
254             public InputStream openStream() {
255                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
256             }
257         };
258         try {
259             final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
260             metaDataMap.put("moduleName", dependencyInfo.getName());
261             metaDataMap.put("revision", dependencyInfo.getFormattedRevision());
262         } catch (final YangSyntaxErrorException | IOException e) {
263             throw new ModelValidationException("Yang resource is invalid.",
264                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
265         }
266         return metaDataMap;
267     }
268
269     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
270         final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
271         if (matcher.matches()) {
272             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
273         }
274         return RevisionSourceIdentifier.create(sourceName);
275     }
276
277     /**
278      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
279      * if the cause of the error is a yang checksum database constraint violation.
280      * @param originalException the original db exception.
281      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
282      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
283      *      cause of the error is not a yang checksum database constraint violation.
284      */
285     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
286             final DataIntegrityViolationException originalException,
287             final Collection<YangResourceEntity> yangResourceEntities) {
288
289         // The exception result
290         DuplicatedYangResourceException duplicatedYangResourceException = null;
291
292         final Throwable cause = originalException.getCause();
293         if (cause instanceof ConstraintViolationException) {
294             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
295             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
296                 // Db constraint related to yang resource checksum uniqueness is not respected
297                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
298                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
299                 duplicatedYangResourceException =
300                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
301             }
302         }
303
304         return Optional.ofNullable(duplicatedYangResourceException);
305
306     }
307
308     /**
309      * Get the name of the yang resource having the specified checksum.
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      * @param exception the exception having the checksum in error.
327      * @return the checksum in error or null if not found.
328      */
329     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
330         String checksum = null;
331         final var matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
332         if (matcher.find() && matcher.groupCount() == 1) {
333             checksum = matcher.group(1);
334         }
335         return checksum;
336     }
337
338     private static ModuleReference toModuleReference(
339         final YangResourceModuleReference yangResourceModuleReference) {
340         return ModuleReference.builder()
341             .moduleName(yangResourceModuleReference.getModuleName())
342             .revision(yangResourceModuleReference.getRevision())
343             .build();
344     }
345 }