a8765eee1e0cd928280054a983760cbb1525363c
[ccsdk/cds.git] /
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2019 IBM.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.controllerblueprints.service.enhancer
19
20 import org.slf4j.LoggerFactory
21 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
22 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
23 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
24 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
25 import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
26 import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
27 import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
28 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
29 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
30 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer
31 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
32 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
33 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
34 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
35 import org.springframework.beans.factory.config.ConfigurableBeanFactory
36 import org.springframework.context.annotation.Scope
37 import org.springframework.stereotype.Service
38
39 @Service
40 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
41 open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
42                                          private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
43                                          private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService)
44     : BluePrintWorkflowEnhancer {
45     private val log= LoggerFactory.getLogger(BluePrintWorkflowEnhancerImpl::class.toString())
46
47     companion object {
48         const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource"
49         const val PROPERTY_DEPENDENCY_NODE_TEMPLATES = "dependency-node-templates"
50     }
51
52     lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
53     lateinit var bluePrintContext: BluePrintContext
54
55     private val workflowDataTypes: MutableMap<String, DataType> = hashMapOf()
56
57     override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) {
58         log.info("##### Enhancing Workflow($name)")
59         this.bluePrintRuntimeService = bluePrintRuntimeService
60         this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
61
62         val dynamicPropertyName = "$name-properties"
63         if (workflow.inputs == null) {
64             workflow.inputs = hashMapOf()
65         }
66         // Clean Dynamic Property Field, If present
67         workflow.inputs?.remove(dynamicPropertyName)
68
69         // Enrich Workflow Inputs
70         enhanceWorkflowInputs(name, workflow)
71
72         // Enrich Workflow Outputs
73         enhanceWorkflowOutputs(name, workflow)
74
75         // Enrich Only for Resource Assignment and Dynamic Input Properties if any
76         enhanceStepTargets(name, workflow)
77
78
79     }
80
81     open fun enhanceWorkflowInputs(name: String, workflow: Workflow) {
82
83         workflow.inputs?.let { inputs ->
84             bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs)
85         }
86     }
87
88     open fun enhanceWorkflowOutputs(name: String, workflow: Workflow) {
89         workflow.outputs?.let { outputs ->
90             bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, outputs)
91         }
92     }
93
94     private fun enhanceStepTargets(name: String, workflow: Workflow) {
95
96         // Get the first Step Target NodeTemplate name( It may be Component or DG Node Template)
97         val firstNodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(name)
98
99         val derivedFrom = bluePrintContext.nodeTemplateNodeType(firstNodeTemplateName).derivedFrom
100
101         when {
102             derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> {
103                 enhanceStepTargets(name, workflow, firstNodeTemplateName, false)
104             }
105             derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> {
106                 enhanceStepTargets(name, workflow, firstNodeTemplateName, true)
107             }
108             else -> {
109                 throw BluePrintProcessorException("couldn't execute workflow($name) step mapped " +
110                         "to node template($firstNodeTemplateName) derived from($derivedFrom)")
111             }
112         }
113
114     }
115
116     private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) {
117
118         val dependencyNodeTemplates: List<String>
119         if (isDG) {
120             val dgNodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName)
121
122             // Get the Dependent Component Node Template Names
123             val dependencyNodeTemplateNodes = dgNodeTemplate.properties?.get(PROPERTY_DEPENDENCY_NODE_TEMPLATES)
124                 ?: throw BluePrintException("couldn't get property($PROPERTY_DEPENDENCY_NODE_TEMPLATES) ")
125
126             dependencyNodeTemplates =
127                 JacksonUtils.getListFromJsonNode(dependencyNodeTemplateNodes, String::class.java)
128         } else {
129             dependencyNodeTemplates = listOf(nodeTemplateName)
130         }
131
132         log.info("workflow($name) dependent component NodeTemplates($dependencyNodeTemplates)")
133
134         // Check and Get Resource Assignment File
135         val resourceAssignmentArtifacts = dependencyNodeTemplates?.mapNotNull { componentNodeTemplateName ->
136             log.info("identified workflow($name) targets($componentNodeTemplateName)")
137
138             val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName)
139                     .artifacts?.filter {
140                 it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE
141             }?.map {
142                 log.info("resource assignment artifacts(${it.key}) for NodeType(${componentNodeTemplateName})")
143                 it.value.file
144             }
145             resourceAssignmentArtifacts
146         }?.flatten()
147
148         log.info("workflow($name) resource assignment files($resourceAssignmentArtifacts")
149
150         if (resourceAssignmentArtifacts != null && resourceAssignmentArtifacts.isNotEmpty()) {
151
152             // Add Workflow Dynamic Property
153             addWorkFlowDynamicPropertyDefinitions(name, workflow)
154
155             resourceAssignmentArtifacts.forEach { fileName ->
156                 // Enhance Resource Assignment File
157                 val resourceAssignmentProperties = enhanceResourceAssignmentFile(fileName!!)
158                 // Add Workflow Dynamic DataType
159                 addWorkFlowDynamicDataType(name, resourceAssignmentProperties)
160             }
161         }
162     }
163
164     // Enhancement for Dynamic Properties, Resource Assignment Properties, Resource Sources
165     private fun enhanceResourceAssignmentFile(fileName: String): MutableMap<String, PropertyDefinition> {
166
167         val filePath = "${bluePrintContext.rootPath}/$fileName"
168
169         log.info("enriching artifacts file(${filePath}")
170
171         val resourceAssignmentProperties: MutableMap<String, PropertyDefinition> = hashMapOf()
172
173         val resourceAssignments: MutableList<ResourceAssignment> = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java)
174                 as? MutableList<ResourceAssignment>
175                 ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
176
177         val alreadyEnhancedKey = "enhanced-$fileName"
178         val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey)
179
180         log.info("enhancing workflow resource mapping file($fileName) already enhanced($alreadyEnhanced)")
181
182         if (!alreadyEnhanced) {
183             // Call Resource Assignment Enhancer
184             resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments)
185             bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive())
186         }
187
188         resourceAssignments.forEach { resourceAssignment ->
189             resourceAssignmentProperties[resourceAssignment.name] = resourceAssignment.property!!
190         }
191         return resourceAssignmentProperties
192     }
193
194     private fun addWorkFlowDynamicPropertyDefinitions(name: String, workflow: Workflow) {
195         val dynamicPropertyName = "$name-properties"
196         val propertyDefinition = PropertyDefinition()
197         propertyDefinition.description = "Dynamic PropertyDefinition for workflow($name)."
198         propertyDefinition.type = "dt-$dynamicPropertyName"
199         propertyDefinition.required = true
200         // Add to Workflow Inputs
201         workflow.inputs?.put(dynamicPropertyName, propertyDefinition)
202     }
203
204     private fun addWorkFlowDynamicDataType(workflowName: String, mappingProperties: MutableMap<String, PropertyDefinition>) {
205
206         val dataTypeName = "dt-$workflowName-properties"
207
208         var dynamicDataType: DataType? = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName)
209
210         if (dynamicDataType == null) {
211             log.info("dataType not present for the recipe({})", dataTypeName)
212             dynamicDataType = DataType()
213             dynamicDataType.version = "1.0.0"
214             dynamicDataType.description = "Dynamic DataType definition for workflow($workflowName)."
215             dynamicDataType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC
216
217             val dataTypeProperties: MutableMap<String, PropertyDefinition> = hashMapOf()
218             dynamicDataType.properties = dataTypeProperties
219
220             // Overwrite WorkFlow DataType
221             bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType)
222
223         } else {
224             log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).")
225         }
226         // Merge all the Recipe Properties
227         mappingProperties.forEach { propertyName, propertyDefinition ->
228             dynamicDataType.properties?.put(propertyName, propertyDefinition)
229         }
230     }
231 }