2 * Copyright © 2017-2018 AT&T Intellectual Property.
3 * Modifications Copyright © 2019 IBM.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.services.execution
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.blueprintsprocessor.core.cluster.executeWithLock
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.CDS_LOCK_GROUP
29 import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
30 import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants
31 import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException
32 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
33 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
34 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
35 import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
36 import org.onap.ccsdk.cds.controllerblueprints.core.getAsString
37 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
38 import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
39 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
40 import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines
41 import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService
42 import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService
43 import org.slf4j.LoggerFactory
46 * AbstractComponentFunction
47 * @author Brinda Santh
49 abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServiceInput, ExecutionServiceOutput> {
52 private val log = LoggerFactory.getLogger(AbstractComponentFunction::class.java)
54 lateinit var executionServiceInput: ExecutionServiceInput
55 var executionServiceOutput = ExecutionServiceOutput()
56 lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*>
57 lateinit var bluePrintClusterService: BlueprintClusterService
58 lateinit var implementation: Implementation
59 lateinit var processId: String
60 lateinit var workflowName: String
61 lateinit var stepName: String
62 lateinit var interfaceName: String
63 lateinit var operationName: String
64 lateinit var nodeTemplateName: String
65 var operationInputs: MutableMap<String, JsonNode> = hashMapOf()
67 override fun getName(): String {
71 override suspend fun prepareRequestNB(executionRequest: ExecutionServiceInput): ExecutionServiceInput {
72 check(this::bluePrintRuntimeService.isInitialized) { "failed to prepare blueprint runtime" }
73 checkNotNull(executionRequest.stepData) { "failed to get step info" }
75 // Get the Step Name and Step Inputs
76 this.stepName = executionRequest.stepData!!.name
77 this.operationInputs = executionRequest.stepData!!.properties
79 checkNotEmpty(stepName) { "failed to get step name from step data" }
81 this.executionServiceInput = executionRequest
83 processId = executionRequest.commonHeader.requestId
84 check(processId.isNotEmpty()) { "couldn't get process id for step($stepName)" }
86 workflowName = executionRequest.actionIdentifiers.actionName
87 check(workflowName.isNotEmpty()) { "couldn't get action name for step($stepName)" }
89 log.info("preparing request id($processId) for workflow($workflowName) step($stepName)")
91 nodeTemplateName = this.operationInputs.getAsString(BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE)
92 check(nodeTemplateName.isNotEmpty()) { "couldn't get NodeTemplate name for step($stepName)" }
94 interfaceName = this.operationInputs.getAsString(BlueprintConstants.PROPERTY_CURRENT_INTERFACE)
95 check(interfaceName.isNotEmpty()) { "couldn't get Interface name for step($stepName)" }
97 operationName = this.operationInputs.getAsString(BlueprintConstants.PROPERTY_CURRENT_OPERATION)
98 check(operationName.isNotEmpty()) { "couldn't get Operation name for step($stepName)" }
100 /** Get the Implementation Details */
101 implementation = bluePrintRuntimeService.bluePrintContext()
102 .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
105 /** Resolve and validate lock properties */
106 implementation.lock?.apply {
107 val resolvedValues = bluePrintRuntimeService.resolvePropertyAssignments(
108 BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE,
110 mutableMapOf("key" to this.key, "acquireTimeout" to this.acquireTimeout)
112 this.key = resolvedValues["key"] ?: "".asJsonType()
113 this.acquireTimeout = resolvedValues["acquireTimeout"] ?: "".asJsonType()
115 checkNotBlank(this.key.textValue()) { "Failed to resolve lock key" }
116 check(this.acquireTimeout.isInt && this.acquireTimeout.intValue() >= 0) {
117 "Failed to resolve lock acquireTimeout - must be a positive integer"
121 check(this::implementation.isInitialized) { "failed to prepare implementation" }
123 val operationResolvedProperties = bluePrintRuntimeService
124 .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
126 this.operationInputs.putAll(operationResolvedProperties)
128 return executionRequest
131 override suspend fun prepareResponseNB(): ExecutionServiceOutput {
132 log.info("Preparing Response...")
133 executionServiceOutput.commonHeader = executionServiceInput.commonHeader
134 executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
135 val status = Status()
137 // Resolve the Output Expression
138 val stepOutputs = bluePrintRuntimeService
139 .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
141 val stepOutputData = StepData().apply {
143 properties = stepOutputs
145 executionServiceOutput.stepData = stepOutputData
146 // Set the Default Step Status
147 status.eventType = EventType.EVENT_COMPONENT_EXECUTED.name
148 } catch (e: Exception) {
149 status.message = BlueprintConstants.STATUS_FAILURE
150 status.eventType = EventType.EVENT_COMPONENT_FAILURE.name
152 executionServiceOutput.status = status
153 return this.executionServiceOutput
156 override suspend fun applyNB(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
158 prepareRequestNB(executionServiceInput)
159 implementation.lock?.let {
160 bluePrintClusterService.clusterLock("${it.key.textValue()}@$CDS_LOCK_GROUP")
161 .executeWithLock(it.acquireTimeout.intValue().times(1000).toLong()) {
162 applyNBWithTimeout(executionServiceInput)
164 } ?: applyNBWithTimeout(executionServiceInput)
165 } catch (runtimeException: RuntimeException) {
166 log.error("failed in ${getName()} : ${runtimeException.message}", runtimeException)
167 recoverNB(runtimeException, executionServiceInput)
169 return prepareResponseNB()
172 private suspend fun applyNBWithTimeout(executionServiceInput: ExecutionServiceInput) =
173 withTimeout((implementation.timeout * 1000).toLong()) {
175 "DEBUG::: AbstractComponentFunction.withTimeout " +
176 "section ${implementation.timeout} seconds"
178 processNB(executionServiceInput)
181 fun getOperationInput(key: String): JsonNode {
182 return operationInputs[key]
183 ?: throw BlueprintProcessorException("couldn't get the operation input($key) value.")
186 fun getOptionalOperationInput(key: String): JsonNode? {
187 return operationInputs[key]
190 fun setAttribute(key: String, value: JsonNode) {
191 bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, key, value)
194 fun addError(type: String, name: String, error: String) {
195 bluePrintRuntimeService.getBlueprintError().addError(type, name, error)
198 fun addError(error: String) {
199 bluePrintRuntimeService.getBlueprintError().addError(error)
203 * Get Execution Input Payload data
205 fun requestPayload(): JsonNode? {
206 return executionServiceInput.payload
210 * Get Execution Input payload action property with [expression]
211 * ex: requestPayloadActionProperty("data") will look for path "payload/<action-name>-request/data"
213 fun requestPayloadActionProperty(expression: String?): JsonNode? {
214 val requestExpression = if (expression.isNullOrBlank()) {
215 "$workflowName-request"
217 "$workflowName-request.$expression"
219 return executionServiceInput.payload.jsonPathParse(".$requestExpression")
222 suspend fun artifactContent(artifactName: String): String {
223 return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
226 suspend fun relationshipProperty(relationshipName: String, propertyName: String): JsonNode {
227 return bluePrintRuntimeService.resolveRelationshipTemplateProperties(relationshipName).get(propertyName)
228 ?: throw BlueprintProcessorException("failed to get relationship($relationshipName) property($propertyName)")
231 suspend fun mashTemplateNData(artifactName: String, json: String): String {
232 val content = artifactContent(artifactName)
233 return BlueprintVelocityTemplateService.generateContent(content, json)
236 suspend fun readLinesFromArtifact(artifactName: String): List<String> {
237 val artifactDefinition =
238 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
239 val file = normalizedFile(bluePrintRuntimeService.bluePrintContext().rootPath, artifactDefinition.file)
240 return file.readNBLines()