1f17b2c6eb4df87ee1b8e2eefd64e0fe01acb85e
[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.k8s.K8sPluginApi
29 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
30 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
31 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService
32 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
33 import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants
34 import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException
35 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
36 import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
37 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
38 import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService
39 import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType
40 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils
41 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
42 import org.slf4j.LoggerFactory
43 import org.springframework.beans.factory.config.ConfigurableBeanFactory
44 import org.springframework.context.annotation.Scope
45 import org.springframework.stereotype.Component
46 import org.yaml.snakeyaml.Yaml
47 import java.io.File
48 import java.nio.file.Files
49 import java.nio.file.Path
50 import java.nio.file.Paths
51
52 @Component("component-k8s-profile-upload")
53 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
54 open class K8sProfileUploadComponent(
55     private var bluePrintPropertiesService: BlueprintPropertiesService,
56     private val resourceResolutionService: ResourceResolutionService
57 ) :
58
59     AbstractComponentFunction() {
60
61     companion object {
62
63         const val INPUT_K8S_PROFILE_NAME = "k8s-rb-profile-name"
64         const val INPUT_K8S_DEFINITION_NAME = "k8s-rb-definition-name"
65         const val INPUT_K8S_DEFINITION_VERSION = "k8s-rb-definition-version"
66         const val INPUT_K8S_PROFILE_NAMESPACE = "k8s-rb-profile-namespace"
67         const val INPUT_K8S_PROFILE_SOURCE = "k8s-rb-profile-source"
68         const val INPUT_RESOURCE_ASSIGNMENT_MAP = "resource-assignment-map"
69         const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names"
70
71         const val OUTPUT_STATUSES = "statuses"
72         const val OUTPUT_SKIPPED = "skipped"
73         const val OUTPUT_UPLOADED = "uploaded"
74         const val OUTPUT_ERROR = "error"
75     }
76
77     private val log = LoggerFactory.getLogger(K8sProfileUploadComponent::class.java)!!
78
79     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
80         log.info("Triggering K8s Profile Upload component logic.")
81
82         val inputParameterNames = arrayOf(
83             INPUT_K8S_PROFILE_NAME,
84             INPUT_K8S_DEFINITION_NAME,
85             INPUT_K8S_DEFINITION_VERSION,
86             INPUT_K8S_PROFILE_NAMESPACE,
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                 log.warn("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                 var profileSource: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_SOURCE]?.returnNullIfMissing()?.asText()
148                 if (profileNamespace == null)
149                     throw BlueprintProcessorException("Profile $profileName namespace is missing")
150                 if (profileSource == null) {
151                     profileSource = profileName
152                     log.info("Profile name used instead of profile source")
153                 }
154                 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
155                 val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, profileSource)
156                 if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE)
157                     throw BlueprintProcessorException(
158                         "Unexpected profile artifact type for profile source " +
159                             "$profileSource. Expecting: $artifact.type"
160                     )
161                 var profile = K8sProfile()
162                 profile.profileName = profileName
163                 profile.rbName = definitionName
164                 profile.rbVersion = definitionVersion
165                 profile.namespace = profileNamespace
166                 val profileFilePath: Path = prepareProfileFile(profileName, profileSource, artifact.file)
167                 api.createProfile(profile)
168                 api.uploadProfileContent(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         bluePrintRuntimeService.getBlueprintError().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, true
359         )
360         if (!destinationFolder.exists())
361             Files.createDirectories(destinationFolder.toPath())
362         finalFile.bufferedWriter().use { out -> out.write(finalFileContent) }
363     }
364 }