Templating constants added to ResourceAssignment
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / processor / ResourceAssignmentProcessor.kt
1 /*
2  *  Copyright © 2018 IBM.
3  *
4  *  Modifications Copyright © 2017-2019 AT&T, Bell Canada
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  */
18
19 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
20
21 import com.fasterxml.jackson.databind.JsonNode
22 import com.fasterxml.jackson.databind.node.TextNode
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
25 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
28 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
29 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
30 import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
31 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
32 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
33 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
34 import org.slf4j.LoggerFactory
35
36 abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssignment, Boolean> {
37
38     private val log = LoggerFactory.getLogger(ResourceAssignmentProcessor::class.java)
39
40     lateinit var raRuntimeService: ResourceAssignmentRuntimeService
41     var resourceDictionaries: MutableMap<String, ResourceDefinition> = hashMapOf()
42     var resourceAssignments: MutableList<ResourceAssignment> = arrayListOf()
43
44     var scriptPropertyInstances: MutableMap<String, Any> = hashMapOf()
45     lateinit var scriptType: String
46
47     /**
48      * This will be called from the scripts to serve instance from runtime to scripts.
49      */
50     open fun <T> scriptPropertyInstanceType(name: String): T {
51         return scriptPropertyInstances as? T
52             ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
53     }
54
55     open fun setFromInput(resourceAssignment: ResourceAssignment): Boolean {
56         try {
57             val value = raRuntimeService.getInputValue(resourceAssignment.name)
58             if (!value.isNullOrMissing()) {
59                 log.debug(
60                     "For Resource:(${resourceAssignment.name}) found value:({}) in input-data.",
61                     ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value)
62                 )
63                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
64                 return true
65             }
66         } catch (e: BluePrintProcessorException) {
67             // NoOp - couldn't find value from input
68         }
69         return false
70     }
71
72     open fun setFromInputKeyDependencies(keys: MutableList<String>, resourceAssignment: ResourceAssignment): Boolean {
73         try {
74             for (dependencyKey in keys) {
75                 var value = raRuntimeService.getInputValue(dependencyKey)
76                 if (!value.isNullOrMissing()) {
77                     log.debug(
78                         "For Resource:(${resourceAssignment.name}) found value:({}) in input-data under: ($dependencyKey).",
79                         ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value)
80                     )
81                     ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
82                     return true
83                 }
84             }
85         } catch (e: BluePrintProcessorException) {
86             // NoOp - couldn't find value from input
87         }
88         return false
89     }
90
91     open fun resourceDefinition(name: String): ResourceDefinition? {
92         return if (resourceDictionaries.containsKey(name)) resourceDictionaries[name] else null
93     }
94
95     open fun resolveInputKeyMappingVariables(
96         inputKeyMapping: Map<String, String>,
97         templatingConstants: Map<String, String>?
98     ): Map<String, JsonNode> {
99         val const = templatingConstants?.mapValues { TextNode(it.value) as JsonNode }
100         return inputKeyMapping.mapValues { const?.get(it.value) ?: raRuntimeService.getResolutionStore(it.value) }
101     }
102
103     open suspend fun resolveFromInputKeyMapping(valueToResolve: String, keyMapping: MutableMap<String, JsonNode>):
104         String {
105             if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) {
106                 return valueToResolve
107             }
108             // TODO("Optimize to JSON Node directly without velocity").asJsonNode().toString()
109             return BluePrintVelocityTemplateService.generateContent(valueToResolve, keyMapping.asJsonNode().toString())
110         }
111
112     final override suspend fun applyNB(resourceAssignment: ResourceAssignment): Boolean {
113         try {
114             processNB(resourceAssignment)
115         } catch (runtimeException: RuntimeException) {
116             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
117             recoverNB(runtimeException, resourceAssignment)
118             return false
119         }
120         return true
121     }
122
123     open suspend fun executeScript(resourceAssignment: ResourceAssignment) {
124         return when (scriptType) {
125             BluePrintConstants.SCRIPT_JYTHON -> {
126                 executeScriptBlocking(resourceAssignment)
127             }
128             else -> {
129                 executeScriptNB(resourceAssignment)
130             }
131         }
132     }
133
134     private suspend fun executeScriptNB(resourceAssignment: ResourceAssignment) {
135         try {
136             processNB(resourceAssignment)
137         } catch (runtimeException: RuntimeException) {
138             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
139             recoverNB(runtimeException, resourceAssignment)
140         }
141     }
142
143     private fun executeScriptBlocking(resourceAssignment: ResourceAssignment) {
144         try {
145             process(resourceAssignment)
146         } catch (runtimeException: RuntimeException) {
147             log.error("failed in ResourceAssignmentProcessor : ${runtimeException.message}", runtimeException)
148             recover(runtimeException, resourceAssignment)
149         }
150     }
151
152     /**
153      * If Jython Script, Override Blocking methods(process() and recover())
154      * If Kotlin or Internal Scripts, Override non blocking methods ( processNB() and recoverNB()), so default
155      * blocking
156      * methods will have default implementation,
157      *
158      * Always applyNB() method will be invoked, apply() won't be called from parent
159      */
160
161     final override fun apply(resourceAssignment: ResourceAssignment): Boolean {
162         throw BluePrintException("Not Implemented, use applyNB method")
163     }
164
165     final override fun prepareRequest(resourceAssignment: ResourceAssignment): ResourceAssignment {
166         throw BluePrintException("Not Implemented required")
167     }
168
169     final override fun prepareResponse(): Boolean {
170         throw BluePrintException("Not Implemented required")
171     }
172
173     final override suspend fun prepareRequestNB(resourceAssignment: ResourceAssignment): ResourceAssignment {
174         throw BluePrintException("Not Implemented required")
175     }
176
177     final override suspend fun prepareResponseNB(): Boolean {
178         throw BluePrintException("Not Implemented required")
179     }
180
181     override fun process(resourceAssignment: ResourceAssignment) {
182         throw BluePrintException("Not Implemented, child class will implement this")
183     }
184
185     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
186         throw BluePrintException("Not Implemented, child class will implement this")
187     }
188
189     fun addError(type: String, name: String, error: String) {
190         raRuntimeService.getBluePrintError().addError(type, name, error, getName())
191     }
192
193     fun addError(error: String) {
194         raRuntimeService.getBluePrintError().addError(error, getName())
195     }
196
197     open fun isTemplateKeyValueNull(resourceAssignment: ResourceAssignment): Boolean {
198         val resourceProp = checkNotNull(resourceAssignment.property) {
199             "Failed to populate mandatory resource resource mapping $resourceAssignment"
200         }
201         if (resourceProp.required != null && resourceProp.required!! &&
202             resourceProp.value.isNullOrMissing()
203         ) {
204             return true
205         }
206         return false
207     }
208 }