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