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, MutableList<ResourceAssignment>>
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, resourceAssignmentList) = resolveResources(
141 resourceAssignmentRuntimeService, nodeTemplateName,
142 artifactName, properties
144 val resolvedJsonContent = resourceAssignmentList
145 .associateBy({ it.name }, { it.property?.value })
148 templateMap[artifactName] = resolvedStringContent
149 assignmentMap[artifactName] = resolvedJsonContent
151 val failedResolution = resourceAssignmentList.filter { it.status != "success" && it.property?.required == true }.map { it.name }
152 if (failedResolution.isNotEmpty()) {
153 // The following error message is returned by default to handle a scenario when
154 // error message comes empty even when resolution has actually failed.
155 // Example: input-source type resolution seems to fail with no error code.
156 bluePrintRuntimeService.getBlueprintError().errors.add("Failed to resolve required resources($failedResolution)")
157 bluePrintRuntimeService.getBlueprintError().errors.addAll(resourceAssignmentRuntimeService.getBlueprintError().errors)
160 return ResourceResolutionResult(templateMap, assignmentMap)
163 override suspend fun resolveResources(
164 bluePrintRuntimeService: BlueprintRuntimeService<*>,
165 nodeTemplateName: String,
166 artifactPrefix: String,
167 properties: Map<String, Any>
168 ): Pair<String, MutableList<ResourceAssignment>> {
170 // Template Artifact Definition Name
171 val artifactTemplate = "$artifactPrefix-template"
172 // Resource Assignment Artifact Definition Name
173 val artifactMapping = "$artifactPrefix-mapping"
175 log.info("Resolving resource with resource assignment artifact($artifactMapping)")
177 val resourceAssignmentContent =
178 bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
180 val resourceAssignments: MutableList<ResourceAssignment> =
181 JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
182 as? MutableList<ResourceAssignment>
183 ?: throw BlueprintProcessorException("couldn't get Dictionary Definitions")
185 if (isToStore(properties)) {
186 val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
187 if (existingResourceResolution.isNotEmpty()) {
188 updateResourceAssignmentWithExisting(
189 bluePrintRuntimeService as ResourceAssignmentRuntimeService,
190 existingResourceResolution, resourceAssignments
195 // Get the Resource Dictionary Name
196 val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
197 .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
200 resolveResourceAssignments(
201 bluePrintRuntimeService,
208 val resolutionSummary = properties.getOrDefault(
209 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY,
213 val resolvedParamJsonContent =
214 ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
215 val artifactTemplateDefinition =
216 bluePrintRuntimeService.bluePrintContext().checkNodeTemplateArtifact(nodeTemplateName, artifactTemplate)
218 val resolvedContent = when {
219 artifactTemplateDefinition != null -> {
220 blueprintTemplateService.generateContent(
221 bluePrintRuntimeService, nodeTemplateName,
222 artifactTemplate, resolvedParamJsonContent, false,
224 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE to
225 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE]
230 resolutionSummary -> {
231 ResourceAssignmentUtils.generateResolutionSummaryData(resourceAssignments, resourceDefinitions)
234 resolvedParamJsonContent
238 if (isToStore(properties)) {
239 templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
240 log.info("Template resolution saved into database successfully : ($properties)")
243 return Pair(resolvedContent, resourceAssignments)
246 override suspend fun resolveResourceDefinition(
247 blueprintRuntimeService: BlueprintRuntimeService<*>,
248 resourceDefinitions: MutableMap<String, ResourceDefinition>,
249 resolveDefinition: String,
250 sources: List<String>
251 ): MutableMap<String, JsonNode> {
253 // Populate Dummy Resource Assignments
254 val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
256 resolveResourceAssignments(
257 blueprintRuntimeService, resourceDefinitions, resourceAssignments,
258 UUID.randomUUID().toString(), hashMapOf()
261 // Get the data from Resource Assignments
262 return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
266 * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
267 * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
270 override suspend fun resolveResourceAssignments(
271 blueprintRuntimeService: BlueprintRuntimeService<*>,
272 resourceDefinitions: MutableMap<String, ResourceDefinition>,
273 resourceAssignments: MutableList<ResourceAssignment>,
274 artifactPrefix: String,
275 properties: Map<String, Any>
278 val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
280 // Check the BlueprintRuntime Service Should be ResourceAssignmentRuntimeService
281 val resourceAssignmentRuntimeService = if (blueprintRuntimeService !is ResourceAssignmentRuntimeService) {
282 ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, artifactPrefix)
284 blueprintRuntimeService
287 exposeOccurrencePropertyInResourceAssignments(resourceAssignmentRuntimeService, properties)
290 bulkSequenced.forEach { batchResourceAssignments ->
291 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
292 val deferred = batchResourceAssignments
293 .filter { it.name != "*" && it.name != "start" }
294 .filter { it.status != BlueprintConstants.STATUS_SUCCESS }
295 .map { resourceAssignment ->
297 val dictionaryName = resourceAssignment.dictionaryName
298 val dictionarySource = resourceAssignment.dictionarySource
300 val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
302 val resourceAssignmentProcessor =
303 applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
304 ?: throw BlueprintProcessorException(
305 "failed to get resource processor ($processorName) " +
306 "for resource assignment(${resourceAssignment.name})"
309 // Set Blueprint Runtime Service
310 resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
311 // Set Resource Dictionaries
312 resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
314 resourceAssignmentProcessor.resourceAssignments = resourceAssignments
316 // Invoke Apply Method
317 resourceAssignmentProcessor.applyNB(resourceAssignment)
319 if (isToStore(properties)) {
320 resourceResolutionDBService.write(
322 blueprintRuntimeService,
326 log.info("Resource resolution saved into database successfully : (${resourceAssignment.name})")
329 // Set errors from RA
330 blueprintRuntimeService.setBlueprintError(resourceAssignmentRuntimeService.getBlueprintError())
331 } catch (e: RuntimeException) {
332 log.error("Fail in processing ${resourceAssignment.name}", e)
333 throw BlueprintProcessorException(e)
337 log.debug("Resolving (${deferred.size})resources parallel.")
344 * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
345 * derive the default input processor.
347 private fun processorName(
348 dictionaryName: String,
349 dictionarySource: String,
350 resourceDefinitions: MutableMap<String, ResourceDefinition>
352 val processorName: String = when (dictionarySource) {
354 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
357 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
360 val resourceDefinition = resourceDefinitions[dictionaryName]
361 ?: throw BlueprintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
363 val resourceSource = resourceDefinition.sources[dictionarySource]
364 ?: throw BlueprintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
366 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
369 checkNotEmpty(processorName) {
370 "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
376 // Check whether to store or not the resolution of resource and template
377 private fun isToStore(properties: Map<String, Any>): Boolean {
378 return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) &&
379 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
382 // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
383 private suspend fun isNewResolution(
384 bluePrintRuntimeService: BlueprintRuntimeService<*>,
385 properties: Map<String, Any>,
386 artifactPrefix: String
387 ): List<ResourceResolution> {
388 val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
389 val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
390 val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
391 val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
393 if (resolutionKey.isNotEmpty()) {
394 val existingResourceAssignments =
395 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
396 bluePrintRuntimeService,
401 if (existingResourceAssignments.isNotEmpty()) {
403 "Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
407 return existingResourceAssignments
408 } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
409 val existingResourceAssignments =
410 resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
411 bluePrintRuntimeService,
418 if (existingResourceAssignments.isNotEmpty()) {
420 "Resolution with resourceId=($resourceId) and resourceType=($resourceType) already " +
421 "exist - will resolve all resources not already resolved."
424 return existingResourceAssignments
429 // Update the resource assignment list with the status of the resource that have already been resolved
430 private fun updateResourceAssignmentWithExisting(
431 raRuntimeService: ResourceAssignmentRuntimeService,
432 resourceResolutionList: List<ResourceResolution>,
433 resourceAssignmentList: MutableList<ResourceAssignment>
435 resourceResolutionList.forEach { resourceResolution ->
436 if (resourceResolution.status == BlueprintConstants.STATUS_SUCCESS) {
437 resourceAssignmentList.forEach {
438 if (compareOne(resourceResolution, it)) {
440 "Resource ({}) already resolved: value=({})", it.name,
441 if (hasLogProtect(it.property)) LOG_REDACTED else resourceResolution.value
444 // Make sure to recreate value as per the defined type.
445 val value = resourceResolution.value!!.asJsonType(it.property!!.type)
446 it.property!!.value = value
447 it.status = resourceResolution.status
448 ResourceAssignmentUtils.setResourceDataValue(it, raRuntimeService, value)
455 // Comparision between what we have in the database vs what we have to assign.
456 private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
458 resourceResolution.name == resourceAssignment.name &&
459 resourceResolution.dictionaryName == resourceAssignment.dictionaryName &&
460 resourceResolution.dictionarySource == resourceAssignment.dictionarySource &&
461 resourceResolution.dictionaryVersion == resourceAssignment.version
465 private fun exposeOccurrencePropertyInResourceAssignments(
466 raRuntimeService: ResourceAssignmentRuntimeService,
467 properties: Map<String, Any>
469 raRuntimeService.putResolutionStore(
470 ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE,
471 properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE].asJsonPrimitive()