Merge "PyExecutor ResourceResolution store/retrieve templates"
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / processor / RestResourceResolutionProcessor.kt
1 /*
2  *  Copyright © 2018 - 2020 IBM.
3  *  Modifications Copyright © 2017-2020 AT&T, Bell Canada
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.processor
19
20 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR
21 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
22 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
23 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
24 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
25 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceDomains
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
28 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
29 import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
30 import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage
31 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
32 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier
33 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
34 import org.slf4j.LoggerFactory
35 import org.springframework.beans.factory.config.ConfigurableBeanFactory
36 import org.springframework.context.annotation.Scope
37 import org.springframework.stereotype.Service
38
39 /**
40  * RestResourceResolutionProcessor
41  *
42  * @author Kapil Singal
43  */
44 @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest")
45 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
46 open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService) :
47     ResourceAssignmentProcessor() {
48
49     private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java)
50
51     override fun getName(): String {
52         return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
53     }
54
55     override suspend fun processNB(resourceAssignment: ResourceAssignment) {
56         try {
57             validate(resourceAssignment)
58
59             // Check if It has Input
60             if (!setFromInput(resourceAssignment)) {
61                 val dName = resourceAssignment.dictionaryName!!
62                 val dSource = resourceAssignment.dictionarySource!!
63                 val resourceDefinition = resourceDefinition(dName)
64
65                 /** Check Resource Assignment has the source definitions, If not get from Resource Definitions **/
66                 val resourceSource = resourceAssignment.dictionarySourceDefinition
67                     ?: resourceDefinition?.sources?.get(dSource)
68                     ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)")
69
70                 val resourceSourceProperties =
71                     checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " }
72
73                 val sourceProperties =
74                     JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java)
75
76                 val path = nullToEmpty(sourceProperties.path)
77                 val inputKeyMapping =
78                     checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" }
79                 val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping).toMutableMap()
80
81                 inputKeyMapping?.mapValues { raRuntimeService.getDictionaryStore(it.value) }
82                         ?.map { KeyIdentifier(it.key, it.value) }
83                         ?.let { resourceAssignment.keyIdentifiers.addAll(it) }
84
85                 // Resolving content Variables
86                 val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
87                 resourceSourceProperties["resolved-payload"] = JacksonUtils.jsonNode(payload)
88                 val urlPath =
89                     resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
90                 val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
91
92                 logger.info(
93                     "RestResource ($dSource) dictionary information: " +
94                             "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
95                 )
96                 val requestHeaders = sourceProperties.headers
97                 logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})")
98                 // Get the Rest Client Service
99                 val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties)
100
101                 val response = restClientService.exchangeResource(verb, urlPath, payload, requestHeaders.toMap())
102                 val responseStatusCode = response.status
103                 val responseBody = response.body
104                 val outputKeyMapping = sourceProperties.outputKeyMapping
105                 if (responseStatusCode in 200..299 && outputKeyMapping.isNullOrEmpty()) {
106                     logger.info("AS>> outputKeyMapping==null, will not populateResource")
107                 } else if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
108                     populateResource(resourceAssignment, sourceProperties, responseBody, path)
109                 } else {
110                     val errMsg =
111                         "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
112                     logger.warn(errMsg)
113                     throw BluePrintProcessorException(errMsg)
114                 }
115             }
116             // Check the value has populated for mandatory case
117             ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment)
118         } catch (e: BluePrintProcessorException) {
119             val errorMsg = "Failed to process REST resource resolution in template key ($resourceAssignment) assignments."
120             throw e.updateErrorMessage(ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg,
121                     "Wrong resource definition or resolution failed.")
122         } catch (e: Exception) {
123             ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message)
124             throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e)
125         }
126     }
127
128     fun blueprintWebClientService(
129         resourceAssignment: ResourceAssignment,
130         restResourceSource: RestResourceSource
131     ): BlueprintWebClientService {
132         return if (isNotEmpty(restResourceSource.endpointSelector)) {
133             val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!)
134             blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson)
135         } else {
136             blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!)
137         }
138     }
139
140     @Throws(BluePrintProcessorException::class)
141     private fun populateResource(
142         resourceAssignment: ResourceAssignment,
143         sourceProperties: RestResourceSource,
144         restResponse: String,
145         path: String
146     ) {
147         val dName = resourceAssignment.dictionaryName
148         val dSource = resourceAssignment.dictionarySource
149         val type = nullToEmpty(resourceAssignment.property?.type)
150         val metadata = resourceAssignment.property!!.metadata
151
152         val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) {
153             "failed to get output-key-mappings for $dName under $dSource properties"
154         }
155         logger.info("Response processing type ($type)")
156
157         val responseNode = checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) {
158             "Failed to find path ($path) in response ($restResponse)"
159         }
160
161         val valueToPrint = ResourceAssignmentUtils.getValueToLog(metadata, responseNode)
162         logger.info("populating value for output mapping ($outputKeyMapping), from json ($valueToPrint)")
163
164         val parsedResponseNode = ResourceAssignmentUtils.parseResponseNode(
165             responseNode, resourceAssignment,
166             raRuntimeService, outputKeyMapping
167         )
168
169         // Set the List of Complex Values
170         ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode)
171     }
172
173     @Throws(BluePrintProcessorException::class)
174     private fun validate(resourceAssignment: ResourceAssignment) {
175         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
176         checkNotEmpty(resourceAssignment.dictionaryName) {
177             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
178         }
179         checkNotEmpty(resourceAssignment.dictionarySource) {
180             "resource assignment dictionary source is not defined for template key (${resourceAssignment.name})"
181         }
182     }
183
184     override suspend fun recoverNB(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) {
185         raRuntimeService.getBluePrintError().addError(runtimeException.message!!)
186     }
187 }