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