2 * Copyright © 2017-2018 AT&T Intellectual Property.
3 * Modifications Copyright © 2019 IBM.
4 * Modifications Copyright © 2020 Orange.
5 * Modifications Copyright © 2020 Deutsche Telekom AG.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 package org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.profile.upload
22 import com.fasterxml.jackson.databind.JsonNode
23 import com.fasterxml.jackson.databind.node.ArrayNode
24 import com.fasterxml.jackson.databind.node.ObjectNode
25 import org.apache.commons.io.FileUtils
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
28 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
29 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService
30 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
31 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
32 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
33 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
34 import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
35 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
36 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
37 import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType
38 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
39 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
40 import org.slf4j.LoggerFactory
41 import org.springframework.beans.factory.config.ConfigurableBeanFactory
42 import org.springframework.context.annotation.Scope
43 import org.springframework.stereotype.Component
44 import org.yaml.snakeyaml.Yaml
46 import java.nio.file.Files
47 import java.nio.file.Path
48 import java.nio.file.Paths
50 @Component("component-k8s-profile-upload")
51 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
52 open class K8sProfileUploadComponent(
53 private var bluePrintPropertiesService: BluePrintPropertiesService,
54 private val resourceResolutionService: ResourceResolutionService
57 AbstractComponentFunction() {
61 const val INPUT_K8S_PROFILE_NAME = "k8s-rb-profile-name"
62 const val INPUT_K8S_DEFINITION_NAME = "k8s-rb-definition-name"
63 const val INPUT_K8S_DEFINITION_VERSION = "k8s-rb-definition-version"
64 const val INPUT_K8S_PROFILE_NAMESPACE = "k8s-rb-profile-namespace"
65 const val INPUT_K8S_PROFILE_K8S_VERSION = "k8s-rb-profile-k8s-version"
66 const val INPUT_K8S_PROFILE_SOURCE = "k8s-rb-profile-source"
67 const val INPUT_RESOURCE_ASSIGNMENT_MAP = "resource-assignment-map"
68 const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names"
70 const val OUTPUT_STATUSES = "statuses"
71 const val OUTPUT_SKIPPED = "skipped"
72 const val OUTPUT_UPLOADED = "uploaded"
73 const val OUTPUT_ERROR = "error"
76 private val log = LoggerFactory.getLogger(K8sProfileUploadComponent::class.java)!!
78 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
79 log.info("Triggering K8s Profile Upload component logic.")
81 val inputParameterNames = arrayOf(
82 INPUT_K8S_PROFILE_NAME,
83 INPUT_K8S_DEFINITION_NAME,
84 INPUT_K8S_DEFINITION_VERSION,
85 INPUT_K8S_PROFILE_NAMESPACE,
86 INPUT_K8S_PROFILE_K8S_VERSION,
87 INPUT_K8S_PROFILE_SOURCE,
88 INPUT_ARTIFACT_PREFIX_NAMES
90 var outputPrefixStatuses = mutableMapOf<String, String>()
91 var inputParamsMap = mutableMapOf<String, JsonNode?>()
93 inputParameterNames.forEach {
94 inputParamsMap[it] = getOptionalOperationInput(it)?.returnNullIfMissing()
97 log.info("Getting the template prefixes")
98 val prefixList: ArrayList<String> = getTemplatePrefixList(inputParamsMap[INPUT_ARTIFACT_PREFIX_NAMES])
100 log.info("Iterating over prefixes in resource assignment map.")
101 for (prefix in prefixList) {
102 // Prefilling prefix sucess status
103 outputPrefixStatuses.put(prefix, OUTPUT_SKIPPED)
104 // Resource assignment map is organized by prefixes, in each iteraton we work only
105 // on one section of resource assignment map
106 val prefixNode: JsonNode = operationInputs[INPUT_RESOURCE_ASSIGNMENT_MAP]?.get(prefix) ?: continue
107 val assignmentMapPrefix = JacksonUtils.jsonNode(prefixNode.toPrettyString()) as ObjectNode
109 // We are copying the map because for each prefix it might be completed with a different data
110 var prefixInputParamsMap = inputParamsMap.toMutableMap()
111 prefixInputParamsMap.forEach { (inputParamName, value) ->
113 val mapValue = assignmentMapPrefix?.get(inputParamName)
114 log.debug("$inputParamName value was $value so we fetch $mapValue")
115 prefixInputParamsMap[inputParamName] = mapValue
119 // For clarity we pull out the required fields
120 val profileName: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAME]?.returnNullIfMissing()?.asText()
121 val definitionName: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_NAME]?.returnNullIfMissing()?.asText()
122 val definitionVersion: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_VERSION]?.returnNullIfMissing()?.asText()
124 val k8sProfileUploadConfiguration = K8sProfileUploadConfiguration(bluePrintPropertiesService)
126 // Creating API connector
127 var api = K8sPluginApi(
128 k8sProfileUploadConfiguration.getProperties().username,
129 k8sProfileUploadConfiguration.getProperties().password,
130 k8sProfileUploadConfiguration.getProperties().url,
135 if ((profileName == null) || (definitionName == null) || (definitionVersion == null)) {
136 log.warn("Prefix $prefix does not have required data for us to continue.")
137 } else if (!api.hasDefinition()) {
138 throw BluePrintProcessorException("K8s RB Definition ($definitionName/$definitionVersion) not found ")
139 } else if (profileName == "") {
140 log.warn("K8s rb profile name is empty! Either define profile name to use or choose default")
141 } else if (api.hasProfile(profileName)) {
142 log.info("Profile Already Existing - skipping upload")
144 log.info("Uploading K8s Profile..")
145 outputPrefixStatuses.put(prefix, OUTPUT_ERROR)
146 val profileNamespace: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAMESPACE]?.returnNullIfMissing()?.asText()
147 val profileK8sVersion: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_K8S_VERSION]?.returnNullIfMissing()?.asText()
148 var profileSource: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_SOURCE]?.returnNullIfMissing()?.asText()
149 if (profileNamespace == null)
150 throw BluePrintProcessorException("Profile $profileName namespace is missing")
151 if (profileSource == null) {
152 profileSource = profileName
153 log.info("Profile name used instead of profile source")
155 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
156 val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, profileSource)
157 if (artifact.type != BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE)
158 throw BluePrintProcessorException(
159 "Unexpected profile artifact type for profile source " +
160 "$profileSource. Expecting: $artifact.type"
162 var profile = K8sProfile()
163 profile.profileName = profileName
164 profile.rbName = definitionName
165 profile.rbVersion = definitionVersion
166 profile.namespace = profileNamespace
167 if (profileK8sVersion != null)
168 profile.kubernetesVersion = profileK8sVersion
169 val profileFilePath: Path = prepareProfileFile(profileName, profileSource, artifact.file)
170 api.createProfile(profile)
171 api.uploadProfileContent(profile, profileFilePath)
173 log.info("K8s Profile Upload Completed")
174 outputPrefixStatuses.put(prefix, OUTPUT_UPLOADED)
177 bluePrintRuntimeService.setNodeTemplateAttributeValue(
180 outputPrefixStatuses.asJsonNode()
184 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
185 bluePrintRuntimeService.getBluePrintError().addError(runtimeException.message!!)
188 private fun getTemplatePrefixList(node: JsonNode?): ArrayList<String> {
189 var result = ArrayList<String>()
192 val arrayNode = node.toList()
193 for (prefixNode in arrayNode)
194 result.add(prefixNode.asText())
197 result.add(node.asText())
203 private suspend fun prepareProfileFile(k8sRbProfileName: String, ks8ProfileSource: String, ks8ProfileLocation: String): Path {
204 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
205 val bluePrintBasePath: String = bluePrintContext.rootPath
206 val profileSourceFileFolderPath: Path = Paths.get(
207 bluePrintBasePath.plus(File.separator).plus(ks8ProfileLocation)
210 if (profileSourceFileFolderPath.toFile().exists() && !profileSourceFileFolderPath.toFile().isDirectory)
211 return profileSourceFileFolderPath
212 else if (profileSourceFileFolderPath.toFile().exists()) {
213 log.info("Profile building started from source $ks8ProfileSource")
214 val properties: MutableMap<String, Any> = mutableMapOf()
215 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = false
216 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] = ""
217 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] = ""
218 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] = ""
219 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] = 1
220 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY] = false
221 val resolutionResult: Pair<String, JsonNode> = resourceResolutionService.resolveResources(
222 bluePrintRuntimeService,
227 val tempMainPath: File = createTempDir("k8s-profile-", "")
228 val tempProfilePath: File = createTempDir("content-", "", tempMainPath)
231 val manifestFiles: ArrayList<File>? = readManifestFiles(
232 profileSourceFileFolderPath.toFile(),
235 if (manifestFiles != null) {
237 profileSourceFileFolderPath.toFile(), resolutionResult.second,
238 tempProfilePath, manifestFiles
241 throw BluePrintProcessorException("Manifest file is missing")
242 // Preparation of the final profile content
243 val finalProfileFilePath = Paths.get(
244 tempMainPath.toString().plus(File.separator).plus(
245 "$k8sRbProfileName.tar.gz"
248 if (!BluePrintArchiveUtils.compress(
249 tempProfilePath, finalProfileFilePath.toFile(),
253 throw BluePrintProcessorException("Profile compression has failed")
255 FileUtils.deleteDirectory(tempProfilePath)
257 return finalProfileFilePath
258 } catch (t: Throwable) {
259 FileUtils.deleteDirectory(tempMainPath)
263 throw BluePrintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder")
266 private fun readManifestFiles(profileSource: File, destinationFolder: File): ArrayList<File>? {
267 val directoryListing: Array<File>? = profileSource.listFiles()
268 var result: ArrayList<File>? = null
269 if (directoryListing != null) {
270 for (child in directoryListing) {
271 if (!child.isDirectory && child.name.toLowerCase() == "manifest.yaml") {
272 child.bufferedReader().use { inr ->
273 val manifestYaml = Yaml()
274 val manifestObject: Map<String, Any> = manifestYaml.load(inr)
275 val typeObject: MutableMap<String, Any>? = manifestObject["type"] as MutableMap<String, Any>?
276 if (typeObject != null) {
277 result = ArrayList<File>()
278 val valuesObject = typeObject["values"]
279 if (valuesObject != null) {
280 result!!.add(File(destinationFolder.toString().plus(File.separator).plus(valuesObject)))
281 result!!.add(File(destinationFolder.toString().plus(File.separator).plus(child.name)))
283 (typeObject["configresource"] as ArrayList<*>?)?.forEach { item ->
284 val fileInfo: Map<String, Any> = item as Map<String, Any>
285 val filePath = fileInfo["filepath"]
286 val chartPath = fileInfo["chartpath"]
287 if (filePath == null || chartPath == null)
288 log.error("One configresource in manifest was skipped because of the wrong format")
290 result!!.add(File(destinationFolder.toString().plus(File.separator).plus(filePath)))
302 private fun templateLocation(
305 destinationFolder: File,
306 manifestFiles: ArrayList<File>
308 val directoryListing: Array<File>? = location.listFiles()
309 if (directoryListing != null) {
310 for (child in directoryListing) {
311 var newDestinationFolder = destinationFolder.toPath()
312 if (child.isDirectory)
313 newDestinationFolder = Paths.get(destinationFolder.toString().plus(File.separator).plus(child.name))
315 templateLocation(child, params, newDestinationFolder.toFile(), manifestFiles)
317 } else if (!location.isDirectory) {
318 if (location.extension.toLowerCase() == "vtl") {
319 templateFile(location, params, destinationFolder, manifestFiles)
321 val finalFilePath = Paths.get(
322 destinationFolder.path.plus(File.separator)
325 if (isFileInTheManifestFiles(finalFilePath, manifestFiles)) {
326 if (!destinationFolder.exists())
327 Files.createDirectories(destinationFolder.toPath())
328 FileUtils.copyFile(location, finalFilePath)
334 private fun isFileInTheManifestFiles(file: File, manifestFiles: ArrayList<File>): Boolean {
335 manifestFiles.forEach { fileFromManifest ->
336 if (fileFromManifest.toString().toLowerCase() == file.toString().toLowerCase())
342 private fun templateFile(
345 destinationFolder: File,
346 manifestFiles: ArrayList<File>
348 val finalFile = File(
349 destinationFolder.path.plus(File.separator)
350 .plus(templatedFile.nameWithoutExtension)
352 if (!isFileInTheManifestFiles(finalFile, manifestFiles))
354 val fileContent = templatedFile.bufferedReader().readText()
355 val finalFileContent = BluePrintVelocityTemplateService.generateContent(
359 if (!destinationFolder.exists())
360 Files.createDirectories(destinationFolder.toPath())
361 finalFile.bufferedWriter().use { out -> out.write(finalFileContent) }