1abac7f3de4eaaa0e40d30c5a8b74949015533a0
[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.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.getAsString
31 import org.onap.ccsdk.cds.controllerblueprints.core.getOptionalAsInt
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 processId: String
53     lateinit var workflowName: String
54     lateinit var stepName: String
55     lateinit var interfaceName: String
56     lateinit var operationName: String
57     lateinit var nodeTemplateName: String
58     var timeout: Int = 180
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         checkNotNull(bluePrintRuntimeService) { "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         val operationResolvedProperties = bluePrintRuntimeService
95             .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
96
97         this.operationInputs.putAll(operationResolvedProperties)
98
99         val timeout = this.operationInputs.getOptionalAsInt(BluePrintConstants.PROPERTY_CURRENT_TIMEOUT)
100         timeout?.let { this.timeout = timeout }
101
102         return executionRequest
103     }
104
105     override suspend fun prepareResponseNB(): ExecutionServiceOutput {
106         log.info("Preparing Response...")
107         executionServiceOutput.commonHeader = executionServiceInput.commonHeader
108         executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
109         var status = Status()
110         try {
111             // Resolve the Output Expression
112             val stepOutputs = bluePrintRuntimeService
113                 .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
114
115             val stepOutputData = StepData().apply {
116                 name = stepName
117                 properties = stepOutputs
118             }
119             executionServiceOutput.stepData = stepOutputData
120             // Set the Default Step Status
121             status.eventType = EventType.EVENT_COMPONENT_EXECUTED.name
122         } catch (e: Exception) {
123             status.message = BluePrintConstants.STATUS_FAILURE
124             status.eventType = EventType.EVENT_COMPONENT_FAILURE.name
125         }
126         executionServiceOutput.status = status
127         return this.executionServiceOutput
128     }
129
130     override suspend fun applyNB(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
131         try {
132             prepareRequestNB(executionServiceInput)
133             withTimeout((timeout * 1000).toLong()) {
134                 processNB(executionServiceInput)
135             }
136         } catch (runtimeException: RuntimeException) {
137             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
138             recoverNB(runtimeException, executionServiceInput)
139         }
140         return prepareResponseNB()
141     }
142
143     fun getOperationInput(key: String): JsonNode {
144         return operationInputs[key]
145             ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
146     }
147
148     fun getOptionalOperationInput(key: String): JsonNode? {
149         return operationInputs[key]
150     }
151
152     fun setAttribute(key: String, value: JsonNode) {
153         bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, key, value)
154     }
155
156     fun addError(type: String, name: String, error: String) {
157         bluePrintRuntimeService.getBluePrintError().addError(type, name, error)
158     }
159
160     fun addError(error: String) {
161         bluePrintRuntimeService.getBluePrintError().addError(error)
162     }
163
164     /**
165      * Get Execution Input Payload data
166      */
167     fun requestPayload(): JsonNode? {
168         return executionServiceInput.payload
169     }
170
171     /**
172      * Get Execution Input payload action property with [expression]
173      * ex: requestPayloadActionProperty("data") will look for path "payload/<action-name>-request/data"
174      */
175     fun requestPayloadActionProperty(expression: String?): JsonNode? {
176         val requestExpression = if (expression.isNullOrBlank()) {
177             "$workflowName-request"
178         } else {
179             "$workflowName-request.$expression"
180         }
181         return executionServiceInput.payload.jsonPathParse(".$requestExpression")
182     }
183
184     fun artifactContent(artifactName: String): String {
185         return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
186     }
187
188     suspend fun mashTemplateNData(artifactName: String, json: String): String {
189         val content = artifactContent(artifactName)
190         return BluePrintVelocityTemplateService.generateContent(content, json)
191     }
192
193     suspend fun readLinesFromArtifact(artifactName: String): List<String> {
194         val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
195         val file = normalizedFile(bluePrintRuntimeService.bluePrintContext().rootPath, artifactDefinition.file)
196         return file.readNBLines()
197     }
198 }