a98c9e9d14cd64cfc9bfe0be65e077f18196a064
[ccsdk/cds.git] /
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.profile.upload
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.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
45 import java.io.File
46 import java.nio.file.Files
47 import java.nio.file.Path
48 import java.nio.file.Paths
49
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
55 ) :
56
57     AbstractComponentFunction() {
58
59     companion object {
60
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"
69
70         const val OUTPUT_STATUSES = "statuses"
71         const val OUTPUT_SKIPPED = "skipped"
72         const val OUTPUT_UPLOADED = "uploaded"
73         const val OUTPUT_ERROR = "error"
74     }
75
76     private val log = LoggerFactory.getLogger(K8sProfileUploadComponent::class.java)!!
77
78     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
79         log.info("Triggering K8s Profile Upload component logic.")
80
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
89         )
90         var outputPrefixStatuses = mutableMapOf<String, String>()
91         var inputParamsMap = mutableMapOf<String, JsonNode?>()
92
93         inputParameterNames.forEach {
94             inputParamsMap[it] = getOptionalOperationInput(it)?.returnNullIfMissing()
95         }
96
97         log.info("Getting the template prefixes")
98         val prefixList: ArrayList<String> = getTemplatePrefixList(inputParamsMap[INPUT_ARTIFACT_PREFIX_NAMES])
99
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
108
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) ->
112                 if (value == null) {
113                     val mapValue = assignmentMapPrefix?.get(inputParamName)
114                     log.debug("$inputParamName value was $value so we fetch $mapValue")
115                     prefixInputParamsMap[inputParamName] = mapValue
116                 }
117             }
118
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()
123
124             val k8sProfileUploadConfiguration = K8sProfileUploadConfiguration(bluePrintPropertiesService)
125
126             // Creating API connector
127             var api = K8sPluginApi(
128                 k8sProfileUploadConfiguration.getProperties().username,
129                 k8sProfileUploadConfiguration.getProperties().password,
130                 k8sProfileUploadConfiguration.getProperties().url,
131                 definitionName,
132                 definitionVersion
133             )
134
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")
143             } else {
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")
154                 }
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"
161                     )
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)
172
173                 log.info("K8s Profile Upload Completed")
174                 outputPrefixStatuses.put(prefix, OUTPUT_UPLOADED)
175             }
176         }
177         bluePrintRuntimeService.setNodeTemplateAttributeValue(
178             nodeTemplateName,
179             OUTPUT_STATUSES,
180             outputPrefixStatuses.asJsonNode()
181         )
182     }
183
184     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
185         bluePrintRuntimeService.getBluePrintError().addError(runtimeException.message!!)
186     }
187
188     private fun getTemplatePrefixList(node: JsonNode?): ArrayList<String> {
189         var result = ArrayList<String>()
190         when (node) {
191             is ArrayNode -> {
192                 val arrayNode = node.toList()
193                 for (prefixNode in arrayNode)
194                     result.add(prefixNode.asText())
195             }
196             is ObjectNode -> {
197                 result.add(node.asText())
198             }
199         }
200         return result
201     }
202
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)
208         )
209
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,
223                 nodeTemplateName,
224                 ks8ProfileSource,
225                 properties
226             )
227             val tempMainPath: File = createTempDir("k8s-profile-", "")
228             val tempProfilePath: File = createTempDir("content-", "", tempMainPath)
229
230             try {
231                 val manifestFiles: ArrayList<File>? = readManifestFiles(
232                     profileSourceFileFolderPath.toFile(),
233                     tempProfilePath
234                 )
235                 if (manifestFiles != null) {
236                     templateLocation(
237                         profileSourceFileFolderPath.toFile(), resolutionResult.second,
238                         tempProfilePath, manifestFiles
239                     )
240                 } else
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"
246                     )
247                 )
248                 if (!BluePrintArchiveUtils.compress(
249                         tempProfilePath, finalProfileFilePath.toFile(),
250                         ArchiveType.TarGz
251                     )
252                 ) {
253                     throw BluePrintProcessorException("Profile compression has failed")
254                 }
255                 FileUtils.deleteDirectory(tempProfilePath)
256
257                 return finalProfileFilePath
258             } catch (t: Throwable) {
259                 FileUtils.deleteDirectory(tempMainPath)
260                 throw t
261             }
262         } else
263             throw BluePrintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder")
264     }
265
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)))
282                             }
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")
289                                 else {
290                                     result!!.add(File(destinationFolder.toString().plus(File.separator).plus(filePath)))
291                                 }
292                             }
293                         }
294                     }
295                     break
296                 }
297             }
298         }
299         return result
300     }
301
302     private fun templateLocation(
303         location: File,
304         params: JsonNode,
305         destinationFolder: File,
306         manifestFiles: ArrayList<File>
307     ) {
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))
314
315                 templateLocation(child, params, newDestinationFolder.toFile(), manifestFiles)
316             }
317         } else if (!location.isDirectory) {
318             if (location.extension.toLowerCase() == "vtl") {
319                 templateFile(location, params, destinationFolder, manifestFiles)
320             } else {
321                 val finalFilePath = Paths.get(
322                     destinationFolder.path.plus(File.separator)
323                         .plus(location.name)
324                 ).toFile()
325                 if (isFileInTheManifestFiles(finalFilePath, manifestFiles)) {
326                     if (!destinationFolder.exists())
327                         Files.createDirectories(destinationFolder.toPath())
328                     FileUtils.copyFile(location, finalFilePath)
329                 }
330             }
331         }
332     }
333
334     private fun isFileInTheManifestFiles(file: File, manifestFiles: ArrayList<File>): Boolean {
335         manifestFiles.forEach { fileFromManifest ->
336             if (fileFromManifest.toString().toLowerCase() == file.toString().toLowerCase())
337                 return true
338         }
339         return false
340     }
341
342     private fun templateFile(
343         templatedFile: File,
344         params: JsonNode,
345         destinationFolder: File,
346         manifestFiles: ArrayList<File>
347     ) {
348         val finalFile = File(
349             destinationFolder.path.plus(File.separator)
350                 .plus(templatedFile.nameWithoutExtension)
351         )
352         if (!isFileInTheManifestFiles(finalFile, manifestFiles))
353             return
354         val fileContent = templatedFile.bufferedReader().readText()
355         val finalFileContent = BluePrintVelocityTemplateService.generateContent(
356             fileContent,
357             params, true
358         )
359         if (!destinationFolder.exists())
360             Files.createDirectories(destinationFolder.toPath())
361         finalFile.bufferedWriter().use { out -> out.write(finalFileContent) }
362     }
363 }