Add Json unit diff option.
[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.*
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
40 import java.util.*
41
42 interface ResourceResolutionService {
43
44     fun registeredResourceSources(): List<String>
45
46     suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String,
47                                     resolutionKey: String): String
48
49     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
50                                  artifactNames: List<String>, properties: Map<String, Any>): MutableMap<String, JsonNode>
51
52     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
53                                  artifactPrefix: String, properties: Map<String, Any>): String
54
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>
62
63     suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
64                                            resourceDefinitions: MutableMap<String, ResourceDefinition>,
65                                            resourceAssignments: MutableList<ResourceAssignment>,
66                                            artifactPrefix: String,
67                                            properties: Map<String, Any>)
68 }
69
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 {
76
77     private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
78
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) }
83     }
84
85     override suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>,
86                                              artifactTemplate: String,
87                                              resolutionKey: String): String {
88         return templateResolutionDBService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
89                 bluePrintRuntimeService,
90                 artifactTemplate,
91                 resolutionKey)
92     }
93
94     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
95                                           artifactNames: List<String>,
96                                           properties: Map<String, Any>): MutableMap<String, JsonNode> {
97
98         val resourceAssignmentRuntimeService =
99                 ResourceAssignmentUtils.transformToRARuntimeService(bluePrintRuntimeService, artifactNames.toString())
100
101         val resolvedParams: MutableMap<String, JsonNode> = hashMapOf()
102         artifactNames.forEach { artifactName ->
103             val resolvedContent = resolveResources(resourceAssignmentRuntimeService, nodeTemplateName,
104                     artifactName, properties)
105
106             resolvedParams[artifactName] = resolvedContent.asJsonType()
107         }
108         return resolvedParams
109     }
110
111
112     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
113                                           artifactPrefix: String, properties: Map<String, Any>): String {
114
115         // Velocity Artifact Definition Name
116         val artifactTemplate = "$artifactPrefix-template"
117         // Resource Assignment Artifact Definition Name
118         val artifactMapping = "$artifactPrefix-mapping"
119
120         val resolvedContent: String
121         log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)")
122
123         val resourceAssignmentContent =
124                 bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
125
126         val resourceAssignments: MutableList<ResourceAssignment> =
127                 JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
128                         as? MutableList<ResourceAssignment>
129                         ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
130
131         if (isToStore(properties)) {
132             val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix)
133             if (existingResourceResolution.isNotEmpty()) {
134                 updateResourceAssignmentWithExisting(bluePrintRuntimeService as ResourceAssignmentRuntimeService,
135                     existingResourceResolution, resourceAssignments)
136             }
137         }
138
139         // Get the Resource Dictionary Name
140         val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
141                 .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
142
143         // Resolve resources
144         resolveResourceAssignments(bluePrintRuntimeService,
145                 resourceDefinitions,
146                 resourceAssignments,
147                 artifactPrefix,
148                 properties)
149
150         val resolvedParamJsonContent =
151                 ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
152
153         resolvedContent = blueprintTemplateService.generateContent(bluePrintRuntimeService, nodeTemplateName,
154                 artifactTemplate, resolvedParamJsonContent)
155
156         if (isToStore(properties)) {
157             templateResolutionDBService.write(properties, resolvedContent, bluePrintRuntimeService, artifactPrefix)
158             log.info("Template resolution saved into database successfully : ($properties)")
159         }
160
161         return resolvedContent
162     }
163
164     override suspend fun resolveResourceDefinition(blueprintRuntimeService: BluePrintRuntimeService<*>,
165                                                    resourceDefinitions: MutableMap<String, ResourceDefinition>,
166                                                    resolveDefinition: String, sources: List<String>)
167             : MutableMap<String, JsonNode> {
168
169         // Populate Dummy Resource Assignments
170         val resourceAssignments = createResourceAssignments(resourceDefinitions, resolveDefinition, sources)
171
172         resolveResourceAssignments(blueprintRuntimeService, resourceDefinitions, resourceAssignments,
173                 UUID.randomUUID().toString(), hashMapOf())
174
175         // Get the data from Resource Assignments
176         return ResourceAssignmentUtils.generateResourceForAssignments(resourceAssignments)
177     }
178
179     /**
180      * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
181      * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
182      * request.
183      */
184     override suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
185                                                     resourceDefinitions: MutableMap<String, ResourceDefinition>,
186                                                     resourceAssignments: MutableList<ResourceAssignment>,
187                                                     artifactPrefix: String,
188                                                     properties: Map<String, Any>) {
189
190         val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
191
192         // Check the BlueprintRuntime Service Should be ResourceAssignmentRuntimeService
193         val resourceAssignmentRuntimeService = if (blueprintRuntimeService !is ResourceAssignmentRuntimeService) {
194             ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, artifactPrefix)
195         } else {
196             blueprintRuntimeService
197         }
198
199
200         coroutineScope {
201             bulkSequenced.forEach { batchResourceAssignments ->
202                 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
203                 val deferred = batchResourceAssignments
204                         .filter { it.name != "*" && it.name != "start" }
205                         .filter { it.status != BluePrintConstants.STATUS_SUCCESS }
206                         .map { resourceAssignment ->
207                             async {
208                                 val dictionaryName = resourceAssignment.dictionaryName
209                                 val dictionarySource = resourceAssignment.dictionarySource
210
211                                 val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
212
213                                 val resourceAssignmentProcessor =
214                                         applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
215                                                 ?: throw BluePrintProcessorException("failed to get resource processor ($processorName) " +
216                                                         "for resource assignment(${resourceAssignment.name})")
217                                 try {
218                                     // Set BluePrint Runtime Service
219                                     resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
220                                     // Set Resource Dictionaries
221                                     resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
222                                     // Invoke Apply Method
223                                     resourceAssignmentProcessor.applyNB(resourceAssignment)
224
225                                     if (isToStore(properties)) {
226                                         resourceResolutionDBService.write(properties,
227                                                 blueprintRuntimeService,
228                                                 artifactPrefix,
229                                                 resourceAssignment)
230                                         log.info("Resource resolution saved into database successfully : ($resourceAssignment)")
231                                     }
232
233                                     // Set errors from RA
234                                     blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
235                                 } catch (e: RuntimeException) {
236                                     log.error("Fail in processing ${resourceAssignment.name}", e)
237                                     throw BluePrintProcessorException(e)
238                                 }
239                             }
240                         }
241                 log.debug("Resolving (${deferred.size})resources parallel.")
242                 deferred.awaitAll()
243             }
244         }
245
246     }
247
248     /**
249      * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
250      *  derive the default input processor.
251      */
252     private fun processorName(dictionaryName: String, dictionarySource: String,
253                               resourceDefinitions: MutableMap<String, ResourceDefinition>): String {
254         val processorName: String = when (dictionarySource) {
255             "input" -> {
256                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
257             }
258             "default" -> {
259                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
260             }
261             else -> {
262                 val resourceDefinition = resourceDefinitions[dictionaryName]
263                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
264
265                 val resourceSource = resourceDefinition.sources[dictionarySource]
266                         ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
267
268                 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
269             }
270         }
271         checkNotEmpty(processorName) {
272             "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
273         }
274
275         return processorName
276
277     }
278
279     // Check whether to store or not the resolution of resource and template
280     private fun isToStore(properties: Map<String, Any>): Boolean {
281         return properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT)
282                 && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean
283     }
284
285     // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType
286     private suspend fun isNewResolution(bluePrintRuntimeService: BluePrintRuntimeService<*>,
287                                         properties: Map<String, Any>,
288                                         artifactPrefix: String): List<ResourceResolution> {
289         val occurrence = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_OCCURRENCE] as Int
290         val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String
291         val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String
292         val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String
293
294         if (resolutionKey.isNotEmpty()) {
295             val existingResourceAssignments =
296                     resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence(
297                             bluePrintRuntimeService,
298                             resolutionKey,
299                             occurrence,
300                             artifactPrefix)
301             if (existingResourceAssignments.isNotEmpty()) {
302                 log.info("Resolution with resolutionKey=($resolutionKey) already exist - will resolve all resources not already resolved.",
303                         resolutionKey)
304             }
305             return existingResourceAssignments
306         } else if (resourceId.isNotEmpty() && resourceType.isNotEmpty()) {
307             val existingResourceAssignments =
308                     resourceResolutionDBService.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence(
309                             bluePrintRuntimeService,
310                             resourceId,
311                             resourceType,
312
313                             occurrence,
314                             artifactPrefix)
315             if (existingResourceAssignments.isNotEmpty()) {
316                 log.info("Resolution with resourceId=($resourceId) and resourceType=($resourceType) already exist - will resolve " +
317                         "all resources not already resolved.")
318             }
319             return existingResourceAssignments
320         }
321         return emptyList()
322     }
323
324     // Update the resource assignment list with the status of the resource that have already been resolved
325     private fun updateResourceAssignmentWithExisting(raRuntimeService : ResourceAssignmentRuntimeService,
326                                                      resourceResolutionList: List<ResourceResolution>,
327                                                      resourceAssignmentList: MutableList<ResourceAssignment>) {
328         resourceResolutionList.forEach { resourceResolution ->
329             if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) {
330                 resourceAssignmentList.forEach {
331                     if (compareOne(resourceResolution, it)) {
332                         log.info("Resource ({}) already resolve: value=({})", it.name, resourceResolution.value)
333                         val value = resourceResolution.value!!.asJsonPrimitive()
334                         it.property!!.value = value
335                         it.status = resourceResolution.status
336                         ResourceAssignmentUtils.setResourceDataValue(it, raRuntimeService, value)
337                     }
338                 }
339             }
340         }
341     }
342
343     // Comparision between what we have in the database vs what we have to assign.
344     private fun compareOne(resourceResolution: ResourceResolution, resourceAssignment: ResourceAssignment): Boolean {
345         return (resourceResolution.name == resourceAssignment.name
346                 && resourceResolution.dictionaryName == resourceAssignment.dictionaryName
347                 && resourceResolution.dictionarySource == resourceAssignment.dictionarySource
348                 && resourceResolution.dictionaryVersion == resourceAssignment.version)
349     }
350
351 }