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