Upgrade Open daylight yang tool to version 8.0.6
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / impl / CpsModulePersistenceServiceImpl.java
index 535cbe2..8008e03 100755 (executable)
@@ -1,7 +1,7 @@
 /*
  *  ============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
  *  ================================================================================
  *  Licensed under the Apache License, Version 2.0 (the "License");
@@ -39,41 +39,40 @@ 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.ModelValidationException;
-import org.onap.cps.spi.exceptions.SchemaSetInUseException;
+import org.onap.cps.spi.model.ModuleDefinition;
 import org.onap.cps.spi.model.ModuleReference;
-import org.onap.cps.spi.repository.AnchorRepository;
 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.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
 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.beans.factory.annotation.Autowired;
 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";
@@ -81,23 +80,15 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
     private static final Pattern RFC6020_RECOMMENDED_FILENAME_PATTERN = Pattern
             .compile("([\\w-]+)@(\\d{4}-\\d{2}-\\d{2})(?:\\.yang)?", Pattern.CASE_INSENSITIVE);
 
-    @Autowired
-    private YangResourceRepository yangResourceRepository;
+    private final YangResourceRepository yangResourceRepository;
 
-    @Autowired
-    private SchemaSetRepository schemaSetRepository;
+    private final SchemaSetRepository schemaSetRepository;
 
-    @Autowired
-    private DataspaceRepository dataspaceRepository;
+    private final DataspaceRepository dataspaceRepository;
 
-    @Autowired
-    private AnchorRepository anchorRepository;
+    private final CpsAdminPersistenceService cpsAdminPersistenceService;
 
-    @Autowired
-    private FragmentRepository fragmentRepository;
-
-    @Autowired
-    private CpsAdminPersistenceService cpsAdminPersistenceService;
+    private final ModuleReferenceRepository moduleReferenceRepository;
 
     @Override
     public Map<String, String> getYangSchemaResources(final String dataspaceName, final String schemaSetName) {
@@ -105,7 +96,7 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
         final var schemaSetEntity =
             schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
         return schemaSetEntity.getYangResources().stream().collect(
-            Collectors.toMap(YangResourceEntity::getName, YangResourceEntity::getContent));
+            Collectors.toMap(YangResourceEntity::getFileName, YangResourceEntity::getContent));
     }
 
     @Override
@@ -115,10 +106,30 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
     }
 
     @Override
-    public List<ModuleReference> getAllYangResourcesModuleReferences() {
-        final List<YangResourceModuleReference> yangResourceModuleReferenceList =
-                yangResourceRepository.findAllModuleNameAndRevision();
+    public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName) {
+        final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
+            yangResourceRepository.findAllModuleReferencesByDataspace(dataspaceName);
         return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
+            .collect(Collectors.toList());
+    }
+
+    @Override
+    public Collection<ModuleReference> getYangResourceModuleReferences(final String dataspaceName,
+                                                                       final String anchorName) {
+        final Set<YangResourceModuleReference> yangResourceModuleReferenceList =
+                yangResourceRepository
+                        .findAllModuleReferencesByDataspaceAndAnchor(dataspaceName, anchorName);
+        return yangResourceModuleReferenceList.stream().map(CpsModulePersistenceServiceImpl::toModuleReference)
+                .collect(Collectors.toList());
+    }
+
+    @Override
+    public Collection<ModuleDefinition> getYangResourceDefinitions(final String dataspaceName,
+                                                                   final String anchorName) {
+        final Set<YangResourceEntity> yangResourceEntities =
+                yangResourceRepository
+                        .findAllModuleDefinitionsByDataspaceAndAnchor(dataspaceName, anchorName);
+        return yangResourceEntities.stream().map(CpsModulePersistenceServiceImpl::toModuleDefinition)
                 .collect(Collectors.toList());
     }
 
@@ -126,12 +137,12 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
     @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<String, String> yangResourcesNameToContentMap) {
-
+        final Map<String, String> moduleReferenceNameToContentMap) {
         final var dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
-        final var yangResourceEntities = synchronizeYangResources(yangResourcesNameToContentMap);
+        final var yangResourceEntities = synchronizeYangResources(moduleReferenceNameToContentMap);
         final var schemaSetEntity = new SchemaSetEntity();
         schemaSetEntity.setName(schemaSetName);
         schemaSetEntity.setDataspace(dataspaceEntity);
@@ -145,32 +156,52 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
 
     @Override
     @Transactional
-    public void deleteSchemaSet(final String dataspaceName, final String schemaSetName,
-        final CascadeDeleteAllowed cascadeDeleteAllowed) {
+    // 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<String, String> newModuleNameToContentMap,
+                                          final Collection<ModuleReference> allModuleReferences) {
+        storeSchemaSet(dataspaceName, schemaSetName, newModuleNameToContentMap);
+        final DataspaceEntity dataspaceEntity = dataspaceRepository.getByName(dataspaceName);
+        final SchemaSetEntity schemaSetEntity =
+                schemaSetRepository.getByDataspaceAndName(dataspaceEntity, schemaSetName);
+        final List<Long> 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);
-
-        final Collection<AnchorEntity> 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);
+    }
+
+    @Override
+    @Transactional
+    public void deleteUnusedYangResourceModules() {
         yangResourceRepository.deleteOrphans();
     }
 
-    private Set<YangResourceEntity> synchronizeYangResources(final Map<String, String> yangResourcesNameToContentMap) {
-        final Map<String, YangResourceEntity> checksumToEntityMap = yangResourcesNameToContentMap.entrySet().stream()
+    @Override
+    public Collection<ModuleReference> identifyNewModuleReferences(
+        final Collection<ModuleReference> moduleReferencesToCheck) {
+        return moduleReferenceRepository.identifyNewModuleReferences(moduleReferencesToCheck);
+    }
+
+    private Set<YangResourceEntity> synchronizeYangResources(
+        final Map<String, String> moduleReferenceNameToContentMap) {
+        final Map<String, YangResourceEntity> checksumToEntityMap = moduleReferenceNameToContentMap.entrySet().stream()
             .map(entry -> {
                 final String checksum = DigestUtils.sha256Hex(entry.getValue().getBytes(StandardCharsets.UTF_8));
                 final Map<String, String> 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"));
@@ -198,9 +229,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;
             }
         }
@@ -217,6 +251,11 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
                 createIdentifierFromSourceName(checkNotNull(sourceName));
 
         final var tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
+            @Override
+            public Optional<String> getSymbolicName() {
+                return Optional.empty();
+            }
+
             @Override
             protected MoreObjects.ToStringHelper addToStringAttributes(
                     final MoreObjects.ToStringHelper toStringHelper) {
@@ -250,6 +289,7 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
     /**
      * 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
@@ -280,6 +320,7 @@ 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.
@@ -290,12 +331,13 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
                 yangResourceEntities.stream()
                         .filter(entity -> StringUtils.equals(checksum, (entity.getChecksum())))
                         .findFirst()
-                        .map(YangResourceEntity::getName)
+                        .map(YangResourceEntity::getFileName)
                         .orElse(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.
      */
@@ -308,10 +350,18 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
         return checksum;
     }
 
-    private static ModuleReference toModuleReference(final YangResourceModuleReference yangResourceModuleReference) {
+    private static ModuleReference toModuleReference(
+        final YangResourceModuleReference yangResourceModuleReference) {
         return ModuleReference.builder()
-                .name(yangResourceModuleReference.getModuleName())
-                .revision(yangResourceModuleReference.getRevision())
-                .build();
+            .moduleName(yangResourceModuleReference.getModuleName())
+            .revision(yangResourceModuleReference.getRevision())
+            .build();
+    }
+
+    private static ModuleDefinition toModuleDefinition(final YangResourceEntity yangResourceEntity) {
+        return new ModuleDefinition(
+                yangResourceEntity.getModuleName(),
+                yangResourceEntity.getRevision(),
+                yangResourceEntity.getContent());
     }
 }