3e329d7f5884276e60b6fe87033fc4feccb3af2b
[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.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                 processNB(executionServiceInput)
138             }
139         } catch (runtimeException: RuntimeException) {
140             log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
141             recoverNB(runtimeException, executionServiceInput)
142         }
143         return prepareResponseNB()
144     }
145
146     fun getOperationInput(key: String): JsonNode {
147         return operationInputs[key]
148             ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
149     }
150
151     fun getOptionalOperationInput(key: String): JsonNode? {
152         return operationInputs[key]
153     }
154
155     fun setAttribute(key: String, value: JsonNode) {
156         bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, key, value)
157     }
158
159     fun addError(type: String, name: String, error: String) {
160         bluePrintRuntimeService.getBluePrintError().addError(type, name, error)
161     }
162
163     fun addError(error: String) {
164         bluePrintRuntimeService.getBluePrintError().addError(error)
165     }
166
167     /**
168      * Get Execution Input Payload data
169      */
170     fun requestPayload(): JsonNode? {
171         return executionServiceInput.payload
172     }
173
174     /**
175      * Get Execution Input payload action property with [expression]
176      * ex: requestPayloadActionProperty("data") will look for path "payload/<action-name>-request/data"
177      */
178     fun requestPayloadActionProperty(expression: String?): JsonNode? {
179         val requestExpression = if (expression.isNullOrBlank()) {
180             "$workflowName-request"
181         } else {
182             "$workflowName-request.$expression"
183         }
184         return executionServiceInput.payload.jsonPathParse(".$requestExpression")
185     }
186
187     suspend fun artifactContent(artifactName: String): String {
188         return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
189     }
190
191     suspend fun relationshipProperty(relationshipName: String, propertyName: String): JsonNode {
192         return bluePrintRuntimeService.resolveRelationshipTemplateProperties(relationshipName).get(propertyName)
193             ?: throw BluePrintProcessorException("failed to get relationship($relationshipName) property($propertyName)")
194     }
195
196     suspend fun mashTemplateNData(artifactName: String, json: String): String {
197         val content = artifactContent(artifactName)
198         return BluePrintVelocityTemplateService.generateContent(content, json)
199     }
200
201     suspend fun readLinesFromArtifact(artifactName: String): List<String> {
202         val artifactDefinition =
203             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
204         val file = normalizedFile(bluePrintRuntimeService.bluePrintContext().rootPath, artifactDefinition.file)
205         return file.readNBLines()
206     }
207 }