938affc827da2fb385e96bccd5ba05a3f0daeeb6
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / ResourceResolutionService.kt
1 /*
2  *  Copyright © 2017-2018 AT&T Intellectual Property.
3  *  Modifications Copyright © 2018-2019 IBM, Bell Canada
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.blueprintsprocessor.functions.resource.resolution
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import kotlinx.coroutines.async
22 import kotlinx.coroutines.awaitAll
23 import kotlinx.coroutines.coroutineScope
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolution
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionDBService
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.TemplateResolutionService
27 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
28 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
29 import org.onap.ccsdk.cds.controllerblueprints.core.*
30 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
31 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService
32 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
33 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
34 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
35 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.BulkResourceSequencingUtils
36 import org.slf4j.LoggerFactory
37 import org.springframework.context.ApplicationContext
38 import org.springframework.stereotype.Service
39
40 interface ResourceResolutionService {
41
42     fun registeredResourceSources(): List<String>
43
44     suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String,
45                                     resolutionKey: String): String
46
47     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
48                                  artifactNames: List<String>, properties: Map<String, Any>): MutableMap<String, JsonNode>
49
50     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
51                                  artifactPrefix: String, properties: Map<String, Any>): String
52
53     suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
54                                            resourceDefinitions: MutableMap<String, ResourceDefinition>,
55                                            resourceAssignments: MutableList<ResourceAssignment>,
56                                            artifactPrefix: String,
57                                            properties: Map<String, Any>)
58 }
59
60 @Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
61 open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext,
62                                          private var templateResolutionDBService: TemplateResolutionService,
63                                          private var blueprintTemplateService: BluePrintTemplateService,
64                                          private var resourceResolutionDBService: ResourceResolutionDBService) :
65     ResourceResolutionService {
66
67     private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
68
69     override fun registeredResourceSources(): List<String> {
70         return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java)
71             .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
72             .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
73     }
74
75     override suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>,
76                                              artifactTemplate: String,
77                                              resolutionKey: String): String {
78         return templateResolutionDBService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
79             bluePrintRuntimeService,
80             artifactTemplate,
81             resolutionKey)
82     }
83
84     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
85                                           artifactNames: List<String>,
86                                           properties: Map<String, Any>): MutableMap<String, JsonNode> {
87
88
89         val resourceAssignmentRuntimeService =
90             ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
91
92         val resolvedParams: MutableMap<String, JsonNode> = hashMapOf()
93         artifactNames.forEach { artifactName ->
94             val resolvedContent = resolveResources(resourceAssignmentRuntimeService, nodeTemplateName,
95                 artifactName, properties)
96
97             resolvedParams[artifactName] = resolvedContent.asJsonType()
98
99         }
100         return resolvedParams
101     }
102
103
104     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
105                                           artifactPrefix: String, properties: Map<String, Any>): String {
106
107         // Velocity Artifact Definition Name
108         val artifactTemplate = "$artifactPrefix-template"
109         // Resource Assignment Artifact Definition Name
110         val artifactMapping = "$artifactPrefix-mapping"
111
112         val resolvedContent: String
113         log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)")
114
115         val resourceAssignmentContent =
116             bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
117
118         val resourceAssignments: MutableList<ResourceAssignment> =
119             JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
120                     as? MutableList<ResourceAssignment>
121                 ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
122
123         if (isToStore(properties)) {
124             val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
125             if (existingResourceResolution.isNotEmpty()) {
126                 updateResourceAssignmentWithExisting(existingResourceResolution, resourceAssignments)
127             }
128         }
129
130         // Get the Resource Dictionary Name
131         val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
132             .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
133
134         // Resolve resources
135         resolveResourceAssignments(bluePrintRuntimeService,
136             resourceDefinitions,
137             resourceAssignments,
138             artifactPrefix,
139             properties)
140
141         val resolvedParamJsonContent =
142             ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
143
144         resolvedContent = blueprintTemplateService.generateContent(bluePrintRuntimeService, nodeTemplateName,
145             artifactTemplate, resolvedParamJsonContent)
146
147         if (isToStore(properties)) {
148             templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
149             log.info("Template resolution saved into database successfully : ($properties)")
150         }
151
152         return resolvedContent
153     }
154
155     /**
156      * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
157      * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
158      * request.
159      */
160     override suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
161                                                     resourceDefinitions: MutableMap<String, ResourceDefinition>,
162                                                     resourceAssignments: MutableList<ResourceAssignment>,
163                                                     artifactPrefix: String,
164                                                     properties: Map<String, Any>) {
165
166         val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
167         val resourceAssignmentRuntimeService = blueprintRuntimeService as ResourceAssignmentRuntimeService
168
169         coroutineScope {
170             bulkSequenced.forEach { batchResourceAssignments ->
171                 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
172                 val deferred = batchResourceAssignments
173                     .filter { it.name != "*" && it.name != "start" }
174                     .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
175                     .map { resourceAssignment ->
176                         async {
177                             val dictionaryName = resourceAssignment.dictionaryName
178                             val dictionarySource = resourceAssignment.dictionarySource
179
180                             val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
181
182                             val resourceAssignmentProcessor =
183                                 applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
184                                     ?: throw BluePrintProcessorException("failed to get resource processor ($processorName) " +
185                                             "for resource assignment(${resourceAssignment.name})")
186                             try {
187                                 // Set BluePrint Runtime Service
188                                 resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
189                                 // Set Resource Dictionaries
190                                 resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
191                                 // Invoke Apply Method
192                                 resourceAssignmentProcessor.applyNB(resourceAssignment)
193
194                                 if (isToStore(properties)) {
195                                     resourceResolutionDBService.write(properties,
196                                         blueprintRuntimeService,
197                                         artifactPrefix,
198                                         resourceAssignment)
199                                     log.info("Resource resolution saved into database successfully : ($resourceAssignment)")
200                                 }
201
202                                 // Set errors from RA
203                                 blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
204                             } catch (e: RuntimeException) {
205                                 log.error("Fail in processing ${resourceAssignment.name}", e)
206                                 throw BluePrintProcessorException(e)
207                             }
208                         }
209                     }
210                 log.debug("Resolving (${deferred.size})resources parallel.")
211                 deferred.awaitAll()
212             }
213         }
214
215     }
216
217     /**
218      * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
219      *  derive the default input processor.
220      */
221     private fun processorName(dictionaryName: String, dictionarySource: String,
222                               resourceDefinitions: MutableMap<String, ResourceDefinition>): String {
223         val processorName: String = when (dictionarySource) {
224             "input" -> {
225                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
226             }
227             "default" -> {
228                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
229             }
230             else -> {
231                 val resourceDefinition = resourceDefinitions[dictionaryName]
232                     ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
233
234                 val resourceSource = resourceDefinition.sources[dictionarySource]
235                     ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
236
237                 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
238             }
239         }
240         checkNotEmpty(processorName) {
241             "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
242         }
243
244         return processorName
245
246     }
247
248     // Check whether to store or not the resolution of resource and template
249     private fun isToStore(properties: Map<String, Any>): Boolean {
250         return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT)
251                 && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
252     }
253
254     // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
255     private suspend fun isNewResolution(bluePrintRuntimeService: BluePrintRuntimeService<*>,
256                                         properties: Map<String, Any>,
257                                         artifactPrefix: String): List<ResourceResolution> {
258         val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
259         val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
260         val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
261         val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
262
263         if (resolutionKey.isNotEmpty()) {
264             val existingResourceAssignments =
265                 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
266                     bluePrintRuntimeService,
267                     resolutionKey,
268                     occurrence,
269                     artifactPrefix)
270             if (existingResourceAssignments.isNotEmpty()) {
271                 log.info("Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
272                     resolutionKey)
273             }
274             return existingResourceAssignments
275         } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
276             val existingResourceAssignments =
277                 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
278                     bluePrintRuntimeService,
279                     resourceId,
280                     resourceType,
281
282                     occurrence,
283                     artifactPrefix)
284             if (existingResourceAssignments.isNotEmpty()) {
285                 log.info("Resolution with resourceId=($resourceId) and resourceType=($resourceType) already exist - will resolve " +
286                         "all resources not already resolved.")
287             }
288             return existingResourceAssignments
289         }
290         return emptyList()
291     }
292
293     // Update the resource assignment list with the status of the resource that have already been resolved
294     private fun updateResourceAssignmentWithExisting(resourceResolutionList: List<ResourceResolution>,
295                                                      resourceAssignmentList: MutableList<ResourceAssignment>) {
296         resourceResolutionList.forEach { resourceResolution ->
297             if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
298                 resourceAssignmentList.forEach {
299                     if (compareOne(resourceResolution, it)) {
300                         log.info("Resource ({}) already resolve: value=({})", it.name, resourceResolution.value)
301                         it.property!!.value = resourceResolution.value!!.asJsonPrimitive()
302                         it.status = resourceResolution.status
303                     }
304                 }
305             }
306         }
307     }
308
309     // Comparision between what we have in the database vs what we have to assign.
310     private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
311         return (resourceResolution.name == resourceAssignment.name
312                 && resourceResolution.dictionaryName == resourceAssignment.dictionaryName
313                 && resourceResolution.dictionarySource == resourceAssignment.dictionarySource
314                 && resourceResolution.dictionaryVersion == resourceAssignment.version)
315     }
316
317 }