Refactoring ResourceAssignmentUtils
[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.*
26 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
27 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
28 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
29 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
30 import org.slf4j.LoggerFactory
31 import java.util.*
32
33 abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssignment, Boolean> {
34
35     private val log = LoggerFactory.getLogger(ResourceAssignmentProcessor::class.java)
36
37     lateinit var raRuntimeService: ResourceAssignmentRuntimeService
38     var resourceDictionaries: MutableMap<String, ResourceDefinition> = hashMapOf()
39
40     var scriptPropertyInstances: MutableMap<String, Any> = hashMapOf()
41     lateinit var scriptType: String
42
43     /**
44      * This will be called from the scripts to serve instance from runtime to scripts.
45      */
46     open fun <T> scriptPropertyInstanceType(name: String): T {
47         return scriptPropertyInstances as? T
48             ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
49     }
50
51     open fun setFromInput(resourceAssignment: ResourceAssignment): Boolean {
52         try {
53             val value = raRuntimeService.getInputValue(resourceAssignment.name)
54             if (!value.isNullOrMissing()) {
55                 ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value)
56                 return true
57             }
58         } catch (e: BluePrintProcessorException) {
59             // NoOp - couldn't find value from input
60         }
61         return false
62     }
63
64     open fun resourceDefinition(name: String): ResourceDefinition? {
65         return if (resourceDictionaries.containsKey(name)) resourceDictionaries[name] else null
66     }
67
68     open fun resolveInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, JsonNode> {
69         val resolvedInputKeyMapping = HashMap<String, JsonNode>()
70         if (MapUtils.isNotEmpty(inputKeyMapping)) {
71             for ((key, value) in inputKeyMapping) {
72                 val resultValue = raRuntimeService.getResolutionStore(value)
73                 resolvedInputKeyMapping[key] = resultValue
74             }
75         }
76         return resolvedInputKeyMapping
77     }
78
79     open suspend fun resolveFromInputKeyMapping(valueToResolve: String, keyMapping: MutableMap<String, JsonNode>):
80             String {
81         if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) {
82             return valueToResolve
83         }
84         //TODO("Optimize to JSON Node directly without velocity").asJsonNode().toString()
85         return BluePrintVelocityTemplateService.generateContent(valueToResolve, keyMapping.asJsonNode().toString())
86     }
87
88     final override suspend fun applyNB(resourceAssignment: ResourceAssignment): Boolean {
89         try {
90             processNB(resourceAssignment)
91         } catch (runtimeException: RuntimeException) {
92             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
93             recoverNB(runtimeException, resourceAssignment)
94             return false
95         }
96         return true
97     }
98
99     suspend fun executeScript(resourceAssignment: ResourceAssignment) {
100         return when (scriptType) {
101             BluePrintConstants.SCRIPT_JYTHON -> {
102                 executeScriptBlocking(resourceAssignment)
103             }
104             else -> {
105                 executeScriptNB(resourceAssignment)
106             }
107         }
108     }
109
110     private suspend fun executeScriptNB(resourceAssignment: ResourceAssignment) {
111         try {
112             processNB(resourceAssignment)
113         } catch (runtimeException: RuntimeException) {
114             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
115             recoverNB(runtimeException, resourceAssignment)
116         }
117     }
118
119     private fun executeScriptBlocking(resourceAssignment: ResourceAssignment) {
120         try {
121             process(resourceAssignment)
122         } catch (runtimeException: RuntimeException) {
123             log.error("failed in ResourceAssignmentProcessor : ${runtimeException.message}", runtimeException)
124             recover(runtimeException, resourceAssignment)
125         }
126     }
127
128     /**
129      * If Jython Script, Override Blocking methods(process() and recover())
130      * If Kotlin or Internal Scripts, Override non blocking methods ( processNB() and recoverNB()), so default
131      * blocking
132      * methods will have default implementation,
133      *
134      * Always applyNB() method will be invoked, apply() won't be called from parent
135      */
136
137     final override fun apply(resourceAssignment: ResourceAssignment): Boolean {
138         throw BluePrintException("Not Implemented, use applyNB method")
139     }
140
141     final override fun prepareRequest(resourceAssignment: ResourceAssignment): ResourceAssignment {
142         throw BluePrintException("Not Implemented required")
143     }
144
145     final override fun prepareResponse(): Boolean {
146         throw BluePrintException("Not Implemented required")
147     }
148
149     final override suspend fun prepareRequestNB(resourceAssignment: ResourceAssignment): ResourceAssignment {
150         throw BluePrintException("Not Implemented required")
151     }
152
153     final override suspend fun prepareResponseNB(): Boolean {
154         throw BluePrintException("Not Implemented required")
155     }
156
157     override fun process(resourceAssignment: ResourceAssignment) {
158         throw BluePrintException("Not Implemented, child class will implement this")
159     }
160
161     override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
162         throw BluePrintException("Not Implemented, child class will implement this")
163     }
164
165     fun addError(type: String, name: String, error: String) {
166         raRuntimeService.getBluePrintError().addError(type, name, error)
167     }
168
169     fun addError(error: String) {
170         raRuntimeService.getBluePrintError().addError(error)
171     }
172 }