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