2 * Copyright © 2019 IBM.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
19 import com.fasterxml.jackson.databind.JsonNode
20 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
21 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
22 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
23 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
25 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
26 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
27 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
28 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
29 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
30 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
31 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
32 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
33 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
34 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
35 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
36 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
37 import org.slf4j.LoggerFactory
38 import org.springframework.beans.factory.config.ConfigurableBeanFactory
39 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
40 import org.springframework.context.annotation.Scope
41 import org.springframework.stereotype.Component
43 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
44 @Component("component-remote-python-executor")
45 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
46 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService) : AbstractComponentFunction() {
48 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
51 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
52 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
53 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
54 const val INPUT_COMMAND = "command"
55 const val INPUT_PACKAGES = "packages"
56 const val DEFAULT_SELECTOR = "remote-python"
58 const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
59 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
60 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
61 const val ATTRIBUTE_RESPONSE_DATA = "response-data"
64 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
66 log.debug("Processing : $operationInputs")
68 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
69 val blueprintName = bluePrintContext.name()
70 val blueprintVersion = bluePrintContext.version()
72 val operationAssignment: OperationAssignment = bluePrintContext
73 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
75 val artifactName: String = operationAssignment.implementation?.primary
76 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
78 val artifactDefinition =
79 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
81 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
83 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
85 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
87 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
88 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
89 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
91 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
93 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
94 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
95 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
97 val command = getOperationInput(INPUT_COMMAND).asText()
98 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
99 if (args != null && args.isNotEmpty()) {
100 scriptCommand = scriptCommand.plus(" ").plus(args)
104 // Open GRPC Connection
105 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
106 remoteScriptExecutionService.init(endPointSelector.asText())
108 // Get endpoint from DSL
109 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
110 remoteScriptExecutionService.init(endPointSelectorJson)
113 // If packages are defined, then install in remote server
114 if (packages != null) {
115 val prepareEnvInput = PrepareRemoteEnvInput(
116 requestId = processId,
117 remoteIdentifier = RemoteIdentifier(
118 blueprintName = blueprintName,
119 blueprintVersion = blueprintVersion
123 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
124 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
125 val logs = prepareEnvOutput.response
126 val logsEnv = logs.toString().asJsonPrimitive()
127 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logsEnv)
129 if (prepareEnvOutput.status != StatusType.SUCCESS) {
130 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
131 setNodeOutputErrors(prepareEnvOutput.status.name, logsEnv)
133 setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(), logsEnv, "".asJsonPrimitive())
137 // if Env preparation was successful, then proceed with command execution in this Env
138 if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
139 // Populate command execution properties and pass it to the remote server
140 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
142 val remoteExecutionInput = RemoteScriptExecutionInput(
143 requestId = processId,
144 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
145 command = scriptCommand,
146 properties = properties
148 val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
150 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
151 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
152 setNodeOutputErrors(remoteExecutionOutput.status.name, logs, remoteExecutionOutput.payload)
154 setNodeOutputProperties(
155 remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
156 remoteExecutionOutput.payload
160 } catch (e: Exception) {
161 log.error("Failed to process on remote executor", e)
163 remoteScriptExecutionService.close()
167 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
168 bluePrintRuntimeService.getBluePrintError()
169 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
172 private fun formatNestedJsonNode(node: JsonNode): String {
173 val sb = StringBuilder()
174 if (node.isValueNode) {
177 node.forEach { sb.append(" $it") }
183 * Utility function to set the output properties of the executor node
185 private fun setNodeOutputProperties(status: JsonNode, message: JsonNode, artifacts: JsonNode) {
186 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
187 log.info("Executor status : $status")
188 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
189 log.info("Executor artifacts: $artifacts")
190 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
191 log.info("Executor message : $message")
195 * Utility function to set the output properties and errors of the executor node, in cas of errors
197 private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive()) {
198 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
199 log.info("Executor status : $status")
200 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
201 log.info("Executor message : $message")
202 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
203 log.info("Executor artifacts: $artifacts")
205 addError(status, ATTRIBUTE_EXEC_CMD_LOG, message.toString())