Fix resolution of keyIdentifiers
[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 =
205             bluePrintRuntimeService.bluePrintContext().checkNodeTemplateArtifact(nodeTemplateName, artifactTemplate)
206
207         val resolvedContent = when {
208             artifactTemplateDefinition != null -> {
209                 blueprintTemplateService.generateContent(
210                     bluePrintRuntimeService, nodeTemplateName,
211                     artifactTemplate, resolvedParamJsonContent, false,
212                     mutableMapOf(
213                         ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
214                             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE]
215                                 .asJsonPrimitive()
216                     )
217                 )
218             }
219             resolutionSummary -> {
220                 ResourceAssignmentUtils.generateResolutionSummaryData(resourceAssignments, resourceDefinitions)
221             }
222             else -> {
223                 resolvedParamJsonContent
224             }
225         }
226
227         if (isToStore(properties)) {
228             templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
229             log.info("Template resolution saved into database successfully : ($properties)")
230         }
231
232         return Pair(resolvedContent, assignmentMap)
233     }
234
235     override suspend fun resolveResourceDefinition(
236         blueprintRuntimeService: BluePrintRuntimeService<*>,
237         resourceDefinitions: MutableMap<String, ResourceDefinition>,
238         resolveDefinition: String,
239         sources: List<String>
240     ): MutableMap<String, JsonNode> {
241
242         // Populate Dummy Resource Assignments
243         val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
244
245         resolveResourceAssignments(
246             blueprintRuntimeService, resourceDefinitions, resourceAssignments,
247             UUID.randomUUID().toString(), hashMapOf()
248         )
249
250         // Get the data from Resource Assignments
251         return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
252     }
253
254     /**
255      * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
256      * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
257      * request.
258      */
259     override suspend fun resolveResourceAssignments(
260         blueprintRuntimeService: BluePrintRuntimeService<*>,
261         resourceDefinitions: MutableMap<String, ResourceDefinition>,
262         resourceAssignments: MutableList<ResourceAssignment>,
263         artifactPrefix: String,
264         properties: Map<String, Any>
265     ) {
266
267         val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
268
269         // Check the BlueprintRuntime Service Should be ResourceAssignmentRuntimeService
270         val resourceAssignmentRuntimeService = if (blueprintRuntimeService !is ResourceAssignmentRuntimeService) {
271             ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, artifactPrefix)
272         } else {
273             blueprintRuntimeService
274         }
275
276         exposeOccurrencePropertyInResourceAssignments(resourceAssignmentRuntimeService, properties)
277
278         coroutineScope {
279             bulkSequenced.forEach { batchResourceAssignments ->
280                 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
281                 val deferred = batchResourceAssignments
282                     .filter { it.name != "*" && it.name != "start" }
283                     .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
284                     .map { resourceAssignment ->
285                         async {
286                             val dictionaryName = resourceAssignment.dictionaryName
287                             val dictionarySource = resourceAssignment.dictionarySource
288
289                             val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
290
291                             val resourceAssignmentProcessor =
292                                 applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
293                                     ?: throw BluePrintProcessorException(
294                                         "failed to get resource processor ($processorName) " +
295                                             "for resource assignment(${resourceAssignment.name})"
296                                     )
297                             try {
298                                 // Set BluePrint Runtime Service
299                                 resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
300                                 // Set Resource Dictionaries
301                                 resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
302
303                                 resourceAssignmentProcessor.resourceAssignments = resourceAssignments
304
305                                 // Invoke Apply Method
306                                 resourceAssignmentProcessor.applyNB(resourceAssignment)
307
308                                 if (isToStore(properties)) {
309                                     resourceResolutionDBService.write(
310                                         properties,
311                                         blueprintRuntimeService,
312                                         artifactPrefix,
313                                         resourceAssignment
314                                     )
315                                     log.info("Resource resolution saved into database successfully : (${resourceAssignment.name})")
316                                 }
317
318                                 // Set errors from RA
319                                 blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
320                             } catch (e: RuntimeException) {
321                                 log.error("Fail in processing ${resourceAssignment.name}", e)
322                                 throw BluePrintProcessorException(e)
323                             }
324                         }
325                     }
326                 log.debug("Resolving (${deferred.size})resources parallel.")
327                 deferred.awaitAll()
328             }
329         }
330     }
331
332     /**
333      * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
334      *  derive the default input processor.
335      */
336     private fun processorName(
337         dictionaryName: String,
338         dictionarySource: String,
339         resourceDefinitions: MutableMap<String, ResourceDefinition>
340     ): String {
341         val processorName: String = when (dictionarySource) {
342             "input" -> {
343                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
344             }
345             "default" -> {
346                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
347             }
348             else -> {
349                 val resourceDefinition = resourceDefinitions[dictionaryName]
350                     ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
351
352                 val resourceSource = resourceDefinition.sources[dictionarySource]
353                     ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
354
355                 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
356             }
357         }
358         checkNotEmpty(processorName) {
359             "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
360         }
361
362         return processorName
363     }
364
365     // Check whether to store or not the resolution of resource and template
366     private fun isToStore(properties: Map<String, Any>): Boolean {
367         return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) &&
368             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
369     }
370
371     // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
372     private suspend fun isNewResolution(
373         bluePrintRuntimeService: BluePrintRuntimeService<*>,
374         properties: Map<String, Any>,
375         artifactPrefix: String
376     ): List<ResourceResolution> {
377         val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
378         val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
379         val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
380         val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
381
382         if (resolutionKey.isNotEmpty()) {
383             val existingResourceAssignments =
384                 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
385                     bluePrintRuntimeService,
386                     resolutionKey,
387                     occurrence,
388                     artifactPrefix
389                 )
390             if (existingResourceAssignments.isNotEmpty()) {
391                 log.info(
392                     "Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
393                     resolutionKey
394                 )
395             }
396             return existingResourceAssignments
397         } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
398             val existingResourceAssignments =
399                 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
400                     bluePrintRuntimeService,
401                     resourceId,
402                     resourceType,
403
404                     occurrence,
405                     artifactPrefix
406                 )
407             if (existingResourceAssignments.isNotEmpty()) {
408                 log.info(
409                     "Resolution with resourceId=($resourceId) and resourceType=($resourceType) already " +
410                         "exist - will resolve all resources not already resolved."
411                 )
412             }
413             return existingResourceAssignments
414         }
415         return emptyList()
416     }
417
418     // Update the resource assignment list with the status of the resource that have already been resolved
419     private fun updateResourceAssignmentWithExisting(
420         raRuntimeService: ResourceAssignmentRuntimeService,
421         resourceResolutionList: List<ResourceResolution>,
422         resourceAssignmentList: MutableList<ResourceAssignment>
423     ) {
424         resourceResolutionList.forEach { resourceResolution ->
425             if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
426                 resourceAssignmentList.forEach {
427                     if (compareOne(resourceResolution, it)) {
428                         log.info(
429                             "Resource ({}) already resolved: value=({})", it.name,
430                             if (hasLogProtect(it.property)) LOG_REDACTED else resourceResolution.value
431                         )
432
433                         // Make sure to recreate value as per the defined type.
434                         val value = resourceResolution.value!!.asJsonType(it.property!!.type)
435                         it.property!!.value = value
436                         it.status = resourceResolution.status
437                         ResourceAssignmentUtils.setResourceDataValue(it, raRuntimeService, value)
438                     }
439                 }
440             }
441         }
442     }
443
444     // Comparision between what we have in the database vs what we have to assign.
445     private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
446         return (
447             resourceResolution.name == resourceAssignment.name &&
448                 resourceResolution.dictionaryName == resourceAssignment.dictionaryName &&
449                 resourceResolution.dictionarySource == resourceAssignment.dictionarySource &&
450                 resourceResolution.dictionaryVersion == resourceAssignment.version
451             )
452     }
453
454     private fun exposeOccurrencePropertyInResourceAssignments(
455         raRuntimeService: ResourceAssignmentRuntimeService,
456         properties: Map<String, Any>
457     ) {
458         raRuntimeService.putResolutionStore(
459             ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE,
460             properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()
461         )
462     }
463 }