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.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
49 data class ResourceResolutionResult(
50 val templateMap: MutableMap<String, String>,
51 val assignmentMap: MutableMap<String, JsonNode>
54 interface ResourceResolutionService {
56 fun registeredResourceSources(): List<String>
58 suspend fun resolveFromDatabase(
59 bluePrintRuntimeService: BluePrintRuntimeService<*>,
60 artifactTemplate: String,
64 suspend fun resolveResources(
65 bluePrintRuntimeService: BluePrintRuntimeService<*>,
66 nodeTemplateName: String,
67 artifactNames: List<String>,
68 properties: Map<String, Any>
69 ): ResourceResolutionResult
71 suspend fun resolveResources(
72 bluePrintRuntimeService: BluePrintRuntimeService<*>,
73 nodeTemplateName: String,
74 artifactPrefix: String,
75 properties: Map<String, Any>
76 ): Pair<String, JsonNode>
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,
87 MutableMap<String, JsonNode>
89 suspend fun resolveResourceAssignments(
90 blueprintRuntimeService: BluePrintRuntimeService<*>,
91 resourceDefinitions: MutableMap<String, ResourceDefinition>,
92 resourceAssignments: MutableList<ResourceAssignment>,
93 artifactPrefix: String,
94 properties: Map<String, Any>
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
105 ResourceResolutionService {
107 private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
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) }
115 override suspend fun resolveFromDatabase(
116 bluePrintRuntimeService: BluePrintRuntimeService<*>,
117 artifactTemplate: String,
118 resolutionKey: String
120 return templateResolutionDBService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
121 bluePrintRuntimeService,
127 override suspend fun resolveResources(
128 bluePrintRuntimeService: BluePrintRuntimeService<*>,
129 nodeTemplateName: String,
130 artifactNames: List<String>,
131 properties: Map<String, Any>
132 ): ResourceResolutionResult {
134 val resourceAssignmentRuntimeService =
135 ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
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
144 templateMap[artifactName] = resolvedStringContent
145 assignmentMap[artifactName] = resolvedJsonContent
147 return ResourceResolutionResult(templateMap, assignmentMap)
150 override suspend fun resolveResources(
151 bluePrintRuntimeService: BluePrintRuntimeService<*>,
152 nodeTemplateName: String,
153 artifactPrefix: String,
154 properties: Map<String, Any>
155 ): Pair<String, JsonNode> {
157 // Template Artifact Definition Name
158 val artifactTemplate = "$artifactPrefix-template"
159 // Resource Assignment Artifact Definition Name
160 val artifactMapping = "$artifactPrefix-mapping"
162 log.info("Resolving resource with resource assignment artifact($artifactMapping)")
164 val resourceAssignmentContent =
165 bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
167 val resourceAssignments: MutableList<ResourceAssignment> =
168 JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
169 as? MutableList<ResourceAssignment>
170 ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
172 if (isToStore(properties)) {
173 val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
174 if (existingResourceResolution.isNotEmpty()) {
175 updateResourceAssignmentWithExisting(
176 bluePrintRuntimeService as ResourceAssignmentRuntimeService,
177 existingResourceResolution, resourceAssignments
182 // Get the Resource Dictionary Name
183 val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
184 .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
187 resolveResourceAssignments(
188 bluePrintRuntimeService,
195 val resolutionSummary = properties.getOrDefault(
196 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY,
199 val assignmentMap = resourceAssignments
200 .associateBy({ it.name }, { it.property?.value })
202 val resolvedParamJsonContent =
203 ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
204 val artifactTemplateDefinition =
205 bluePrintRuntimeService.bluePrintContext().checkNodeTemplateArtifact(nodeTemplateName, artifactTemplate)
207 val resolvedContent = when {
208 artifactTemplateDefinition != null -> {
209 blueprintTemplateService.generateContent(
210 bluePrintRuntimeService, nodeTemplateName,
211 artifactTemplate, resolvedParamJsonContent, false,
213 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
214 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE]
219 resolutionSummary -> {
220 ResourceAssignmentUtils.generateResolutionSummaryData(resourceAssignments, resourceDefinitions)
223 resolvedParamJsonContent
227 if (isToStore(properties)) {
228 templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
229 log.info("Template resolution saved into database successfully : ($properties)")
232 return Pair(resolvedContent, assignmentMap)
235 override suspend fun resolveResourceDefinition(
236 blueprintRuntimeService: BluePrintRuntimeService<*>,
237 resourceDefinitions: MutableMap<String, ResourceDefinition>,
238 resolveDefinition: String,
239 sources: List<String>
240 ): MutableMap<String, JsonNode> {
242 // Populate Dummy Resource Assignments
243 val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
245 resolveResourceAssignments(
246 blueprintRuntimeService, resourceDefinitions, resourceAssignments,
247 UUID.randomUUID().toString(), hashMapOf()
250 // Get the data from Resource Assignments
251 return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
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
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>
267 val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
269 // Check the BlueprintRuntime Service Should be ResourceAssignmentRuntimeService
270 val resourceAssignmentRuntimeService = if (blueprintRuntimeService !is ResourceAssignmentRuntimeService) {
271 ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, artifactPrefix)
273 blueprintRuntimeService
276 exposeOccurrencePropertyInResourceAssignments(resourceAssignmentRuntimeService, properties)
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 ->
286 val dictionaryName = resourceAssignment.dictionaryName
287 val dictionarySource = resourceAssignment.dictionarySource
289 val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
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})"
298 // Set BluePrint Runtime Service
299 resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
300 // Set Resource Dictionaries
301 resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
303 resourceAssignmentProcessor.resourceAssignments = resourceAssignments
305 // Invoke Apply Method
306 resourceAssignmentProcessor.applyNB(resourceAssignment)
308 if (isToStore(properties)) {
309 resourceResolutionDBService.write(
311 blueprintRuntimeService,
315 log.info("Resource resolution saved into database successfully : (${resourceAssignment.name})")
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)
326 log.debug("Resolving (${deferred.size})resources parallel.")
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.
336 private fun processorName(
337 dictionaryName: String,
338 dictionarySource: String,
339 resourceDefinitions: MutableMap<String, ResourceDefinition>
341 val processorName: String = when (dictionarySource) {
343 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
346 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
349 val resourceDefinition = resourceDefinitions[dictionaryName]
350 ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
352 val resourceSource = resourceDefinition.sources[dictionarySource]
353 ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
355 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
358 checkNotEmpty(processorName) {
359 "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
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
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
382 if (resolutionKey.isNotEmpty()) {
383 val existingResourceAssignments =
384 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
385 bluePrintRuntimeService,
390 if (existingResourceAssignments.isNotEmpty()) {
392 "Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
396 return existingResourceAssignments
397 } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
398 val existingResourceAssignments =
399 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
400 bluePrintRuntimeService,
407 if (existingResourceAssignments.isNotEmpty()) {
409 "Resolution with resourceId=($resourceId) and resourceType=($resourceType) already " +
410 "exist - will resolve all resources not already resolved."
413 return existingResourceAssignments
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>
424 resourceResolutionList.forEach { resourceResolution ->
425 if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
426 resourceAssignmentList.forEach {
427 if (compareOne(resourceResolution, it)) {
429 "Resource ({}) already resolved: value=({})", it.name,
430 if (hasLogProtect(it.property)) LOG_REDACTED else resourceResolution.value
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)
444 // Comparision between what we have in the database vs what we have to assign.
445 private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
447 resourceResolution.name == resourceAssignment.name &&
448 resourceResolution.dictionaryName == resourceAssignment.dictionaryName &&
449 resourceResolution.dictionarySource == resourceAssignment.dictionarySource &&
450 resourceResolution.dictionaryVersion == resourceAssignment.version
454 private fun exposeOccurrencePropertyInResourceAssignments(
455 raRuntimeService: ResourceAssignmentRuntimeService,
456 properties: Map<String, Any>
458 raRuntimeService.putResolutionStore(
459 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE,
460 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()