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