X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=cps-ri%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fcps%2Fspi%2Fimpl%2FCpsModulePersistenceServiceImpl.java;h=c9f9a78ef53b16e56e155c76386fb12293015c37;hb=3ded83809e65eec2ac673f157b03212472a29833;hp=1b3dc2486f41fd5955baa671abbb56b0392ae787;hpb=0e210d77ec39915046a95615f5f9d2a2dc65162b;p=cps.git diff --git a/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java b/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java index 1b3dc2486..c9f9a78ef 100755 --- a/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java +++ b/cps-ri/src/main/java/org/onap/cps/spi/impl/CpsModulePersistenceServiceImpl.java @@ -1,8 +1,9 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation - * Modifications Copyright (C) 2020-2021 Bell Canada. + * Copyright (C) 2020-2022 Nordix Foundation + * Modifications Copyright (C) 2020-2022 Bell Canada. * Modifications Copyright (C) 2021 Pantheon.tech + * Modifications Copyright (C) 2022 TechMahindra Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +23,16 @@ package org.onap.cps.spi.impl; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -32,66 +40,111 @@ import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.transaction.Transactional; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.exception.ConstraintViolationException; -import org.onap.cps.spi.CascadeDeleteAllowed; import org.onap.cps.spi.CpsAdminPersistenceService; import org.onap.cps.spi.CpsModulePersistenceService; -import org.onap.cps.spi.entities.AnchorEntity; +import org.onap.cps.spi.entities.DataspaceEntity; import org.onap.cps.spi.entities.SchemaSetEntity; import org.onap.cps.spi.entities.YangResourceEntity; +import org.onap.cps.spi.entities.YangResourceModuleReference; import org.onap.cps.spi.exceptions.AlreadyDefinedException; import org.onap.cps.spi.exceptions.DuplicatedYangResourceException; -import org.onap.cps.spi.exceptions.SchemaSetInUseException; -import org.onap.cps.spi.repository.AnchorRepository; +import org.onap.cps.spi.exceptions.ModelValidationException; +import org.onap.cps.spi.model.ModuleDefinition; +import org.onap.cps.spi.model.ModuleReference; +import org.onap.cps.spi.model.SchemaSet; import org.onap.cps.spi.repository.DataspaceRepository; -import org.onap.cps.spi.repository.FragmentRepository; +import org.onap.cps.spi.repository.ModuleReferenceRepository; import org.onap.cps.spi.repository.SchemaSetRepository; import org.onap.cps.spi.repository.YangResourceRepository; -import org.springframework.beans.factory.annotation.Autowired; +import org.opendaylight.yangtools.yang.common.Revision; +import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; +import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; +import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException; +import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; +import org.springframework.retry.support.RetrySynchronizationManager; import org.springframework.stereotype.Component; - -@Component @Slf4j +@Component +@RequiredArgsConstructor public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceService { private static final String YANG_RESOURCE_CHECKSUM_CONSTRAINT_NAME = "yang_resource_checksum_key"; private static final Pattern CHECKSUM_EXCEPTION_PATTERN = Pattern.compile(".*\\(checksum\\)=\\((\\w+)\\).*"); + private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern + .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE); + + private final YangResourceRepository yangResourceRepository; + + private final SchemaSetRepository schemaSetRepository; + + private final DataspaceRepository dataspaceRepository; - @Autowired - private YangResourceRepository yangResourceRepository; + private final CpsAdminPersistenceService cpsAdminPersistenceService; - @Autowired - private SchemaSetRepository schemaSetRepository; + private final ModuleReferenceRepository moduleReferenceRepository; + + @Override + public Map getYangSchemaResources(final String dataspaceName, final String schemaSetName) { + final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName); + final var schemaSetEntity = + schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName); + return schemaSetEntity.getYangResources().stream().collect( + Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent)); + } - @Autowired - private DataspaceRepository dataspaceRepository; + @Override + public Map getYangSchemaSetResources(final String dataspaceName, final String anchorName) { + final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName); + return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName()); + } - @Autowired - private AnchorRepository anchorRepository; + @Override + public Collection getYangResourceModuleReferences(final String dataspaceName) { + final Set yangResourceModuleReferenceList = + yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName); + return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference) + .collect(Collectors.toList()); + } - @Autowired - private FragmentRepository fragmentRepository; + @Override + public Collection getYangResourceModuleReferences(final String dataspaceName, + final String anchorName) { + final Set yangResourceModuleReferenceList = + yangResourceRepository + .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName); + return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference) + .collect(Collectors.toList()); + } - @Autowired - private CpsAdminPersistenceService cpsAdminPersistenceService; + @Override + public Collection getYangResourceDefinitions(final String dataspaceName, + final String anchorName) { + final Set yangResourceEntities = + yangResourceRepository + .findAllModuleDefinitionsByDataspaceAndAnchor(dataspaceName, anchorName); + return yangResourceEntities.stream().map(CpsModulePersistenceServiceImpl::toModuleDefinition) + .collect(Collectors.toList()); + } @Override @Transactional // A retry is made to store the schema set if it fails because of duplicated yang resource exception that // can occur in case of specific concurrent requests. - @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 2, backoff = @Backoff(delay = 500)) + @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff = + @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2)) public void storeSchemaSet(final String dataspaceName, final String schemaSetName, - final Map yangResourcesNameToContentMap) { - + final Map moduleReferenceNameToContentMap) { final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName); - final Set yangResourceEntities = synchronizeYangResources(yangResourcesNameToContentMap); + final var yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap); final var schemaSetEntity = new SchemaSetEntity(); schemaSetEntity.setName(schemaSetName); schemaSetEntity.setDataspace(dataspaceEntity); @@ -103,13 +156,65 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ } } - private Set synchronizeYangResources(final Map yangResourcesNameToContentMap) { - final Map checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream() + @Override + public Collection getSchemaSetsByDataspaceName(final String dataspaceName) { + final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName); + final List schemaSetEntities = schemaSetRepository.getByDataspace(dataspaceEntity); + return schemaSetEntities.stream() + .map(CpsModulePersistenceServiceImpl::toSchemaSet).collect(Collectors.toList()); + } + + @Override + @Transactional + // A retry is made to store the schema set if it fails because of duplicated yang resource exception that + // can occur in case of specific concurrent requests. + @Retryable(value = DuplicatedYangResourceException.class, maxAttempts = 5, backoff = + @Backoff(random = true, delay = 200, maxDelay = 2000, multiplier = 2)) + public void storeSchemaSetFromModules(final String dataspaceName, final String schemaSetName, + final Map newModuleNameToContentMap, + final Collection allModuleReferences) { + storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap); + final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName); + final SchemaSetEntity schemaSetEntity = + schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName); + final List allYangResourceIds = + yangResourceRepository.getResourceIdsByModuleReferences(allModuleReferences); + yangResourceRepository.insertSchemaSetIdYangResourceId(schemaSetEntity.getId(), allYangResourceIds); + } + + @Override + @Transactional + public void deleteSchemaSet(final String dataspaceName, final String schemaSetName) { + final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName); + final var schemaSetEntity = + schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName); + schemaSetRepository.delete(schemaSetEntity); + } + + @Override + @Transactional + public void deleteUnusedYangResourceModules() { + yangResourceRepository.deleteOrphans(); + } + + @Override + public Collection identifyNewModuleReferences( + final Collection moduleReferencesToCheck) { + return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck); + } + + private Set synchronizeYangResources( + final Map moduleReferenceNameToContentMap) { + final Map checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream() .map(entry -> { final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8)); + final Map moduleNameAndRevisionMap = createModuleNameAndRevisionMap(entry.getKey(), + entry.getValue()); final var yangResourceEntity = new YangResourceEntity(); - yangResourceEntity.setName(entry.getKey()); + yangResourceEntity.setFileName(entry.getKey()); yangResourceEntity.setContent(entry.getValue()); + yangResourceEntity.setModuleName(moduleNameAndRevisionMap.get("moduleName")); + yangResourceEntity.setRevision(moduleNameAndRevisionMap.get("revision")); yangResourceEntity.setChecksum(checksum); return yangResourceEntity; }) @@ -134,9 +239,12 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ convertToDuplicatedYangResourceException( dataIntegrityViolationException, newYangResourceEntities); convertedException.ifPresent( - e -> log.warn( - "Cannot persist duplicated yang resource. " - + "A total of 2 attempts to store the schema set are planned.", e)); + e -> { + int retryCount = RetrySynchronizationManager.getContext() == null ? 0 + : RetrySynchronizationManager.getContext().getRetryCount(); + log.warn("Cannot persist duplicated yang resource. System will attempt this method " + + "up to 5 times. Current retry count : {}", ++retryCount, e); + }); throw convertedException.isPresent() ? convertedException.get() : dataIntegrityViolationException; } } @@ -147,9 +255,51 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ .build(); } + private static Map createModuleNameAndRevisionMap(final String sourceName, final String source) { + final Map metaDataMap = new HashMap<>(); + final var revisionSourceIdentifier = + createIdentifierFromSourceName(checkNotNull(sourceName)); + + final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) { + @Override + public Optional getSymbolicName() { + return Optional.empty(); + } + + @Override + protected MoreObjects.ToStringHelper addToStringAttributes( + final MoreObjects.ToStringHelper toStringHelper) { + return toStringHelper; + } + + @Override + public InputStream openStream() { + return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)); + } + }; + try { + final var dependencyInfo = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource); + metaDataMap.put("moduleName", dependencyInfo.getName()); + metaDataMap.put("revision", dependencyInfo.getFormattedRevision()); + } catch (final YangSyntaxErrorException | IOException e) { + throw new ModelValidationException("Yang resource is invalid.", + String.format("Yang syntax validation failed for resource %s:%n%s", sourceName, e.getMessage()), e); + } + return metaDataMap; + } + + private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) { + final var matcher = RFC6020_RECOMMENDED_FILENAME_PATTERN.matcher(sourceName); + if (matcher.matches()) { + return RevisionSourceIdentifier.create(matcher.group(1), Revision.of(matcher.group(2))); + } + return RevisionSourceIdentifier.create(sourceName); + } + /** * Convert the specified data integrity violation exception into a CPS duplicated Yang resource exception * if the cause of the error is a yang checksum database constraint violation. + * * @param originalException the original db exception. * @param yangResourceEntities the collection of Yang resources involved in the db failure. * @return an optional converted CPS duplicated Yang resource exception. The optional is empty if the original @@ -178,8 +328,28 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ } + /** + * Get the name of the yang resource having the specified checksum. + * + * @param checksum the checksum. Null is supported. + * @param yangResourceEntities the list of yang resources to search among. + * @return the name found or null if none. + */ + private String getNameForChecksum( + final String checksum, final Collection yangResourceEntities) { + final Optional optionalFileName = yangResourceEntities.stream() + .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum()))) + .findFirst() + .map(YangResourceEntity::getFileName); + if (optionalFileName.isPresent()) { + return optionalFileName.get(); + } + return null; + } + /** * Get the checksum that caused the constraint violation exception. + * * @param exception the exception having the checksum in error. * @return the checksum in error or null if not found. */ @@ -192,54 +362,23 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ return checksum; } - /** - * Get the name of the yang resource having the specified checksum. - * @param checksum the checksum. Null is supported. - * @param yangResourceEntities the list of yang resources to search among. - * @return the name found or null if none. - */ - private String getNameForChecksum( - final String checksum, final Collection yangResourceEntities) { - return - yangResourceEntities.stream() - .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum()))) - .findFirst() - .map(YangResourceEntity::getName) - .orElse(null); + private static ModuleReference toModuleReference( + final YangResourceModuleReference yangResourceModuleReference) { + return ModuleReference.builder() + .moduleName(yangResourceModuleReference.getModuleName()) + .revision(yangResourceModuleReference.getRevision()) + .build(); } - @Override - public Map getYangSchemaResources(final String dataspaceName, final String schemaSetName) { - final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName); - final var schemaSetEntity = - schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName); - return schemaSetEntity.getYangResources().stream().collect( - Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent)); + private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) { + return new ModuleDefinition( + yangResourceEntity.getModuleName(), + yangResourceEntity.getRevision(), + yangResourceEntity.getContent()); } - @Override - public Map getYangSchemaSetResources(final String dataspaceName, final String anchorName) { - final var anchor = cpsAdminPersistenceService.getAnchor(dataspaceName, anchorName); - return getYangSchemaResources(dataspaceName, anchor.getSchemaSetName()); - } - - @Override - @Transactional - public void deleteSchemaSet(final String dataspaceName, final String schemaSetName, - final CascadeDeleteAllowed cascadeDeleteAllowed) { - final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName); - final var schemaSetEntity = - schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName); - - final Collection anchorEntities = anchorRepository.findAllBySchemaSet(schemaSetEntity); - if (!anchorEntities.isEmpty()) { - if (cascadeDeleteAllowed != CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED) { - throw new SchemaSetInUseException(dataspaceName, schemaSetName); - } - fragmentRepository.deleteByAnchorIn(anchorEntities); - anchorRepository.deleteAll(anchorEntities); - } - schemaSetRepository.delete(schemaSetEntity); - yangResourceRepository.deleteOrphans(); + private static SchemaSet toSchemaSet(final SchemaSetEntity schemaSetEntity) { + return SchemaSet.builder().name(schemaSetEntity.getName()) + .dataspaceName(schemaSetEntity.getDataspace().getName()).build(); } }