Merge "Adding Edit catalog functionality"
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / commons / db-lib / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / db / service / BlueprintProcessorCatalogServiceImpl.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2019 Bell Canada.
4  * Modifications Copyright © 2018 IBM.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 package org.onap.ccsdk.cds.blueprintsprocessor.db.service
20
21 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel
22 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelContent
23 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository
24 import org.onap.ccsdk.cds.controllerblueprints.core.*
25 import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants
26 import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
27 import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
28 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService
29 import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
31 import org.slf4j.LoggerFactory
32 import org.springframework.dao.DataIntegrityViolationException
33 import org.springframework.stereotype.Service
34 import java.io.File
35 import java.nio.file.Path
36 import java.util.*
37
38 // TODO("Duplicate : Merge BlueprintProcessorCatalogServiceImpl and ControllerBlueprintCatalogServiceImpl")
39 /**
40  * Similar/Duplicate implementation in [org.onap.ccsdk.cds.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl]
41  */
42 @Service("blueprintsProcessorCatalogService")
43 class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: BluePrintValidatorService,
44                                            private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
45                                            private val blueprintModelRepository: BlueprintModelRepository)
46     : BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) {
47
48     private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString())
49
50     override suspend fun delete(name: String, version: String) {
51         // Clean blueprint script cache
52         val cacheKey = BluePrintFileUtils
53                 .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version))
54         BluePrintCompileCache.cleanClassLoader(cacheKey)
55         log.info("removed cba file name($name), version($version) from cache")
56         // Cleaning Deployed Blueprint
57         deleteNBDir(bluePrintLoadConfiguration.blueprintDeployPath, name, version)
58         log.info("removed cba file name($name), version($version) from deploy location")
59         // Cleaning Data Base
60         blueprintModelRepository
61                 .deleteByArtifactNameAndArtifactVersion(name, version)
62         log.info("removed cba file name($name), version($version) from database")
63     }
64
65
66     override suspend fun get(name: String, version: String, extract: Boolean): Path? {
67
68         val deployFile = normalizedFile(bluePrintLoadConfiguration.blueprintDeployPath, name, version)
69         val cbaFile = normalizedFile(bluePrintLoadConfiguration.blueprintArchivePath,
70                 UUID.randomUUID().toString(), "cba.zip")
71
72         if (extract && deployFile.exists()) {
73             log.info("cba file name($name), version($version) already present(${deployFile.absolutePath})")
74         } else {
75             deployFile.reCreateNBDirs()
76             cbaFile.parentFile.reCreateNBDirs()
77
78             try {
79                 log.info("getting cba file name($name), version($version) from db")
80                 blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version)?.also {
81                     it.blueprintModelContent.run {
82
83                         cbaFile.writeBytes(this!!.content!!)
84                         cbaFile.deCompress(deployFile)
85                         log.info("cba file name($name), version($version) saved in (${deployFile.absolutePath})")
86                     }
87                 }
88
89                 check(deployFile.exists() && deployFile.list().isNotEmpty()) {
90                     throw BluePrintProcessorException("file check failed")
91                 }
92             } catch (e: Exception) {
93                 deleteNBDir(deployFile.absolutePath)
94                 throw BluePrintProcessorException("failed to get  get cba file name($name), version($version) from db" +
95                         " : ${e.message}")
96             } finally {
97                 deleteNBDir(cbaFile.parentFile.absolutePath)
98             }
99         }
100
101         return if (extract) {
102             deployFile.toPath()
103         } else {
104             cbaFile.toPath()
105         }
106     }
107
108     override suspend fun save(metadata: MutableMap<String, String>, archiveFile: File) {
109         val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]
110         val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]
111
112         check(archiveFile.isFile && !archiveFile.isDirectory) {
113             throw BluePrintException("Not a valid Archive file(${archiveFile.absolutePath})")
114         }
115
116         blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let {
117             log.info("Overwriting blueprint model :$artifactName::$artifactVersion")
118             blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(artifactName, artifactVersion)
119             val deployFile =
120                     normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion)
121
122             val cacheKey = BluePrintFileUtils.compileCacheKey(deployFile)
123             BluePrintCompileCache.cleanClassLoader(cacheKey)
124
125             deleteNBDir(deployFile).let {
126                 if (it) log.info("Deleted deployed blueprint model :$artifactName::$artifactVersion")
127                 else log.info("Fail to delete deployed blueprint model :$artifactName::$artifactVersion")
128             }
129         }
130
131         val blueprintModel = BlueprintModel()
132         blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID]
133         blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL
134         blueprintModel.published = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_VALID]
135                 ?: BluePrintConstants.FLAG_N
136         blueprintModel.artifactName = artifactName
137         blueprintModel.artifactVersion = artifactVersion
138         blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR]!!
139         blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS]!!
140         blueprintModel.artifactDescription = "Controller Blueprint for $artifactName:$artifactVersion"
141
142         val blueprintModelContent = BlueprintModelContent()
143         blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID]
144         blueprintModelContent.contentType = "CBA_ZIP"
145         blueprintModelContent.name = "$artifactName:$artifactVersion"
146         blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content"
147         blueprintModelContent.content = archiveFile.readBytes()
148         blueprintModelContent.blueprintModel = blueprintModel
149
150         blueprintModel.blueprintModelContent = blueprintModelContent
151
152         try {
153             blueprintModelRepository.saveAndFlush(blueprintModel)
154         } catch (ex: DataIntegrityViolationException) {
155             throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " +
156                     "is already exist in database: ${ex.message}", ex)
157         }
158     }
159 }