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