b449a789b0bd5249a0b078b35820e881abd1f92f
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsModulePersistenceServiceImpl.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2020-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2020-2022 Bell Canada.
5  *  Modifications Copyright (C) 2021 Pantheon.tech
6  *  Modifications Copyright (C) 2022 TechMahindra Ltd.
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.spi.impl;
25
26 import static com.google.common.base.Preconditions.checkNotNull;
27
28 import com.google.common.base.MoreObjects;
29 import com.google.common.collect.ImmutableSet;
30 import jakarta.transaction.Transactional;
31 import java.io.ByteArrayInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.nio.charset.StandardCharsets;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Optional;
42 import java.util.Set;
43 import java.util.regex.Matcher;
44 import java.util.regex.Pattern;
45 import java.util.stream.Collectors;
46 import lombok.RequiredArgsConstructor;
47 import lombok.extern.slf4j.Slf4j;
48 import org.apache.commons.codec.digest.DigestUtils;
49 import org.apache.commons.lang3.StringUtils;
50 import org.hibernate.exception.ConstraintViolationException;
51 import org.onap.cps.spi.CpsModulePersistenceService;
52 import org.onap.cps.spi.entities.DataspaceEntity;
53 import org.onap.cps.spi.entities.SchemaSetEntity;
54 import org.onap.cps.spi.entities.YangResourceEntity;
55 import org.onap.cps.spi.entities.YangResourceModuleReference;
56 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
57 import org.onap.cps.spi.exceptions.DuplicatedYangResourceException;
58 import org.onap.cps.spi.exceptions.ModelValidationException;
59 import org.onap.cps.spi.model.ModuleDefinition;
60 import org.onap.cps.spi.model.ModuleReference;
61 import org.onap.cps.spi.model.SchemaSet;
62 import org.onap.cps.spi.repository.DataspaceRepository;
63 import org.onap.cps.spi.repository.ModuleReferenceRepository;
64 import org.onap.cps.spi.repository.SchemaSetRepository;
65 import org.onap.cps.spi.repository.YangResourceRepository;
66 import org.opendaylight.yangtools.yang.common.Revision;
67 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
68 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
69 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
70 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
71 import org.springframework.dao.DataIntegrityViolationException;
72 import org.springframework.retry.RetryContext;
73 import org.springframework.retry.annotation.Backoff;
74 import org.springframework.retry.annotation.Retryable;
75 import org.springframework.retry.support.RetrySynchronizationManager;
76 import org.springframework.stereotype.Component;
77
78 @Slf4j
79 @Component
80 @RequiredArgsConstructor
81 public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService {
82
83     private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key";
84     private static final String NO_MODULE_NAME_FILTER = null;
85     private static final String NO_MODULE_REVISION = null;
86     private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*");
87     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
88             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
89
90     private final YangResourceRepository yangResourceRepository;
91
92     private final SchemaSetRepository schemaSetRepository;
93
94     private final DataspaceRepository dataspaceRepository;
95
96     private final ModuleReferenceRepository moduleReferenceRepository;
97
98     @Override
99     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
100         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
101         final SchemaSetEntity schemaSetEntity =
102             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
103         return schemaSetEntity.getYangResources().stream().collect(
104             Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent));
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     public Collection<ModuleDefinition> getYangResourceDefinitions(final String dataspaceName,
127                                                                    final String anchorName) {
128         final Set<YangResourceEntity> yangResourceEntities =
129                 yangResourceRepository.findAllModuleDefinitionsByDataspaceAndAnchorAndModule(dataspaceName, anchorName,
130                     NO_MODULE_NAME_FILTER, NO_MODULE_REVISION);
131         return convertYangResourceEntityToModuleDefinition(yangResourceEntities);
132     }
133
134     @Override
135     public Collection<ModuleDefinition> getYangResourceDefinitionsByAnchorAndModule(final String dataspaceName,
136                                                                                     final String anchorName,
137                                                                                     final String moduleName,
138                                                                                     final String moduleRevision) {
139         final Set<YangResourceEntity> yangResourceEntities =
140             yangResourceRepository.findAllModuleDefinitionsByDataspaceAndAnchorAndModule(dataspaceName, anchorName,
141                 moduleName, moduleRevision);
142         return convertYangResourceEntityToModuleDefinition(yangResourceEntities);
143     }
144
145     private List<ModuleDefinition> convertYangResourceEntityToModuleDefinition(final Set<YangResourceEntity>
146                                                                                    yangResourceEntities) {
147         final List<ModuleDefinition> resultModuleDefinitions = new ArrayList<>(yangResourceEntities.size());
148         for (final YangResourceEntity yangResourceEntity: yangResourceEntities) {
149             resultModuleDefinitions.add(toModuleDefinition(yangResourceEntity));
150         }
151         return resultModuleDefinitions;
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(retryFor = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
159         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
160     public void storeSchemaSet(final String dataspaceName, final String schemaSetName,
161         final Map<String, String> moduleReferenceNameToContentMap) {
162         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
163         final Set<YangResourceEntity> yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
164         final SchemaSetEntity schemaSetEntity = new SchemaSetEntity();
165         schemaSetEntity.setName(schemaSetName);
166         schemaSetEntity.setDataspace(dataspaceEntity);
167         schemaSetEntity.setYangResources(yangResourceEntities);
168         try {
169             schemaSetRepository.save(schemaSetEntity);
170         } catch (final DataIntegrityViolationException e) {
171             throw AlreadyDefinedException.forSchemaSet(schemaSetName, dataspaceName, e);
172         }
173     }
174
175     @Override
176     public Collection<SchemaSet> getSchemaSetsByDataspaceName(final String dataspaceName) {
177         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
178         final List<SchemaSetEntity> schemaSetEntities = schemaSetRepository.findByDataspace(dataspaceEntity);
179         return schemaSetEntities.stream()
180                 .map(CpsModulePersistenceServiceImpl::toSchemaSet).collect(Collectors.toList());
181     }
182
183     @Override
184     @Transactional
185     // A retry is made to store the schema set if it fails because of duplicated yang resource exception that
186     // can occur in case of specific concurrent requests.
187     @Retryable(retryFor = DuplicatedYangResourceException.class, maxAttempts = 5, backoff =
188         @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2))
189     public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
190                                           final Map<String, String> newModuleNameToContentMap,
191                                           final Collection<ModuleReference> allModuleReferences) {
192         storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
193         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
194         final SchemaSetEntity schemaSetEntity =
195                 schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
196         final List<Integer> allYangResourceIds =
197             yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
198         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), allYangResourceIds);
199     }
200
201     @Override
202     @Transactional
203     public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) {
204         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
205         final SchemaSetEntity schemaSetEntity =
206             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
207         schemaSetRepository.delete(schemaSetEntity);
208     }
209
210     @Override
211     @Transactional
212     public void deleteSchemaSets(final String dataspaceName, final Collection<String> schemaSetNames) {
213         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
214         schemaSetRepository.deleteByDataspaceAndNameIn(dataspaceEntity, schemaSetNames);
215     }
216
217
218     @Override
219     @Transactional
220     public void updateSchemaSetFromModules(final String dataspaceName, final String schemaSetName,
221                                            final Map<String, String> newModuleNameToContentMap,
222                                            final Collection<ModuleReference> allModuleReferences) {
223         final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
224         final SchemaSetEntity schemaSetEntity =
225             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
226         storeAndLinkNewModules(newModuleNameToContentMap, schemaSetEntity);
227         updateAllModuleReferences(allModuleReferences, schemaSetEntity.getId());
228     }
229
230
231
232     @Override
233     @Transactional
234     public void deleteUnusedYangResourceModules() {
235         yangResourceRepository.deleteOrphans();
236     }
237
238     @Override
239     public Collection<ModuleReference> identifyNewModuleReferences(
240         final Collection<ModuleReference> moduleReferencesToCheck) {
241         return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
242     }
243
244     private Set<YangResourceEntity> synchronizeYangResources(
245         final Map<String, String> moduleReferenceNameToContentMap) {
246         final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
247             .map(entry -> {
248                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
249                 final Map<String, String> moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(),
250                             entry.getValue());
251                 final YangResourceEntity yangResourceEntity = new YangResourceEntity();
252                 yangResourceEntity.setFileName(entry.getKey());
253                 yangResourceEntity.setContent(entry.getValue());
254                 yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName"));
255                 yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision"));
256                 yangResourceEntity.setChecksum(checksum);
257                 return yangResourceEntity;
258             })
259             .collect(Collectors.toMap(
260                 YangResourceEntity::getChecksum,
261                 entity -> entity
262             ));
263
264         final List<YangResourceEntity> existingYangResourceEntities =
265             yangResourceRepository.findAllByChecksumIn(checksumToEntityMap.keySet());
266         existingYangResourceEntities.forEach(yangFile -> checksumToEntityMap.remove(yangFile.getChecksum()));
267
268         final Collection<YangResourceEntity> newYangResourceEntities = checksumToEntityMap.values();
269         if (!newYangResourceEntities.isEmpty()) {
270             try {
271                 yangResourceRepository.saveAll(newYangResourceEntities);
272             } catch (final DataIntegrityViolationException dataIntegrityViolationException) {
273                 // Throw a CPS duplicated Yang resource exception if the cause of the error is a yang checksum
274                 // database constraint violation.
275                 // If it is not, then throw the original exception
276                 final Optional<DuplicatedYangResourceException> convertedException =
277                         convertToDuplicatedYangResourceException(
278                                 dataIntegrityViolationException, newYangResourceEntities);
279                 convertedException.ifPresent(
280                         e -> {
281                             final RetryContext context = RetrySynchronizationManager.getContext();
282                             int retryCount = context == null ? 0 : context.getRetryCount();
283                             log.warn("Cannot persist duplicated yang resource. System will attempt this method "
284                                     + "up to 5 times. Current retry count : {}", ++retryCount, e);
285                         });
286                 throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException;
287             }
288         }
289
290         return ImmutableSet.<YangResourceEntity>builder()
291             .addAll(existingYangResourceEntities)
292             .addAll(newYangResourceEntities)
293             .build();
294     }
295
296     private static Map<String, String> createModuleNameAndRevisionMap(final String sourceName, final String source) {
297         final Map<String, String> metaDataMap = new HashMap<>();
298         final RevisionSourceIdentifier revisionSourceIdentifier =
299             createIdentifierFromSourceName(checkNotNull(sourceName));
300
301         final YangTextSchemaSource tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
302             @Override
303             public Optional<String> getSymbolicName() {
304                 return Optional.empty();
305             }
306
307             @Override
308             protected MoreObjects.ToStringHelper addToStringAttributes(
309                     final MoreObjects.ToStringHelper toStringHelper) {
310                 return toStringHelper;
311             }
312
313             @Override
314             public InputStream openStream() {
315                 return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
316             }
317         };
318         try {
319             final YangModelDependencyInfo yangModelDependencyInfo
320                 = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
321             metaDataMap.put("moduleName", yangModelDependencyInfo.getName());
322             metaDataMap.put("revision", yangModelDependencyInfo.getFormattedRevision());
323         } catch (final YangSyntaxErrorException | IOException e) {
324             throw new ModelValidationException("Yang resource is invalid.",
325                    String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e);
326         }
327         return metaDataMap;
328     }
329
330     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
331         final Matcher matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName);
332         if (matcher.matches()) {
333             return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2)));
334         }
335         return RevisionSourceIdentifier.create(sourceName);
336     }
337
338     /**
339      * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception
340      * if the cause of the error is a yang checksum database constraint violation.
341      *
342      * @param originalException the original db exception.
343      * @param yangResourceEntities the collection of Yang resources involved in the db failure.
344      * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original
345      *      cause of the error is not a yang checksum database constraint violation.
346      */
347     private Optional<DuplicatedYangResourceException> convertToDuplicatedYangResourceException(
348             final DataIntegrityViolationException originalException,
349             final Collection<YangResourceEntity> yangResourceEntities) {
350
351         // The exception result
352         DuplicatedYangResourceException duplicatedYangResourceException = null;
353
354         final Throwable cause = originalException.getCause();
355         if (cause instanceof ConstraintViolationException) {
356             final ConstraintViolationException constraintException = (ConstraintViolationException) cause;
357             if (YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME.equals(constraintException.getConstraintName())) {
358                 // Db constraint related to yang resource checksum uniqueness is not respected
359                 final String checksumInError = getDuplicatedChecksumFromException(constraintException);
360                 final String nameInError = getNameForChecksum(checksumInError, yangResourceEntities);
361                 duplicatedYangResourceException =
362                         new DuplicatedYangResourceException(nameInError, checksumInError, constraintException);
363             }
364         }
365
366         return Optional.ofNullable(duplicatedYangResourceException);
367
368     }
369
370     private String getNameForChecksum(final String checksum,
371                                       final Collection<YangResourceEntity> yangResourceEntities) {
372         final Optional<String> optionalFileName = yangResourceEntities.stream()
373                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
374                         .findFirst()
375                         .map(YangResourceEntity::getFileName);
376         return optionalFileName.orElse("no filename");
377     }
378
379     private String getDuplicatedChecksumFromException(final ConstraintViolationException exception) {
380         final Matcher matcher = CHECKSUM_EXCEPTION_PATTERN.matcher(exception.getSQLException().getMessage());
381         if (matcher.find()) {
382             return matcher.group(1);
383         }
384         return "no checksum found";
385     }
386
387     private static ModuleReference toModuleReference(
388         final YangResourceModuleReference yangResourceModuleReference) {
389         return ModuleReference.builder()
390             .moduleName(yangResourceModuleReference.getModuleName())
391             .revision(yangResourceModuleReference.getRevision())
392             .build();
393     }
394
395     private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
396         return new ModuleDefinition(
397                 yangResourceEntity.getModuleName(),
398                 yangResourceEntity.getRevision(),
399                 yangResourceEntity.getContent());
400     }
401
402     private static SchemaSet toSchemaSet(final SchemaSetEntity schemaSetEntity) {
403         return SchemaSet.builder().name(schemaSetEntity.getName())
404                 .dataspaceName(schemaSetEntity.getDataspace().getName()).build();
405     }
406
407     private void storeAndLinkNewModules(final Map<String, String> newModuleNameToContentMap,
408                                         final SchemaSetEntity schemaSetEntity) {
409         final Set<YangResourceEntity> yangResourceEntities
410             = new HashSet<>(synchronizeYangResources(newModuleNameToContentMap));
411         schemaSetEntity.setYangResources(yangResourceEntities);
412         schemaSetRepository.save(schemaSetEntity);
413     }
414
415     private void updateAllModuleReferences(final Collection<ModuleReference> allModuleReferences,
416                                            final Integer schemaSetEntityId) {
417         yangResourceRepository.deleteSchemaSetYangResourceForSchemaSetId(schemaSetEntityId);
418         final List<Integer> allYangResourceIds =
419             yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences);
420         yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntityId, allYangResourceIds);
421     }
422
423 }