Merge "Removed logging of configuration snapshot as it might leak sensitive data...
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / services / execution-service / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / services / execution / AbstractComponentFunction.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.services.execution
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import kotlinx.coroutines.withTimeout
22 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
23 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData
26 import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
28 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
29 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
30 import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
31 import org.onap.ccsdk.cds.controllerblueprints.core.getAsString
32 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
33 import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
34 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
35 import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines
36 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
37 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
38 import org.slf4j.LoggerFactory
39
40 /**
41  * AbstractComponentFunction
42  * @author Brinda Santh
43  */
44 abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServiceInput, ExecutionServiceOutput> {
45
46     @Transient
47     private val log = LoggerFactory.getLogger(AbstractComponentFunction::class.java)
48
49     lateinit var executionServiceInput: ExecutionServiceInput
50     var executionServiceOutput = ExecutionServiceOutput()
51     lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
52     lateinit var implementation: Implementation
53     lateinit var processId: String
54     lateinit var workflowName: String
55     lateinit var stepName: String
56     lateinit var interfaceName: String
57     lateinit var operationName: String
58     lateinit var nodeTemplateName: String
59     var operationInputs: MutableMap<String, JsonNode> = hashMapOf()
60
61     override fun getName(): String {
62         return stepName
63     }
64
65     override suspend fun prepareRequestNB(executionRequest: ExecutionServiceInput): ExecutionServiceInput {
66         check(this::bluePrintRuntimeService.isInitialized) { "failed to prepare blueprint runtime" }
67         checkNotNull(executionRequest.stepData) { "failed to get step info" }
68
69         // Get the Step Name and Step Inputs
70         this.stepName = executionRequest.stepData!!.name
71         this.operationInputs = executionRequest.stepData!!.properties
72
73         checkNotEmpty(stepName) { "failed to get step name from step data" }
74
75         this.executionServiceInput = executionRequest
76
77         processId = executionRequest.commonHeader.requestId
78         check(processId.isNotEmpty()) { "couldn't get process id for step($stepName)" }
79
80         workflowName = executionRequest.actionIdentifiers.actionName
81         check(workflowName.isNotEmpty()) { "couldn't get action name for step($stepName)" }
82
83         log.info("preparing request id($processId) for workflow($workflowName) step($stepName)")
84
85         nodeTemplateName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE)
86         check(nodeTemplateName.isNotEmpty()) { "couldn't get NodeTemplate name for step($stepName)" }
87
88         interfaceName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_INTERFACE)
89         check(interfaceName.isNotEmpty()) { "couldn't get Interface name for step($stepName)" }
90
91         operationName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_OPERATION)
92         check(operationName.isNotEmpty()) { "couldn't get Operation name for step($stepName)" }
93
94         /** Get the Implementation Details */
95         implementation = bluePrintRuntimeService.bluePrintContext()
96             .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
97             ?: Implementation()
98         check(this::implementation.isInitialized) { "failed to prepare implementation" }
99
100         val operationResolvedProperties = bluePrintRuntimeService
101             .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
102
103         this.operationInputs.putAll(operationResolvedProperties)
104
105         return executionRequest
106     }
107
108     override suspend fun prepareResponseNB(): ExecutionServiceOutput {
109         log.info("Preparing Response...")
110         executionServiceOutput.commonHeader = executionServiceInput.commonHeader
111         executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
112         val status = Status()
113         try {
114             // Resolve the Output Expression
115             val stepOutputs = bluePrintRuntimeService
116                 .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
117
118             val stepOutputData = StepData().apply {
119                 name = stepName
120                 properties = stepOutputs
121             }
122             executionServiceOutput.stepData = stepOutputData
123             // Set the Default Step Status
124             status.eventType = EventType.EVENT_COMPONENT_EXECUTED.name
125         } catch (e: Exception) {
126             status.message = BluePrintConstants.STATUS_FAILURE
127             status.eventType = EventType.EVENT_COMPONENT_FAILURE.name
128         }
129         executionServiceOutput.status = status
130         return this.executionServiceOutput
131     }
132
133     override suspend fun applyNB(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
134         try {
135             prepareRequestNB(executionServiceInput)
136             withTimeout((implementation.timeout * 1000).toLong()) {
137                 log.debug("DEBUG::: AbstractComponentFunction.withTimeout section ${implementation.timeout} seconds")
138                 processNB(executionServiceInput)
139             }
140         } catch (runtimeException: RuntimeException) {
141             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
142             recoverNB(runtimeException, executionServiceInput)
143         }
144         return prepareResponseNB()
145     }
146
147     fun getOperationInput(key: String): JsonNode {
148         return operationInputs[key]
149             ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
150     }
151
152     fun getOptionalOperationInput(key: String): JsonNode? {
153         return operationInputs[key]
154     }
155
156     fun setAttribute(key: String, value: JsonNode) {
157         bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, key, value)
158     }
159
160     fun addError(type: String, name: String, error: String) {
161         bluePrintRuntimeService.getBluePrintError().addError(type, name, error)
162     }
163
164     fun addError(error: String) {
165         bluePrintRuntimeService.getBluePrintError().addError(error)
166     }
167
168     /**
169      * Get Execution Input Payload data
170      */
171     fun requestPayload(): JsonNode? {
172         return executionServiceInput.payload
173     }
174
175     /**
176      * Get Execution Input payload action property with [expression]
177      * ex: requestPayloadActionProperty("data") will look for path "payload/<action-name>-request/data"
178      */
179     fun requestPayloadActionProperty(expression: String?): JsonNode? {
180         val requestExpression = if (expression.isNullOrBlank()) {
181             "$workflowName-request"
182         } else {
183             "$workflowName-request.$expression"
184         }
185         return executionServiceInput.payload.jsonPathParse(".$requestExpression")
186     }
187
188     suspend fun artifactContent(artifactName: String): String {
189         return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
190     }
191
192     suspend fun relationshipProperty(relationshipName: String, propertyName: String): JsonNode {
193         return bluePrintRuntimeService.resolveRelationshipTemplateProperties(relationshipName).get(propertyName)
194             ?: throw BluePrintProcessorException("failed to get relationship($relationshipName) property($propertyName)")
195     }
196
197     suspend fun mashTemplateNData(artifactName: String, json: String): String {
198         val content = artifactContent(artifactName)
199         return BluePrintVelocityTemplateService.generateContent(content, json)
200     }
201
202     suspend fun readLinesFromArtifact(artifactName: String): List<String> {
203         val artifactDefinition =
204             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
205         val file = normalizedFile(bluePrintRuntimeService.bluePrintContext().rootPath, artifactDefinition.file)
206         return file.readNBLines()
207     }
208 }