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