Resource resolution should return a string
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / utils / ResourceAssignmentUtils.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2019 IBM.
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.utils
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.fasterxml.jackson.databind.ObjectMapper
22 import com.fasterxml.jackson.databind.node.NullNode
23 import com.fasterxml.jackson.databind.node.ObjectNode
24 import com.fasterxml.jackson.databind.node.TextNode
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
27 import org.onap.ccsdk.cds.controllerblueprints.core.*
28 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
29 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils
30 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
31 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
32 import org.slf4j.LoggerFactory
33 import java.util.*
34
35 class ResourceAssignmentUtils {
36     companion object {
37
38         private val logger = LoggerFactory.getLogger(ResourceAssignmentUtils::class.toString())
39
40         suspend fun resourceDefinitions(blueprintBasePath: String): MutableMap<String, ResourceDefinition> {
41             val dictionaryFile = normalizedFile(blueprintBasePath, BluePrintConstants.TOSCA_DEFINITIONS_DIR,
42                     ResourceResolutionConstants.FILE_NAME_RESOURCE_DEFINITION_TYPES)
43             checkFileExists(dictionaryFile) { "resource definition file(${dictionaryFile.absolutePath}) is missing" }
44             return JacksonReactorUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java)
45         }
46
47         @Throws(BluePrintProcessorException::class)
48         fun setResourceDataValue(resourceAssignment: ResourceAssignment,
49                                  raRuntimeService: ResourceAssignmentRuntimeService, value: Any?) {
50             // TODO("See if Validation is needed in future with respect to conversion and Types")
51             return setResourceDataValue(resourceAssignment, raRuntimeService, value.asJsonType())
52         }
53
54         @Throws(BluePrintProcessorException::class)
55         fun setResourceDataValue(resourceAssignment: ResourceAssignment,
56                                  raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode) {
57             val resourceProp = checkNotNull(resourceAssignment.property) {
58                 "Failed in setting resource value for resource mapping $resourceAssignment"
59             }
60             checkNotEmpty(resourceAssignment.name) {
61                 "Failed in setting resource value for resource mapping $resourceAssignment"
62             }
63
64             if (resourceAssignment.dictionaryName.isNullOrEmpty()) {
65                 resourceAssignment.dictionaryName = resourceAssignment.name
66                 logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) " +
67                         "as dictionary key (${resourceAssignment.dictionaryName})")
68             }
69
70             try {
71                 if (resourceProp.type.isNotEmpty()) {
72                     logger.info("Setting Resource Value ($value) for Resource Name " +
73                             "(${resourceAssignment.name}) of type (${resourceProp.type})")
74                     setResourceValue(resourceAssignment, raRuntimeService, value)
75                     resourceAssignment.updatedDate = Date()
76                     resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
77                     resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS
78                 }
79             } catch (e: Exception) {
80                 throw BluePrintProcessorException("Failed in setting value for template key " +
81                         "(${resourceAssignment.name}) and dictionary key (${resourceAssignment.dictionaryName}) of " +
82                         "type (${resourceProp.type}) with error message (${e.message})", e)
83             }
84         }
85
86         private fun setResourceValue(resourceAssignment: ResourceAssignment,
87                                      raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode) {
88             // TODO("See if Validation is needed wrt to type before storing")
89             raRuntimeService.putResolutionStore(resourceAssignment.name, value)
90             raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value)
91             resourceAssignment.property!!.value = value
92         }
93
94         fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) {
95             if (isNotEmpty(resourceAssignment.name)) {
96                 resourceAssignment.updatedDate = Date()
97                 resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM
98                 resourceAssignment.status = BluePrintConstants.STATUS_FAILURE
99                 resourceAssignment.message = message
100             }
101         }
102
103         @Throws(BluePrintProcessorException::class)
104         fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) {
105             val resourceProp = checkNotNull(resourceAssignment.property) {
106                 "Failed to populate mandatory resource resource mapping $resourceAssignment"
107             }
108             if (resourceProp.required != null && resourceProp.required!!
109                     && (resourceProp.value == null || resourceProp.value !is NullNode)) {
110                 logger.error("failed to populate mandatory resource mapping ($resourceAssignment)")
111                 throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)")
112             }
113         }
114
115         @Throws(BluePrintProcessorException::class)
116         fun generateResourceDataForAssignments(assignments: List<ResourceAssignment>): String {
117             val result: String
118             try {
119                 val mapper = ObjectMapper()
120                 val root: ObjectNode = mapper.createObjectNode()
121
122                 assignments.forEach {
123                     if (isNotEmpty(it.name) && it.property != null) {
124                         val rName = it.name
125                         val type = nullToEmpty(it.property?.type).toLowerCase()
126                         val value = useDefaultValueIfNull(it, rName)
127                         logger.info("Generating Resource name ($rName), type ($type), value ($value)")
128                         root.set(rName, value)
129                     }
130                 }
131                 result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)
132                 logger.info("Generated Resource Param Data ($result)")
133             } catch (e: Exception) {
134                 throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e)
135             }
136
137             return result
138         }
139
140         private fun useDefaultValueIfNull(resourceAssignment: ResourceAssignment, resourceAssignmentName: String): JsonNode {
141             if (resourceAssignment.property?.value == null) {
142                 val defaultValue = "\${$resourceAssignmentName}"
143                 return TextNode(defaultValue)
144             } else {
145                 return resourceAssignment.property!!.value!!
146             }
147         }
148
149         fun transformToRARuntimeService(blueprintRuntimeService: BluePrintRuntimeService<*>,
150                                         templateArtifactName: String): ResourceAssignmentRuntimeService {
151
152             val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(blueprintRuntimeService.id(),
153                     blueprintRuntimeService.bluePrintContext())
154             resourceAssignmentRuntimeService.createUniqueId(templateArtifactName)
155             resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap<String, JsonNode>)
156
157             return resourceAssignmentRuntimeService
158         }
159
160         @Throws(BluePrintProcessorException::class)
161         fun getPropertyType(raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String,
162                             propertyName: String): String {
163             lateinit var type: String
164             try {
165                 val dataTypeProps = checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties)
166
167                 val propertyDefinition = checkNotNull(dataTypeProps[propertyName])
168                 type = checkNotEmpty(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" }
169                 logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type)
170             } catch (e: Exception) {
171                 logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e")
172                 throw BluePrintProcessorException("${e.message}", e)
173             }
174             return type
175         }
176     }
177 }