2 * Copyright © 2017-2018 AT&T Intellectual Property.
3 * Modifications Copyright © 2018-2019 IBM, Bell Canada
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution
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.*
31 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
32 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService
33 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
34 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
35 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
36 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.BulkResourceSequencingUtils
37 import org.slf4j.LoggerFactory
38 import org.springframework.context.ApplicationContext
39 import org.springframework.stereotype.Service
42 interface ResourceResolutionService {
44 fun registeredResourceSources(): List<String>
46 suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String,
47 resolutionKey: String): String
49 suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
50 artifactNames: List<String>, properties: Map<String, Any>): MutableMap<String, String>
52 suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
53 artifactPrefix: String, properties: Map<String, Any>): String
55 /** Resolve resources for all the sources defined in a particular resource Definition[resolveDefinition]
56 * with other [resourceDefinitions] dependencies for the sources [sources]
57 * Used to get the same resource values from multiple sources. **/
58 suspend fun resolveResourceDefinition(blueprintRuntimeService: BluePrintRuntimeService<*>,
59 resourceDefinitions: MutableMap<String, ResourceDefinition>,
60 resolveDefinition: String, sources: List<String>)
61 : MutableMap<String, JsonNode>
63 suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
64 resourceDefinitions: MutableMap<String, ResourceDefinition>,
65 resourceAssignments: MutableList<ResourceAssignment>,
66 artifactPrefix: String,
67 properties: Map<String, Any>)
70 @Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
71 open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext,
72 private var templateResolutionDBService: TemplateResolutionService,
73 private var blueprintTemplateService: BluePrintTemplateService,
74 private var resourceResolutionDBService: ResourceResolutionDBService) :
75 ResourceResolutionService {
77 private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
79 override fun registeredResourceSources(): List<String> {
80 return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java)
81 .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
82 .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
85 override suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>,
86 artifactTemplate: String,
87 resolutionKey: String): String {
88 return templateResolutionDBService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
89 bluePrintRuntimeService,
94 override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
95 artifactNames: List<String>,
96 properties: Map<String, Any>): MutableMap<String, String> {
98 val resourceAssignmentRuntimeService =
99 ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
101 val resolvedParams: MutableMap<String, String> = hashMapOf()
102 artifactNames.forEach { artifactName ->
103 val resolvedContent = resolveResources(resourceAssignmentRuntimeService, nodeTemplateName,
104 artifactName, properties)
106 resolvedParams[artifactName] = resolvedContent
108 return resolvedParams
112 override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
113 artifactPrefix: String, properties: Map<String, Any>): String {
115 // Velocity Artifact Definition Name
116 val artifactTemplate = "$artifactPrefix-template"
117 // Resource Assignment Artifact Definition Name
118 val artifactMapping = "$artifactPrefix-mapping"
120 val resolvedContent: String
121 log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)")
123 val resourceAssignmentContent =
124 bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
126 val resourceAssignments: MutableList<ResourceAssignment> =
127 JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
128 as? MutableList<ResourceAssignment>
129 ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
131 if (isToStore(properties)) {
132 val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
133 if (existingResourceResolution.isNotEmpty()) {
134 updateResourceAssignmentWithExisting(bluePrintRuntimeService as ResourceAssignmentRuntimeService,
135 existingResourceResolution, resourceAssignments)
139 // Get the Resource Dictionary Name
140 val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
141 .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
144 resolveResourceAssignments(bluePrintRuntimeService,
150 val resolvedParamJsonContent =
151 ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
153 resolvedContent = blueprintTemplateService.generateContent(bluePrintRuntimeService, nodeTemplateName,
154 artifactTemplate, resolvedParamJsonContent, false,
155 mutableMapOf(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
156 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()))
158 if (isToStore(properties)) {
159 templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
160 log.info("Template resolution saved into database successfully : ($properties)")
163 return resolvedContent
166 override suspend fun resolveResourceDefinition(blueprintRuntimeService: BluePrintRuntimeService<*>,
167 resourceDefinitions: MutableMap<String, ResourceDefinition>,
168 resolveDefinition: String, sources: List<String>)
169 : MutableMap<String, JsonNode> {
171 // Populate Dummy Resource Assignments
172 val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
174 resolveResourceAssignments(blueprintRuntimeService, resourceDefinitions, resourceAssignments,
175 UUID.randomUUID().toString(), hashMapOf())
177 // Get the data from Resource Assignments
178 return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
182 * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
183 * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
186 override suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
187 resourceDefinitions: MutableMap<String, ResourceDefinition>,
188 resourceAssignments: MutableList<ResourceAssignment>,
189 artifactPrefix: String,
190 properties: Map<String, Any>) {
192 val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
194 // Check the BlueprintRuntime Service Should be ResourceAssignmentRuntimeService
195 val resourceAssignmentRuntimeService = if (blueprintRuntimeService !is ResourceAssignmentRuntimeService) {
196 ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, artifactPrefix)
198 blueprintRuntimeService
203 bulkSequenced.forEach { batchResourceAssignments ->
204 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
205 val deferred = batchResourceAssignments
206 .filter { it.name != "*" && it.name != "start" }
207 .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
208 .map { resourceAssignment ->
210 val dictionaryName = resourceAssignment.dictionaryName
211 val dictionarySource = resourceAssignment.dictionarySource
213 val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
215 val resourceAssignmentProcessor =
216 applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
217 ?: throw BluePrintProcessorException("failed to get resource processor ($processorName) " +
218 "for resource assignment(${resourceAssignment.name})")
220 // Set BluePrint Runtime Service
221 resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
222 // Set Resource Dictionaries
223 resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
224 // Invoke Apply Method
225 resourceAssignmentProcessor.applyNB(resourceAssignment)
227 if (isToStore(properties)) {
228 resourceResolutionDBService.write(properties,
229 blueprintRuntimeService,
232 log.info("Resource resolution saved into database successfully : ($resourceAssignment)")
235 // Set errors from RA
236 blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
237 } catch (e: RuntimeException) {
238 log.error("Fail in processing ${resourceAssignment.name}", e)
239 throw BluePrintProcessorException(e)
243 log.debug("Resolving (${deferred.size})resources parallel.")
251 * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
252 * derive the default input processor.
254 private fun processorName(dictionaryName: String, dictionarySource: String,
255 resourceDefinitions: MutableMap<String, ResourceDefinition>): String {
256 val processorName: String = when (dictionarySource) {
258 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
261 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
264 val resourceDefinition = resourceDefinitions[dictionaryName]
265 ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
267 val resourceSource = resourceDefinition.sources[dictionarySource]
268 ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
270 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
273 checkNotEmpty(processorName) {
274 "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
281 // Check whether to store or not the resolution of resource and template
282 private fun isToStore(properties: Map<String, Any>): Boolean {
283 return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT)
284 && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
287 // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
288 private suspend fun isNewResolution(bluePrintRuntimeService: BluePrintRuntimeService<*>,
289 properties: Map<String, Any>,
290 artifactPrefix: String): List<ResourceResolution> {
291 val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
292 val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
293 val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
294 val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
296 if (resolutionKey.isNotEmpty()) {
297 val existingResourceAssignments =
298 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
299 bluePrintRuntimeService,
303 if (existingResourceAssignments.isNotEmpty()) {
304 log.info("Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
307 return existingResourceAssignments
308 } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
309 val existingResourceAssignments =
310 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
311 bluePrintRuntimeService,
317 if (existingResourceAssignments.isNotEmpty()) {
318 log.info("Resolution with resourceId=($resourceId) and resourceType=($resourceType) already exist - will resolve " +
319 "all resources not already resolved.")
321 return existingResourceAssignments
326 // Update the resource assignment list with the status of the resource that have already been resolved
327 private fun updateResourceAssignmentWithExisting(raRuntimeService : ResourceAssignmentRuntimeService,
328 resourceResolutionList: List<ResourceResolution>,
329 resourceAssignmentList: MutableList<ResourceAssignment>) {
330 resourceResolutionList.forEach { resourceResolution ->
331 if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
332 resourceAssignmentList.forEach {
333 if (compareOne(resourceResolution, it)) {
334 log.info("Resource ({}) already resolve: value=({})", it.name, resourceResolution.value)
336 // Make sure to recreate value as per the defined type.
337 val value = resourceResolution.value!!.asJsonType(it.property!!.type)
338 it.property!!.value = value
339 it.status = resourceResolution.status
340 ResourceAssignmentUtils.setResourceDataValue(it, raRuntimeService, value)
347 // Comparision between what we have in the database vs what we have to assign.
348 private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
349 return (resourceResolution.name == resourceAssignment.name
350 && resourceResolution.dictionaryName == resourceAssignment.dictionaryName
351 && resourceResolution.dictionarySource == resourceAssignment.dictionarySource
352 && resourceResolution.dictionaryVersion == resourceAssignment.version)