Revert "Renaming Files having BluePrint to have Blueprint"
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / k8s-connection-plugin / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / k8s / definition / profile / K8sProfileUploadComponent.kt
1 /*
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.
6  *
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
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  */
19
20 package org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.profile
21
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.k8s.K8sConnectionPluginConfiguration
29 import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi
30 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
31 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
32 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService
33 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
34 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
35 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
36 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
37 import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
38 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
39 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
40 import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType
41 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
42 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
43 import org.slf4j.LoggerFactory
44 import org.springframework.beans.factory.config.ConfigurableBeanFactory
45 import org.springframework.context.annotation.Scope
46 import org.springframework.stereotype.Component
47 import org.yaml.snakeyaml.Yaml
48 import java.io.File
49 import java.nio.file.Files
50 import java.nio.file.Path
51 import java.nio.file.Paths
52
53 @Component("component-k8s-profile-upload")
54 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
55 open class K8sProfileUploadComponent(
56     private var bluePrintPropertiesService: BluePrintPropertiesService,
57     private val resourceResolutionService: ResourceResolutionService
58 ) :
59
60     AbstractComponentFunction() {
61
62     companion object {
63
64         const val INPUT_K8S_PROFILE_NAME = "k8s-rb-profile-name"
65         const val INPUT_K8S_DEFINITION_NAME = "k8s-rb-definition-name"
66         const val INPUT_K8S_DEFINITION_VERSION = "k8s-rb-definition-version"
67         const val INPUT_K8S_PROFILE_NAMESPACE = "k8s-rb-profile-namespace"
68         const val INPUT_K8S_PROFILE_K8S_VERSION = "k8s-rb-profile-k8s-version"
69         const val INPUT_K8S_PROFILE_SOURCE = "k8s-rb-profile-source"
70         const val INPUT_RESOURCE_ASSIGNMENT_MAP = "resource-assignment-map"
71         const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names"
72
73         const val OUTPUT_STATUSES = "statuses"
74         const val OUTPUT_SKIPPED = "skipped"
75         const val OUTPUT_UPLOADED = "uploaded"
76         const val OUTPUT_ERROR = "error"
77     }
78
79     private val log = LoggerFactory.getLogger(K8sProfileUploadComponent::class.java)!!
80
81     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
82         log.info("Triggering K8s Profile Upload component logic.")
83
84         val inputParameterNames = arrayOf(
85             INPUT_K8S_PROFILE_NAME,
86             INPUT_K8S_DEFINITION_NAME,
87             INPUT_K8S_DEFINITION_VERSION,
88             INPUT_K8S_PROFILE_NAMESPACE,
89             INPUT_K8S_PROFILE_K8S_VERSION,
90             INPUT_K8S_PROFILE_SOURCE,
91             INPUT_ARTIFACT_PREFIX_NAMES
92         )
93         var outputPrefixStatuses = mutableMapOf<String, String>()
94         var inputParamsMap = mutableMapOf<String, JsonNode?>()
95
96         inputParameterNames.forEach {
97             inputParamsMap[it] = getOptionalOperationInput(it)?.returnNullIfMissing()
98         }
99
100         log.info("Getting the template prefixes")
101         val prefixList: ArrayList<String> = getTemplatePrefixList(inputParamsMap[INPUT_ARTIFACT_PREFIX_NAMES])
102
103         log.info("Iterating over prefixes in resource assignment map.")
104         for (prefix in prefixList) {
105             // Prefilling prefix sucess status
106             outputPrefixStatuses.put(prefix, OUTPUT_SKIPPED)
107             // Resource assignment map is organized by prefixes, in each iteraton we work only
108             // on one section of resource assignment map
109             val prefixNode: JsonNode = operationInputs[INPUT_RESOURCE_ASSIGNMENT_MAP]?.get(prefix) ?: continue
110             val assignmentMapPrefix = JacksonUtils.jsonNode(prefixNode.toPrettyString()) as ObjectNode
111
112             // We are copying the map because for each prefix it might be completed with a different data
113             var prefixInputParamsMap = inputParamsMap.toMutableMap()
114             prefixInputParamsMap.forEach { (inputParamName, value) ->
115                 if (value == null) {
116                     val mapValue = assignmentMapPrefix?.get(inputParamName)
117                     log.debug("$inputParamName value was $value so we fetch $mapValue")
118                     prefixInputParamsMap[inputParamName] = mapValue
119                 }
120             }
121
122             // For clarity we pull out the required fields
123             val profileName: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAME]?.returnNullIfMissing()?.asText()
124             val definitionName: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_NAME]?.returnNullIfMissing()?.asText()
125             val definitionVersion: String? = prefixInputParamsMap[INPUT_K8S_DEFINITION_VERSION]?.returnNullIfMissing()?.asText()
126
127             val k8sProfileUploadConfiguration = K8sConnectionPluginConfiguration(bluePrintPropertiesService)
128
129             // Creating API connector
130             var api = K8sPluginDefinitionApi(k8sProfileUploadConfiguration)
131
132             if ((profileName == null) || (definitionName == null) || (definitionVersion == null)) {
133                 log.warn("Prefix $prefix does not have required data for us to continue.")
134             } else if (!api.hasDefinition(definitionName, definitionVersion)) {
135                 throw BluePrintProcessorException("K8s RB Definition ($definitionName/$definitionVersion) not found ")
136             } else if (profileName == "") {
137                 log.warn("K8s rb profile name is empty! Either define profile name to use or choose default")
138             } else if (api.hasProfile(definitionName, definitionVersion, profileName)) {
139                 log.info("Profile Already Existing - skipping upload")
140             } else {
141                 log.info("Uploading K8s Profile..")
142                 outputPrefixStatuses.put(prefix, OUTPUT_ERROR)
143                 val profileNamespace: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_NAMESPACE]?.returnNullIfMissing()?.asText()
144                 val profileK8sVersion: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_K8S_VERSION]?.returnNullIfMissing()?.asText()
145                 var profileSource: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_SOURCE]?.returnNullIfMissing()?.asText()
146                 if (profileNamespace == null)
147                     throw BluePrintProcessorException("Profile $profileName namespace is missing")
148                 if (profileSource == null) {
149                     profileSource = profileName
150                     log.info("Profile name used instead of profile source")
151                 }
152                 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
153                 val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, profileSource)
154                 if (artifact.type != BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE)
155                     throw BluePrintProcessorException(
156                         "Unexpected profile artifact type for profile source " +
157                             "$profileSource. Expecting: $artifact.type"
158                     )
159                 var profile = K8sProfile()
160                 profile.profileName = profileName
161                 profile.rbName = definitionName
162                 profile.rbVersion = definitionVersion
163                 profile.namespace = profileNamespace
164                 if (profileK8sVersion != null)
165                     profile.kubernetesVersion = profileK8sVersion
166                 val profileFilePath: Path = prepareProfileFile(profileName, profileSource, artifact.file)
167                 api.createProfile(definitionName, definitionVersion, profile)
168                 api.uploadProfileContent(definitionName, definitionVersion, profile, profileFilePath)
169
170                 log.info("K8s Profile Upload Completed")
171                 outputPrefixStatuses.put(prefix, OUTPUT_UPLOADED)
172             }
173         }
174         bluePrintRuntimeService.setNodeTemplateAttributeValue(
175             nodeTemplateName,
176             OUTPUT_STATUSES,
177             outputPrefixStatuses.asJsonNode()
178         )
179     }
180
181     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
182         addError(runtimeException.message!!)
183     }
184
185     private fun getTemplatePrefixList(node: JsonNode?): ArrayList<String> {
186         var result = ArrayList<String>()
187         when (node) {
188             is ArrayNode -> {
189                 val arrayNode = node.toList()
190                 for (prefixNode in arrayNode)
191                     result.add(prefixNode.asText())
192             }
193             is ObjectNode -> {
194                 result.add(node.asText())
195             }
196         }
197         return result
198     }
199
200     private suspend fun prepareProfileFile(k8sRbProfileName: String, ks8ProfileSource: String, ks8ProfileLocation: String): Path {
201         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
202         val bluePrintBasePath: String = bluePrintContext.rootPath
203         val profileSourceFileFolderPath: Path = Paths.get(
204             bluePrintBasePath.plus(File.separator).plus(ks8ProfileLocation)
205         )
206
207         if (profileSourceFileFolderPath.toFile().exists() && !profileSourceFileFolderPath.toFile().isDirectory)
208             return profileSourceFileFolderPath
209         else if (profileSourceFileFolderPath.toFile().exists()) {
210             log.info("Profile building started from source $ks8ProfileSource")
211             val properties: MutableMap<String, Any> = mutableMapOf()
212             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = false
213             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] = ""
214             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] = ""
215             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] = ""
216             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] = 1
217             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY] = false
218             val resolutionResult: Pair<String, MutableList<ResourceAssignment>> = resourceResolutionService.resolveResources(
219                 bluePrintRuntimeService,
220                 nodeTemplateName,
221                 ks8ProfileSource,
222                 properties
223             )
224             val tempMainPath: File = createTempDir("k8s-profile-", "")
225             val tempProfilePath: File = createTempDir("content-", "", tempMainPath)
226
227             val resolvedJsonContent = resolutionResult.second
228                 .associateBy({ it.name }, { it.property?.value })
229                 .asJsonNode()
230
231             try {
232                 val manifestFiles: ArrayList<File>? = readManifestFiles(
233                     profileSourceFileFolderPath.toFile(),
234                     tempProfilePath
235                 )
236                 if (manifestFiles != null) {
237                     templateLocation(
238                         profileSourceFileFolderPath.toFile(), resolvedJsonContent,
239                         tempProfilePath, manifestFiles
240                     )
241                 } else
242                     throw BluePrintProcessorException("Manifest file is missing")
243                 // Preparation of the final profile content
244                 val finalProfileFilePath = Paths.get(
245                     tempMainPath.toString().plus(File.separator).plus(
246                         "$k8sRbProfileName.tar.gz"
247                     )
248                 )
249                 if (!BluePrintArchiveUtils.compress(
250                         tempProfilePath, finalProfileFilePath.toFile(),
251                         ArchiveType.TarGz
252                     )
253                 ) {
254                     throw BluePrintProcessorException("Profile compression has failed")
255                 }
256                 FileUtils.deleteDirectory(tempProfilePath)
257
258                 return finalProfileFilePath
259             } catch (t: Throwable) {
260                 FileUtils.deleteDirectory(tempMainPath)
261                 throw t
262             }
263         } else
264             throw BluePrintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder")
265     }
266
267     private fun readManifestFiles(profileSource: File, destinationFolder: File): ArrayList<File>? {
268         val directoryListing: Array<File>? = profileSource.listFiles()
269         var result: ArrayList<File>? = null
270         if (directoryListing != null) {
271             for (child in directoryListing) {
272                 if (!child.isDirectory && child.name.toLowerCase() == "manifest.yaml") {
273                     child.bufferedReader().use { inr ->
274                         val manifestYaml = Yaml()
275                         val manifestObject: Map<String, Any> = manifestYaml.load(inr)
276                         val typeObject: MutableMap<String, Any>? = manifestObject["type"] as MutableMap<String, Any>?
277                         if (typeObject != null) {
278                             result = ArrayList<File>()
279                             val valuesObject = typeObject["values"]
280                             if (valuesObject != null) {
281                                 result!!.add(File(destinationFolder.toString().plus(File.separator).plus(valuesObject)))
282                                 result!!.add(File(destinationFolder.toString().plus(File.separator).plus(child.name)))
283                             }
284                             (typeObject["configresource"] as ArrayList<*>?)?.forEach { item ->
285                                 val fileInfo: Map<String, Any> = item as Map<String, Any>
286                                 val filePath = fileInfo["filepath"]
287                                 val chartPath = fileInfo["chartpath"]
288                                 if (filePath == null || chartPath == null)
289                                     log.error("One configresource in manifest was skipped because of the wrong format")
290                                 else {
291                                     result!!.add(File(destinationFolder.toString().plus(File.separator).plus(filePath)))
292                                 }
293                             }
294                         }
295                     }
296                     break
297                 }
298             }
299         }
300         return result
301     }
302
303     private fun templateLocation(
304         location: File,
305         params: JsonNode,
306         destinationFolder: File,
307         manifestFiles: ArrayList<File>
308     ) {
309         val directoryListing: Array<File>? = location.listFiles()
310         if (directoryListing != null) {
311             for (child in directoryListing) {
312                 var newDestinationFolder = destinationFolder.toPath()
313                 if (child.isDirectory)
314                     newDestinationFolder = Paths.get(destinationFolder.toString().plus(File.separator).plus(child.name))
315
316                 templateLocation(child, params, newDestinationFolder.toFile(), manifestFiles)
317             }
318         } else if (!location.isDirectory) {
319             if (location.extension.toLowerCase() == "vtl") {
320                 templateFile(location, params, destinationFolder, manifestFiles)
321             } else {
322                 val finalFilePath = Paths.get(
323                     destinationFolder.path.plus(File.separator)
324                         .plus(location.name)
325                 ).toFile()
326                 if (isFileInTheManifestFiles(finalFilePath, manifestFiles)) {
327                     if (!destinationFolder.exists())
328                         Files.createDirectories(destinationFolder.toPath())
329                     FileUtils.copyFile(location, finalFilePath)
330                 }
331             }
332         }
333     }
334
335     private fun isFileInTheManifestFiles(file: File, manifestFiles: ArrayList<File>): Boolean {
336         manifestFiles.forEach { fileFromManifest ->
337             if (fileFromManifest.toString().toLowerCase() == file.toString().toLowerCase())
338                 return true
339         }
340         return false
341     }
342
343     private fun templateFile(
344         templatedFile: File,
345         params: JsonNode,
346         destinationFolder: File,
347         manifestFiles: ArrayList<File>
348     ) {
349         val finalFile = File(
350             destinationFolder.path.plus(File.separator)
351                 .plus(templatedFile.nameWithoutExtension)
352         )
353         if (!isFileInTheManifestFiles(finalFile, manifestFiles))
354             return
355         val fileContent = templatedFile.bufferedReader().readText()
356         val finalFileContent = BluePrintVelocityTemplateService.generateContent(
357             fileContent,
358             params.toString(), true
359         )
360         if (!destinationFolder.exists())
361             Files.createDirectories(destinationFolder.toPath())
362         finalFile.bufferedWriter().use { out -> out.write(finalFileContent) }
363     }
364 }