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 kotlinx.coroutines.GlobalScope
21 import kotlinx.coroutines.TimeoutCancellationException
22 import kotlinx.coroutines.async
23 import kotlinx.coroutines.withTimeout
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
29 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
30 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
31 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
32 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
33 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
34 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
35 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
36 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
37 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
38 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
39 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
40 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
41 import org.slf4j.LoggerFactory
42 import org.springframework.beans.factory.config.ConfigurableBeanFactory
43 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
44 import org.springframework.context.annotation.Scope
45 import org.springframework.stereotype.Component
47 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
48 @Component("component-remote-python-executor")
49 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
50 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService) : AbstractComponentFunction() {
52 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
55 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
56 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
57 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
58 const val INPUT_COMMAND = "command"
59 const val INPUT_PACKAGES = "packages"
60 const val DEFAULT_SELECTOR = "remote-python"
62 const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
63 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
64 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
65 const val ATTRIBUTE_RESPONSE_DATA = "response-data"
68 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
70 log.debug("Processing : $operationInputs")
72 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
73 val blueprintName = bluePrintContext.name()
74 val blueprintVersion = bluePrintContext.version()
76 val operationAssignment: OperationAssignment = bluePrintContext
77 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
79 val artifactName: String = operationAssignment.implementation?.primary
80 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
82 val artifactDefinition =
83 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
85 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
87 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
89 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
91 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
92 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
93 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
95 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
97 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
98 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
99 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
101 val command = getOperationInput(INPUT_COMMAND).asText()
102 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
103 if (args != null && args.isNotEmpty()) {
104 scriptCommand = scriptCommand.plus(" ").plus(args)
108 // Open GRPC Connection
109 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
110 remoteScriptExecutionService.init(endPointSelector.asText())
112 // Get endpoint from DSL
113 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
114 remoteScriptExecutionService.init(endPointSelectorJson)
117 // If packages are defined, then install in remote server
118 if (packages != null) {
119 val prepareEnvInput = PrepareRemoteEnvInput(
120 requestId = processId,
121 remoteIdentifier = RemoteIdentifier(
122 blueprintName = blueprintName,
123 blueprintVersion = blueprintVersion
127 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
128 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
129 val logs = prepareEnvOutput.response
130 val logsEnv = logs.toString().asJsonPrimitive()
131 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logsEnv)
133 if (prepareEnvOutput.status != StatusType.SUCCESS) {
134 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
135 setNodeOutputErrors(prepareEnvOutput.status.name, logsEnv)
137 setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(), logsEnv, "".asJsonPrimitive())
141 // if Env preparation was successful, then proceed with command execution in this Env
142 if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
143 // Populate command execution properties and pass it to the remote server
144 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
146 val remoteExecutionInput = RemoteScriptExecutionInput(
147 requestId = processId,
148 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
149 command = scriptCommand,
150 properties = properties,
151 timeOut = implementation.timeout.toLong())
153 val remoteExecutionOutputDeferred = GlobalScope.async {
154 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
157 val remoteExecutionOutput = withTimeout(implementation.timeout * 1000L) {
158 remoteExecutionOutputDeferred.await()
161 checkNotNull(remoteExecutionOutput) {
162 "Error: Request-id $processId did not return a restul from remote command execution."
164 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
165 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
166 setNodeOutputErrors(remoteExecutionOutput.status.name, logs, remoteExecutionOutput.payload)
168 setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
169 remoteExecutionOutput.payload)
172 } catch (timeoutEx: TimeoutCancellationException) {
173 setNodeOutputErrors(status = "Command executor timed out after ${implementation.timeout} seconds", message = "".asJsonPrimitive())
174 log.error("Command executor timed out after ${implementation.timeout} seconds", timeoutEx)
175 } catch (grpcEx: io.grpc.StatusRuntimeException) {
176 setNodeOutputErrors(status = "Command executor timed out in GRPC call", message = "${grpcEx.status}".asJsonPrimitive())
177 log.error("Command executor time out during GRPC call", grpcEx)
179 remoteScriptExecutionService.close()
183 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
184 bluePrintRuntimeService.getBluePrintError()
185 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
188 private fun formatNestedJsonNode(node: JsonNode): String {
189 val sb = StringBuilder()
190 if (node.isValueNode) {
193 node.forEach { sb.append(" $it") }
199 * Utility function to set the output properties of the executor node
201 private fun setNodeOutputProperties(status: JsonNode, message: JsonNode, artifacts: JsonNode) {
202 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
203 log.info("Executor status : $status")
204 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
205 log.info("Executor artifacts: $artifacts")
206 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
207 log.info("Executor message : $message")
211 * Utility function to set the output properties and errors of the executor node, in cas of errors
213 private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive()) {
214 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
215 log.info("Executor status : $status")
216 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
217 log.info("Executor message : $message")
218 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
219 log.info("Executor artifacts: $artifacts")
221 addError(status, ATTRIBUTE_EXEC_CMD_LOG, message.toString())