e96083f95eaf48bbc013c60852748d7997230343
[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 org.apache.commons.collections.MapUtils
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 import java.util.HashMap
36
37 abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssignment, Boolean> {
38
39     private val log = LoggerFactory.getLogger(ResourceAssignmentProcessor::class.java)
40
41     lateinit var raRuntimeService: ResourceAssignmentRuntimeService
42     var resourceDictionaries: MutableMap<String, ResourceDefinition> = hashMapOf()
43     var resourceAssignments: MutableList<ResourceAssignment> = arrayListOf()
44
45     var scriptPropertyInstances: MutableMap<String, Any> = hashMapOf()
46     lateinit var scriptType: String
47
48     /**
49      * This will be called from the scripts to serve instance from runtime to scripts.
50      */
51     open fun <T> scriptPropertyInstanceType(name: String): T {
52         return scriptPropertyInstances as? T
53             ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
54     }
55
56     open fun setFromInput(resourceAssignment: ResourceAssignment): Boolean {
57         try {
58             val value = raRuntimeService.getInputValue(resourceAssignment.name)
59             if (!value.isNullOrMissing()) {
60                 log.debug(
61                     "For Resource:(${resourceAssignment.name}) found value:({}) in input-data.",
62                     ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value)
63                 )
64                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
65                 return true
66             }
67         } catch (e: BluePrintProcessorException) {
68             // NoOp - couldn't find value from input
69         }
70         return false
71     }
72
73     open fun setFromInputKeyDependencies(keys: MutableList<String>, resourceAssignment: ResourceAssignment): Boolean {
74         try {
75             for (dependencyKey in keys) {
76                 var value = raRuntimeService.getInputValue(dependencyKey)
77                 if (!value.isNullOrMissing()) {
78                     log.debug(
79                         "For Resource:(${resourceAssignment.name}) found value:({}) in input-data under: ($dependencyKey).",
80                         ResourceAssignmentUtils.getValueToLog(resourceAssignment.property?.metadata, value)
81                     )
82                     ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
83                     return true
84                 }
85             }
86         } catch (e: BluePrintProcessorException) {
87             // NoOp - couldn't find value from input
88         }
89         return false
90     }
91
92     open fun resourceDefinition(name: String): ResourceDefinition? {
93         return if (resourceDictionaries.containsKey(name)) resourceDictionaries[name] else null
94     }
95
96     open fun resolveInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, JsonNode> {
97         val resolvedInputKeyMapping = HashMap<String, JsonNode>()
98         if (MapUtils.isNotEmpty(inputKeyMapping)) {
99             for ((key, value) in inputKeyMapping) {
100                 val resultValue = raRuntimeService.getResolutionStore(value)
101                 resolvedInputKeyMapping[key] = resultValue
102             }
103         }
104         return resolvedInputKeyMapping
105     }
106
107     open suspend fun resolveFromInputKeyMapping(valueToResolve: String, keyMapping: MutableMap<String, JsonNode>):
108         String {
109             if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) {
110                 return valueToResolve
111             }
112             // TODO("Optimize to JSON Node directly without velocity").asJsonNode().toString()
113             return BluePrintVelocityTemplateService.generateContent(valueToResolve, keyMapping.asJsonNode().toString())
114         }
115
116     final override suspend fun applyNB(resourceAssignment: ResourceAssignment): Boolean {
117         try {
118             processNB(resourceAssignment)
119         } catch (runtimeException: RuntimeException) {
120             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
121             recoverNB(runtimeException, resourceAssignment)
122             return false
123         }
124         return true
125     }
126
127     open suspend fun executeScript(resourceAssignment: ResourceAssignment) {
128         return when (scriptType) {
129             BluePrintConstants.SCRIPT_JYTHON -> {
130                 executeScriptBlocking(resourceAssignment)
131             }
132             else -> {
133                 executeScriptNB(resourceAssignment)
134             }
135         }
136     }
137
138     private suspend fun executeScriptNB(resourceAssignment: ResourceAssignment) {
139         try {
140             processNB(resourceAssignment)
141         } catch (runtimeException: RuntimeException) {
142             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
143             recoverNB(runtimeException, resourceAssignment)
144         }
145     }
146
147     private fun executeScriptBlocking(resourceAssignment: ResourceAssignment) {
148         try {
149             process(resourceAssignment)
150         } catch (runtimeException: RuntimeException) {
151             log.error("failed in ResourceAssignmentProcessor : ${runtimeException.message}", runtimeException)
152             recover(runtimeException, resourceAssignment)
153         }
154     }
155
156     /**
157      * If Jython Script, Override Blocking methods(process() and recover())
158      * If Kotlin or Internal Scripts, Override non blocking methods ( processNB() and recoverNB()), so default
159      * blocking
160      * methods will have default implementation,
161      *
162      * Always applyNB() method will be invoked, apply() won't be called from parent
163      */
164
165     final override fun apply(resourceAssignment: ResourceAssignment): Boolean {
166         throw BluePrintException("Not Implemented, use applyNB method")
167     }
168
169     final override fun prepareRequest(resourceAssignment: ResourceAssignment): ResourceAssignment {
170         throw BluePrintException("Not Implemented required")
171     }
172
173     final override fun prepareResponse(): Boolean {
174         throw BluePrintException("Not Implemented required")
175     }
176
177     final override suspend fun prepareRequestNB(resourceAssignment: ResourceAssignment): ResourceAssignment {
178         throw BluePrintException("Not Implemented required")
179     }
180
181     final override suspend fun prepareResponseNB(): Boolean {
182         throw BluePrintException("Not Implemented required")
183     }
184
185     override fun process(resourceAssignment: ResourceAssignment) {
186         throw BluePrintException("Not Implemented, child class will implement this")
187     }
188
189     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
190         throw BluePrintException("Not Implemented, child class will implement this")
191     }
192
193     fun addError(type: String, name: String, error: String) {
194         raRuntimeService.getBluePrintError().addError(type, name, error, getName())
195     }
196
197     fun addError(error: String) {
198         raRuntimeService.getBluePrintError().addError(error, getName())
199     }
200
201     open fun isTemplateKeyValueNull(resourceAssignment: ResourceAssignment): Boolean {
202         val resourceProp = checkNotNull(resourceAssignment.property) {
203             "Failed to populate mandatory resource resource mapping $resourceAssignment"
204         }
205         if (resourceProp.required != null && resourceProp.required!! &&
206             resourceProp.value.isNullOrMissing()
207         ) {
208             return true
209         }
210         return false
211     }
212 }