Add Jinja2 custom ResourceLocator
[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 kotlinx.coroutines.async
21 import kotlinx.coroutines.awaitAll
22 import kotlinx.coroutines.coroutineScope
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionResultService
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
28 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
29 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
32 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
33 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.BulkResourceSequencingUtils
34 import org.slf4j.LoggerFactory
35 import org.springframework.context.ApplicationContext
36 import org.springframework.stereotype.Service
37
38 interface ResourceResolutionService {
39
40     fun registeredResourceSources(): List<String>
41
42     suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String,
43                                     resolutionKey: String): String
44
45     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
46                                  artifactNames: List<String>, properties: Map<String, Any>): MutableMap<String, String>
47
48     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
49                                  artifactPrefix: String, properties: Map<String, Any>): String
50
51     suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
52                                  artifactMapping: String, artifactTemplate: String?): String
53
54     suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
55                                            resourceDefinitions: MutableMap<String, ResourceDefinition>,
56                                            resourceAssignments: MutableList<ResourceAssignment>,
57                                            identifierName: String)
58 }
59
60 @Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION)
61 open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext,
62                                          private var resolutionResultService: ResourceResolutionResultService,
63                                          private var blueprintTemplateService: BluePrintTemplateService) :
64         ResourceResolutionService {
65
66     private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java)
67
68     override fun registeredResourceSources(): List<String> {
69         return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java)
70                 .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
71                 .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) }
72     }
73
74     override suspend fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>,
75                                              artifactTemplate: String,
76                                              resolutionKey: String): String {
77         return resolutionResultService.read(bluePrintRuntimeService, artifactTemplate, resolutionKey)
78     }
79
80     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
81                                           artifactNames: List<String>, properties: Map<String, Any>): MutableMap<String, String> {
82
83         val resolvedParams: MutableMap<String, String> = hashMapOf()
84         artifactNames.forEach { artifactName ->
85             val resolvedContent = resolveResources(bluePrintRuntimeService, nodeTemplateName,
86                     artifactName, properties)
87             resolvedParams[artifactName] = resolvedContent
88         }
89         return resolvedParams
90     }
91
92     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
93                                           artifactPrefix: String, properties: Map<String, Any>): String {
94
95         // Velocity Artifact Definition Name
96         val artifactTemplate = "$artifactPrefix-template"
97         // Resource Assignment Artifact Definition Name
98         val artifactMapping = "$artifactPrefix-mapping"
99
100         val result = resolveResources(bluePrintRuntimeService, nodeTemplateName,
101                 artifactMapping, artifactTemplate)
102
103         if (properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT)
104                 && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean) {
105             resolutionResultService.write(properties, result, bluePrintRuntimeService, artifactPrefix)
106             log.info("resolution saved into database successfully : ($properties)")
107         }
108
109         return result
110     }
111
112
113     override suspend fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
114                                           artifactMapping: String, artifactTemplate: String?): String {
115
116         val resolvedContent: String
117         log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)")
118
119         val identifierName = artifactTemplate ?: "no-template"
120
121         val resourceAssignmentContent =
122                 bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping)
123
124         val resourceAssignments: MutableList<ResourceAssignment> =
125                 JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java)
126                         as? MutableList<ResourceAssignment>
127                         ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions")
128
129         // Get the Resource Dictionary Name
130         val resourceDefinitions: MutableMap<String, ResourceDefinition> = ResourceAssignmentUtils
131                 .resourceDefinitions(bluePrintRuntimeService.bluePrintContext().rootPath)
132
133         // Resolve resources
134         resolveResourceAssignments(bluePrintRuntimeService, resourceDefinitions, resourceAssignments, identifierName)
135
136         val resolvedParamJsonContent =
137                 ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList())
138
139         // Check Template is there
140         if (artifactTemplate != null) {
141             resolvedContent = blueprintTemplateService.generateContent(bluePrintRuntimeService, nodeTemplateName,
142                     artifactTemplate, resolvedParamJsonContent)
143
144         } else {
145             resolvedContent = resolvedParamJsonContent
146         }
147
148         return resolvedContent
149     }
150
151     /**
152      * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the
153      * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the
154      * request.
155      */
156     override suspend fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>,
157                                                     resourceDefinitions: MutableMap<String, ResourceDefinition>,
158                                                     resourceAssignments: MutableList<ResourceAssignment>,
159                                                     identifierName: String) {
160
161         val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments)
162         val resourceAssignmentRuntimeService =
163                 ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, identifierName)
164
165         coroutineScope {
166             bulkSequenced.forEach { batchResourceAssignments ->
167                 // Execute Non Dependent Assignments in parallel ( ie asynchronously )
168                 val deferred = batchResourceAssignments.filter { it.name != "*" && it.name != "start" }
169                         .map { resourceAssignment ->
170                             async {
171                                 val dictionaryName = resourceAssignment.dictionaryName
172                                 val dictionarySource = resourceAssignment.dictionarySource
173                                 /**
174                                  * Get the Processor name
175                                  */
176                                 val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDefinitions)
177
178                                 val resourceAssignmentProcessor =
179                                         applicationContext.getBean(processorName) as? ResourceAssignmentProcessor
180                                                 ?: throw BluePrintProcessorException("failed to get resource processor ($processorName) " +
181                                                         "for resource assignment(${resourceAssignment.name})")
182                                 try {
183                                     // Set BluePrint Runtime Service
184                                     resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService
185                                     // Set Resource Dictionaries
186                                     resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions
187                                     // Invoke Apply Method
188                                     resourceAssignmentProcessor.applyNB(resourceAssignment)
189                                     // Set errors from RA
190                                     blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError())
191                                 } catch (e: RuntimeException) {
192                                     log.error("Fail in processing ${resourceAssignment.name}", e)
193                                     throw BluePrintProcessorException(e)
194                                 }
195                             }
196                         }
197                 log.debug("Resolving (${deferred.size})resources parallel.")
198                 deferred.awaitAll()
199             }
200         }
201
202     }
203
204
205     /**
206      * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can
207      *  derive the default input processor.
208      */
209     private fun processorName(dictionaryName: String, dictionarySource: String,
210                               resourceDefinitions: MutableMap<String, ResourceDefinition>): String {
211         val processorName: String = when (dictionarySource) {
212             "input" -> {
213                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input"
214             }
215             "default" -> {
216                 "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default"
217             }
218             else -> {
219                 val resourceDefinition = resourceDefinitions[dictionaryName]
220                         ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName")
221
222                 val resourceSource = resourceDefinition.sources[dictionarySource]
223                         ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)")
224
225                 ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type)
226             }
227         }
228         checkNotEmpty(processorName) {
229             "couldn't get processor name for resource dictionary definition($dictionaryName) source($dictionarySource)"
230         }
231
232         return processorName
233
234     }
235 }