Formatting Code base with ktlint
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / commons / db-lib / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / db / primary / 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.primary.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.BluePrintConstants
25 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants
28 import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
29 import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
30 import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
31 import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
32 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService
33 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
34 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
35 import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs
36 import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
37 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
38 import org.slf4j.LoggerFactory
39 import org.springframework.dao.DataIntegrityViolationException
40 import org.springframework.stereotype.Service
41 import java.io.File
42 import java.nio.file.Path
43 import java.util.UUID
44
45 // TODO("Duplicate : Merge BlueprintProcessorCatalogServiceImpl and ControllerBlueprintCatalogServiceImpl")
46 /**
47  * Similar/Duplicate implementation in [org.onap.ccsdk.cds.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl]
48  */
49 @Service("blueprintsProcessorCatalogService")
50 class BlueprintProcessorCatalogServiceImpl(
51     bluePrintRuntimeValidatorService: BluePrintValidatorService,
52     private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
53     private val blueprintModelRepository: BlueprintModelRepository
54 ) :
55     BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) {
56
57     private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString())
58
59     override suspend fun delete(name: String, version: String) {
60         // Clean blueprint script cache
61         val cacheKey = BluePrintFileUtils
62             .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version))
63         BluePrintCompileCache.cleanClassLoader(cacheKey)
64         log.info("removed cba file name($name), version($version) from cache")
65         // Cleaning Deployed Blueprint
66         deleteNBDir(bluePrintLoadConfiguration.blueprintDeployPath, name, version)
67         log.info("removed cba file name($name), version($version) from deploy location")
68         // Cleaning Data Base
69         blueprintModelRepository
70             .deleteByArtifactNameAndArtifactVersion(name, version)
71         log.info("removed cba file name($name), version($version) from database")
72     }
73
74     override suspend fun get(name: String, version: String, extract: Boolean): Path? {
75
76         val deployFile = normalizedFile(bluePrintLoadConfiguration.blueprintDeployPath, name, version)
77         val cbaFile = normalizedFile(
78             bluePrintLoadConfiguration.blueprintArchivePath,
79             UUID.randomUUID().toString(), "cba.zip"
80         )
81
82         if (extract && deployFile.exists()) {
83             log.info("cba file name($name), version($version) already present(${deployFile.absolutePath})")
84         } else {
85             deployFile.reCreateNBDirs()
86             cbaFile.parentFile.reCreateNBDirs()
87
88             try {
89                 log.info("getting cba file name($name), version($version) from db")
90                 blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version)?.also {
91                     it.blueprintModelContent.run {
92
93                         cbaFile.writeBytes(this!!.content!!)
94                         cbaFile.deCompress(deployFile)
95                         log.info("cba file name($name), version($version) saved in (${deployFile.absolutePath})")
96                     }
97                 }
98
99                 check(deployFile.exists() && deployFile.list().isNotEmpty()) {
100                     throw BluePrintProcessorException("file check failed")
101                 }
102             } catch (e: Exception) {
103                 deleteNBDir(deployFile.absolutePath)
104                 throw BluePrintProcessorException(
105                     "failed to get  get cba file name($name), version($version) from db" +
106                             " : ${e.message}"
107                 )
108             } finally {
109                 deleteNBDir(cbaFile.parentFile.absolutePath)
110             }
111         }
112
113         return if (extract) {
114             deployFile.toPath()
115         } else {
116             cbaFile.toPath()
117         }
118     }
119
120     override suspend fun save(metadata: MutableMap<String, String>, archiveFile: File) {
121         val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]
122         val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]
123
124         check(archiveFile.isFile && !archiveFile.isDirectory) {
125             throw BluePrintException("Not a valid Archive file(${archiveFile.absolutePath})")
126         }
127
128         blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let {
129             log.info("Overwriting blueprint model :$artifactName::$artifactVersion")
130             blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(artifactName, artifactVersion)
131             val deployFile =
132                 normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion)
133
134             val cacheKey = BluePrintFileUtils.compileCacheKey(deployFile)
135             BluePrintCompileCache.cleanClassLoader(cacheKey)
136
137             deleteNBDir(deployFile).let {
138                 if (it) log.info("Deleted deployed blueprint model :$artifactName::$artifactVersion")
139                 else log.info("Fail to delete deployed blueprint model :$artifactName::$artifactVersion")
140             }
141         }
142
143         val blueprintModel = BlueprintModel()
144         blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID]
145         blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL
146         blueprintModel.published = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_VALID]
147             ?: BluePrintConstants.FLAG_N
148         blueprintModel.artifactName = artifactName
149         blueprintModel.artifactVersion = artifactVersion
150         blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR]!!
151         blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS]!!
152         blueprintModel.artifactDescription = "Controller Blueprint for $artifactName:$artifactVersion"
153
154         val blueprintModelContent = BlueprintModelContent()
155         blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID]
156         blueprintModelContent.contentType = "CBA_ZIP"
157         blueprintModelContent.name = "$artifactName:$artifactVersion"
158         blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content"
159         blueprintModelContent.content = archiveFile.readBytes()
160         blueprintModelContent.blueprintModel = blueprintModel
161
162         blueprintModel.blueprintModelContent = blueprintModelContent
163
164         try {
165             blueprintModelRepository.saveAndFlush(blueprintModel)
166         } catch (ex: DataIntegrityViolationException) {
167             throw BluePrintException(
168                 ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " +
169                         "is already exist in database: ${ex.message}", ex
170             )
171         }
172     }
173 }