f38bfad0d586a6090ae882c826f3d2f50849fdfd
[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.blueprintsprocessor.functions.resource.resolution.utils.ResourceDefinitionUtils.createResourceAssignments
30 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
31 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
32 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
33 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
34 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
35 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
36 import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants.LOG_REDACTED
37 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
38 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService
39 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
40 import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect
41 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
42 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
43 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.BulkResourceSequencingUtils
44 import org.slf4j.LoggerFactory
45 import org.springframework.context.ApplicationContext
46 import org.springframework.stereotype.Service
47 import java.util.UUID
48
49 data class ResourceResolutionResult(
50     val templateMap: MutableMap<String, String>,
51     val assignmentMap: MutableMap<String, JsonNode>
52 )
53
54 interface ResourceResolutionService {
55
56     fun registeredResourceSources(): List<String>
57
58     suspend fun resolveFromDatabase(
59         bluePrintRuntimeService: BluePrintRuntimeService<*>,
60         artifactTemplate: String,
61         resolutionKey: String
62     ): String
63
64     suspend fun resolveResources(
65         bluePrintRuntimeService: BluePrintRuntimeService<*>,
66         nodeTemplateName: String,
67         artifactNames: List<String>,
68         properties: Map<String, Any>
69     ): ResourceResolutionResult
70
71     suspend fun resolveResources(
72         bluePrintRuntimeService: BluePrintRuntimeService<*>,
73         nodeTemplateName: String,
74         artifactPrefix: String,
75         properties: Map<String, Any>
76     ): Pair<String, JsonNode>
77
78     /** Resolve resources for all the sources defined in a particular resource Definition[resolveDefinition]
79      * with other [resourceDefinitions] dependencies for the sources [sources]
80      * Used to get the same resource values from multiple sources. **/
81     suspend fun resolveResourceDefinition(
82         blueprintRuntimeService: BluePrintRuntimeService<*>,
83         resourceDefinitions: MutableMap<String, ResourceDefinition>,
84         resolveDefinition: String,
85         sources: List<String>
86     ):
87         MutableMap<String, JsonNode>
88
89     suspend fun resolveResourceAssignments(
90         blueprintRuntimeService: BluePrintRuntimeService<*>,
91         resourceDefinitions: MutableMap<String, ResourceDefinition>,
92         resourceAssignments: MutableList<ResourceAssignment>,
93         artifactPrefix: String,
94         properties: Map<String, Any>
95     )
96 }
97
98 @Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
99 open class ResourceResolutionServiceImpl(
100     private var applicationContext: ApplicationContext,
101     private var templateResolutionDBService: TemplateResolutionService,
102     private var blueprintTemplateService: BluePrintTemplateService,
103     private var resourceResolutionDBService: ResourceResolutionDBService
104 ) :
105     ResourceResolutionService {
106
107     private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
108
109     override fun registeredResourceSources(): List<String> {
110         return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java)
111             .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
112             .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
113     }
114
115     override suspend fun resolveFromDatabase(
116         bluePrintRuntimeService: BluePrintRuntimeService<*>,
117         artifactTemplate: String,
118         resolutionKey: String
119     ): String {
120         return templateResolutionDBService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
121             bluePrintRuntimeService,
122             artifactTemplate,
123             resolutionKey
124         )
125     }
126
127     override suspend fun resolveResources(
128         bluePrintRuntimeService: BluePrintRuntimeService<*>,
129         nodeTemplateName: String,
130         artifactNames: List<String>,
131         properties: Map<String, Any>
132     ): ResourceResolutionResult {
133
134         val resourceAssignmentRuntimeService =
135             ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
136
137         val templateMap: MutableMap<String, String> = hashMapOf()
138         val assignmentMap: MutableMap<String, JsonNode> = hashMapOf()
139         artifactNames.forEach { artifactName ->
140             val (resolvedStringContent, resolvedJsonContent) = resolveResources(
141                 resourceAssignmentRuntimeService, nodeTemplateName,
142                 artifactName, properties
143             )
144             templateMap[artifactName] = resolvedStringContent
145             assignmentMap[artifactName] = resolvedJsonContent
146         }
147         return ResourceResolutionResult(templateMap, assignmentMap)
148     }
149
150     override suspend fun resolveResources(
151         bluePrintRuntimeService: BluePrintRuntimeService<*>,
152         nodeTemplateName: String,
153         artifactPrefix: String,
154         properties: Map<String, Any>
155     ): Pair<String, JsonNode> {
156
157         // Template Artifact Definition Name
158         val artifactTemplate = "$artifactPrefix-template"
159         // Resource Assignment Artifact Definition Name
160         val artifactMapping = "$artifactPrefix-mapping"
161
162         log.info("Resolving resource with resource assignment artifact($artifactMapping)")
163
164         val resourceAssignmentContent =
165             bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
166
167         val resourceAssignments: MutableList<ResourceAssignment> =
168             JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
169                 as? MutableList<ResourceAssignment>
170                 ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
171
172         if (isToStore(properties)) {
173             val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
174             if (existingResourceResolution.isNotEmpty()) {
175                 updateResourceAssignmentWithExisting(
176                     bluePrintRuntimeService as ResourceAssignmentRuntimeService,
177                     existingResourceResolution, resourceAssignments
178                 )
179             }
180         }
181
182         // Get the Resource Dictionary Name
183         val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
184             .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
185
186         // Resolve resources
187         resolveResourceAssignments(
188             bluePrintRuntimeService,
189             resourceDefinitions,
190             resourceAssignments,
191             artifactPrefix,
192             properties
193         )
194
195         val resolutionSummary = properties.getOrDefault(
196             ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY,
197             false
198         ) as Boolean
199         val assignmentMap = resourceAssignments
200                 .associateBy({ it.name }, { it.property?.value })
201                 .asJsonNode()
202         val resolvedParamJsonContent =
203             ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
204         val artifactTemplateDefinition = bluePrintRuntimeService.bluePrintContext().checkNodeTemplateArtifact(nodeTemplateName, artifactTemplate)
205
206         val resolvedContent = when {
207             artifactTemplateDefinition != null -> {
208                 blueprintTemplateService.generateContent(
209                         bluePrintRuntimeService, nodeTemplateName,
210                         artifactTemplate, resolvedParamJsonContent, false,
211                         mutableMapOf(
212                                 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
213                                         properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()
214                         )
215                 )
216             }
217             resolutionSummary -> {
218                 ResourceAssignmentUtils.generateResolutionSummaryData(resourceAssignments, resourceDefinitions)
219             }
220             else -> {
221                 resolvedParamJsonContent
222             }
223         }
224
225         if (isToStore(properties)) {
226             templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
227             log.info("Template resolution saved into database successfully : ($properties)")
228         }
229
230         return Pair(resolvedContent, assignmentMap)
231     }
232
233     override suspend fun resolveResourceDefinition(
234         blueprintRuntimeService: BluePrintRuntimeService<*>,
235         resourceDefinitions: MutableMap<String, ResourceDefinition>,
236         resolveDefinition: String,
237         sources: List<String>
238     ): MutableMap<String, JsonNode> {
239
240         // Populate Dummy Resource Assignments
241         val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
242
243         resolveResourceAssignments(
244             blueprintRuntimeService, resourceDefinitions, resourceAssignments,
245             UUID.randomUUID().toString(), hashMapOf()
246         )
247
248         // Get the data from Resource Assignments
249         return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
250     }
251
252     /**
253      * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
254      * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
255      * request.
256      */
257     override suspend fun resolveResourceAssignments(
258         blueprintRuntimeService: BluePrintRuntimeService<*>,
259         resourceDefinitions: MutableMap<String, ResourceDefinition>,
260         resourceAssignments: MutableList<ResourceAssignment>,
261         artifactPrefix: String,
262         properties: Map<String, Any>
263     ) {
264
265         val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
266
267         // Check the BlueprintRuntime Service Should be ResourceAssignmentRuntimeService
268         val resourceAssignmentRuntimeService = if (blueprintRuntimeService !is ResourceAssignmentRuntimeService) {
269             ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, artifactPrefix)
270         } else {
271             blueprintRuntimeService
272         }
273
274         exposeOccurrencePropertyInResourceAssignments(resourceAssignmentRuntimeService, properties)
275
276         coroutineScope {
277             bulkSequenced.forEach { batchResourceAssignments ->
278                 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
279                 val deferred = batchResourceAssignments
280                     .filter { it.name != "*" && it.name != "start" }
281                     .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
282                     .map { resourceAssignment ->
283                         async {
284                             val dictionaryName = resourceAssignment.dictionaryName
285                             val dictionarySource = resourceAssignment.dictionarySource
286
287                             val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
288
289                             val resourceAssignmentProcessor =
290                                 applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
291                                     ?: throw BluePrintProcessorException(
292                                         "failed to get resource processor ($processorName) " +
293                                                 "for resource assignment(${resourceAssignment.name})"
294                                     )
295                             try {
296                                 // Set BluePrint Runtime Service
297                                 resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
298                                 // Set Resource Dictionaries
299                                 resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
300                                 // Invoke Apply Method
301                                 resourceAssignmentProcessor.applyNB(resourceAssignment)
302
303                                 if (isToStore(properties)) {
304                                     resourceResolutionDBService.write(
305                                         properties,
306                                         blueprintRuntimeService,
307                                         artifactPrefix,
308                                         resourceAssignment
309                                     )
310                                     log.info("Resource resolution saved into database successfully : (${resourceAssignment.name})")
311                                 }
312
313                                 // Set errors from RA
314                                 blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
315                             } catch (e: RuntimeException) {
316                                 log.error("Fail in processing ${resourceAssignment.name}", e)
317                                 throw BluePrintProcessorException(e)
318                             }
319                         }
320                     }
321                 log.debug("Resolving (${deferred.size})resources parallel.")
322                 deferred.awaitAll()
323             }
324         }
325     }
326
327     /**
328      * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
329      *  derive the default input processor.
330      */
331     private fun processorName(
332         dictionaryName: String,
333         dictionarySource: String,
334         resourceDefinitions: MutableMap<String, ResourceDefinition>
335     ): String {
336         val processorName: String = when (dictionarySource) {
337             "input" -> {
338                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
339             }
340             "default" -> {
341                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
342             }
343             else -> {
344                 val resourceDefinition = resourceDefinitions[dictionaryName]
345                     ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
346
347                 val resourceSource = resourceDefinition.sources[dictionarySource]
348                     ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
349
350                 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
351             }
352         }
353         checkNotEmpty(processorName) {
354             "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
355         }
356
357         return processorName
358     }
359
360     // Check whether to store or not the resolution of resource and template
361     private fun isToStore(properties: Map<String, Any>): Boolean {
362         return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) &&
363                 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
364     }
365
366     // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
367     private suspend fun isNewResolution(
368         bluePrintRuntimeService: BluePrintRuntimeService<*>,
369         properties: Map<String, Any>,
370         artifactPrefix: String
371     ): List<ResourceResolution> {
372         val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
373         val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
374         val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
375         val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
376
377         if (resolutionKey.isNotEmpty()) {
378             val existingResourceAssignments =
379                 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
380                     bluePrintRuntimeService,
381                     resolutionKey,
382                     occurrence,
383                     artifactPrefix
384                 )
385             if (existingResourceAssignments.isNotEmpty()) {
386                 log.info(
387                     "Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
388                     resolutionKey
389                 )
390             }
391             return existingResourceAssignments
392         } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
393             val existingResourceAssignments =
394                 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
395                     bluePrintRuntimeService,
396                     resourceId,
397                     resourceType,
398
399                     occurrence,
400                     artifactPrefix
401                 )
402             if (existingResourceAssignments.isNotEmpty()) {
403                 log.info(
404                     "Resolution with resourceId=($resourceId) and resourceType=($resourceType) already exist - will resolve " +
405                             "all resources not already resolved."
406                 )
407             }
408             return existingResourceAssignments
409         }
410         return emptyList()
411     }
412
413     // Update the resource assignment list with the status of the resource that have already been resolved
414     private fun updateResourceAssignmentWithExisting(
415         raRuntimeService: ResourceAssignmentRuntimeService,
416         resourceResolutionList: List<ResourceResolution>,
417         resourceAssignmentList: MutableList<ResourceAssignment>
418     ) {
419         resourceResolutionList.forEach { resourceResolution ->
420             if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
421                 resourceAssignmentList.forEach {
422                     if (compareOne(resourceResolution, it)) {
423                         log.info(
424                             "Resource ({}) already resolved: value=({})", it.name,
425                             if (hasLogProtect(it.property)) LOG_REDACTED else resourceResolution.value
426                         )
427
428                         // Make sure to recreate value as per the defined type.
429                         val value = resourceResolution.value!!.asJsonType(it.property!!.type)
430                         it.property!!.value = value
431                         it.status = resourceResolution.status
432                         ResourceAssignmentUtils.setResourceDataValue(it, raRuntimeService, value)
433                     }
434                 }
435             }
436         }
437     }
438
439     // Comparision between what we have in the database vs what we have to assign.
440     private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
441         return (resourceResolution.name == resourceAssignment.name &&
442                 resourceResolution.dictionaryName == resourceAssignment.dictionaryName &&
443                 resourceResolution.dictionarySource == resourceAssignment.dictionarySource &&
444                 resourceResolution.dictionaryVersion == resourceAssignment.version)
445     }
446
447     private fun exposeOccurrencePropertyInResourceAssignments(
448         raRuntimeService: ResourceAssignmentRuntimeService,
449         properties: Map<String, Any>
450     ) {
451         raRuntimeService.putResolutionStore(
452             ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE,
453             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()
454         )
455     }
456 }