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.BluePrintPropertiesService
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
29 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
30 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
31 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
32 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
33 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
34 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
35 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
36 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
37 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
38 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
39 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
40 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
41 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
42 import org.slf4j.LoggerFactory
43 import org.springframework.beans.factory.config.ConfigurableBeanFactory
44 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
45 import org.springframework.context.annotation.Scope
46 import org.springframework.stereotype.Component
48 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
49 @Component("component-remote-python-executor")
50 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
51 open class ComponentRemotePythonExecutor(
52 private val remoteScriptExecutionService: RemoteScriptExecutionService,
53 private var bluePrintPropertiesService: BluePrintPropertiesService
54 ) : AbstractComponentFunction() {
56 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
59 const val SELECTOR_CMD_EXEC = "blueprintsprocessor.remote-script-command"
60 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
61 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
62 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
64 const val INPUT_COMMAND = "command"
65 const val INPUT_PACKAGES = "packages"
66 const val DEFAULT_SELECTOR = "remote-python"
67 const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
68 const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
70 const val STEP_PREPARE_ENV = "prepare-env"
71 const val STEP_EXEC_CMD = "execute-command"
72 const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
73 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
74 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
75 const val ATTRIBUTE_RESPONSE_DATA = "response-data"
76 const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
77 const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
80 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
82 log.debug("Processing : $operationInputs")
84 val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
86 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
87 val blueprintName = bluePrintContext.name()
88 val blueprintVersion = bluePrintContext.version()
90 val operationAssignment: OperationAssignment = bluePrintContext
91 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
93 val artifactName: String = operationAssignment.implementation?.primary
94 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
96 val artifactDefinition =
97 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
99 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
101 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
103 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
105 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
106 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
107 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
109 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
111 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
112 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
113 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
115 val command = getOperationInput(INPUT_COMMAND).asText()
118 * Timeouts that are specific to the command executor.
119 * Note: the interface->input->timeout is the component level timeout.
121 val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
122 ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
123 val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
124 ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
126 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
127 if (args != null && args.isNotEmpty()) {
128 scriptCommand = scriptCommand.plus(" ").plus(args)
132 // Open GRPC Connection
133 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
134 remoteScriptExecutionService.init(endPointSelector.asText())
136 // Get endpoint from DSL
137 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
138 remoteScriptExecutionService.init(endPointSelectorJson)
141 // If packages are defined, then install in remote server
142 if (packages != null) {
143 val prepareEnvInput = PrepareRemoteEnvInput(
144 requestId = processId,
145 remoteIdentifier = RemoteIdentifier(
146 blueprintName = blueprintName,
147 blueprintVersion = blueprintVersion),
149 timeOut = envPrepTimeout.toLong()
152 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
153 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
154 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
155 val logsEnv = logs.toString().asJsonPrimitive()
156 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logsEnv)
158 if (prepareEnvOutput.status != StatusType.SUCCESS) {
159 val errorMessage = prepareEnvOutput.payload
160 setNodeOutputErrors(prepareEnvOutput.status.name,
167 setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(),
170 "".asJsonPrimitive(),
175 // set env preparation log to empty...
176 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
178 } catch (grpcEx: io.grpc.StatusRuntimeException) {
179 val grpcErrMsg = "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId)."
180 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
181 setNodeOutputErrors(status = grpcErrMsg, step = STEP_PREPARE_ENV, error = "${grpcEx.status}".asJsonPrimitive(), logging = isLogResponseEnabled)
182 log.error(grpcErrMsg, grpcEx)
184 } catch (e: Exception) {
185 val timeoutErrMsg = "Command executor failed during env. preparation.. timeout($envPrepTimeout) requestId ($processId)."
186 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, e.message.asJsonPrimitive())
187 setNodeOutputErrors(status = timeoutErrMsg, step = STEP_PREPARE_ENV, error = "${e.message}".asJsonPrimitive(), logging = isLogResponseEnabled)
188 log.error("Failed to process on remote executor requestId ($processId)", e)
189 addError(timeoutErrMsg)
191 // if Env preparation was successful, then proceed with command execution in this Env
192 if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
194 // Populate command execution properties and pass it to the remote server
195 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
197 val remoteExecutionInput = RemoteScriptExecutionInput(
198 requestId = processId,
199 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
200 command = scriptCommand,
201 properties = properties,
202 timeOut = implementation.timeout.toLong())
204 val remoteExecutionOutputDeferred = GlobalScope.async {
205 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
208 val remoteExecutionOutput = withTimeout(implementation.timeout * 1000L) {
209 remoteExecutionOutputDeferred.await()
212 checkNotNull(remoteExecutionOutput) {
213 "Error: Request-id $processId did not return a restul from remote command execution."
215 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
216 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
217 setNodeOutputErrors(remoteExecutionOutput.status.name,
220 remoteExecutionOutput.payload,
224 setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(),
227 remoteExecutionOutput.payload,
231 } catch (timeoutEx: TimeoutCancellationException) {
232 val timeoutErrMsg = "Command executor timed out executing after $executionTimeout seconds requestId ($processId)"
233 setNodeOutputErrors(status = timeoutErrMsg,
234 step = STEP_EXEC_CMD,
235 logs = "".asJsonPrimitive(),
236 error = "".asJsonPrimitive(),
237 logging = isLogResponseEnabled
239 log.error(timeoutErrMsg, timeoutEx)
240 } catch (grpcEx: io.grpc.StatusRuntimeException) {
241 val timeoutErrMsg = "Command executor timed out executing after $executionTimeout seconds requestId ($processId)"
242 setNodeOutputErrors(status = timeoutErrMsg,
243 step = STEP_EXEC_CMD,
244 logs = "".asJsonPrimitive(),
245 error = "".asJsonPrimitive(),
246 logging = isLogResponseEnabled
248 log.error("Command executor time out during GRPC call", grpcEx)
249 } catch (e: Exception) {
250 log.error("Failed to process on remote executor requestId ($processId)", e)
253 log.debug("Trying to close GRPC channel. request ($processId)")
254 remoteScriptExecutionService.close()
257 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
258 bluePrintRuntimeService.getBluePrintError()
259 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
262 private fun formatNestedJsonNode(node: JsonNode): String {
263 val sb = StringBuilder()
264 if (node.isValueNode) {
267 node.forEach { sb.append(" $it") }
273 * Utility function to set the output properties of the executor node
275 private fun setNodeOutputProperties(status: JsonNode, step: String, message: JsonNode, artifacts: JsonNode, logging: Boolean = true) {
276 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
277 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
278 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
281 log.info("Executor status : $step : $status")
282 log.info("Executor artifacts: $step : $artifacts")
283 log.info("Executor message : $step : $message")
288 * Utility function to set the output properties and errors of the executor node, in cas of errors
290 private fun setNodeOutputErrors(
293 logs: JsonNode = "N/A".asJsonPrimitive(),
295 logging: Boolean = true
297 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
298 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, logs)
299 setAttribute(ATTRIBUTE_RESPONSE_DATA, "N/A".asJsonPrimitive())
302 log.info("Executor status : $step : $status")
303 log.info("Executor message : $step : $error")
304 log.info("Executor logs : $step : $logs")
307 addError(status, step, error.toString())