CCSDK-3531 improve cmd-exec returned err msg
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / python-executor / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / python / executor / ComponentRemotePythonExecutor.kt
1 /*
2  *  Copyright Â© 2019 IBM.
3  *  Modifications Copyright © 2020 Bell Canada.
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.functions.python.executor
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.google.protobuf.ByteString
22 import io.grpc.Status
23 import io.micrometer.core.instrument.Tag
24 import io.micrometer.core.instrument.Timer
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
29 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
30 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionOutput
31 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptUploadBlueprintInput
32 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
33 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository
34 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
35 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
36 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
37 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
38 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
39 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
40 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
41 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
42 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
43 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
44 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
45 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
46 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
47 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
48 import org.slf4j.LoggerFactory
49 import org.springframework.beans.factory.config.ConfigurableBeanFactory
50 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
51 import org.springframework.context.annotation.Scope
52 import org.springframework.stereotype.Component
53 import java.io.File
54
55 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
56 @Component("component-remote-python-executor")
57 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
58 open class ComponentRemotePythonExecutor(
59     private val remoteScriptExecutionService: RemoteScriptExecutionService,
60     private val bluePrintPropertiesService: BluePrintPropertiesService,
61     private val blueprintModelRepository: BlueprintModelRepository
62 ) : AbstractComponentFunction() {
63
64     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
65
66     companion object {
67
68         const val SELECTOR_CMD_EXEC = "blueprintsprocessor.remote-script-command"
69         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
70         const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
71         const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
72
73         const val INPUT_COMMAND = "command"
74         const val INPUT_PACKAGES = "packages"
75         const val DEFAULT_SELECTOR = "remote-python"
76         const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
77         const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
78
79         const val STEP_PREPARE_ENV = "prepare-env"
80         const val STEP_EXEC_CMD = "execute-command"
81         const val STEP_UPLOAD_CBA = "upload-cba"
82         const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
83         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
84         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
85         const val ATTRIBUTE_RESPONSE_DATA = "response-data"
86         const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
87         const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
88         const val DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC = 30
89         // Prometheus metrics counters
90         const val CDS_BP_CE_GRPC_ERROR_TOTAL = "cds_bp_ce_grpc_error_total"
91         const val CDS_BP_CE_TIMEOUT_ERROR_TOTAL = "cds_bp_ce_timeout_error_total"
92         const val CDS_BP_CE_EXECUTION_DURATION_SECONDS = "cds_bp_ce_execution_duration_seconds"
93     }
94
95     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
96
97         log.debug("Processing : $operationInputs")
98
99         val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
100
101         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
102         val blueprintName = bluePrintContext.name()
103         val blueprintVersion = bluePrintContext.version()
104
105         // fetch the template (plus cba bindata) from repository
106         val cbaModel = blueprintModelRepository.findByArtifactNameAndArtifactVersion(blueprintName, blueprintVersion)
107         val blueprintUUID = cbaModel?.id!!
108         val cbaBinData = ByteString.copyFrom(cbaModel?.blueprintModelContent?.content)
109         val archiveType = cbaModel?.blueprintModelContent?.contentType // TODO: should be enum
110         val remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion, blueprintUUID = blueprintUUID)
111         val originatorId = executionServiceInput.commonHeader.originatorId
112         val subRequestId = executionServiceInput.commonHeader.subRequestId
113         val requestId = processId
114
115         val pythonScript = getScriptFile()
116         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
117
118         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
119         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
120         var packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
121
122         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
123         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
124             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
125
126         val command = getOperationInput(INPUT_COMMAND).asText()
127         val cbaNameVerUuid = "blueprintName($blueprintName) blueprintVersion($blueprintVersion) blueprintUUID($blueprintUUID)"
128
129         /**
130          * Timeouts that are specific to the command executor.
131          * Note: the interface->input->timeout is the component level timeout.
132          */
133         val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
134             ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
135         val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
136             ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
137
138         // component level timeout should be => env_prep_timeout + execution_timeout
139         val timeout = implementation.timeout
140
141         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
142         if (args != null && args.isNotEmpty()) {
143             scriptCommand = scriptCommand.plus(" ").plus(args)
144         }
145
146         try {
147             // Open GRPC Connection
148             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
149                 remoteScriptExecutionService.init(endPointSelector.asText())
150             } else {
151                 // Get endpoint from DSL
152                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
153                 remoteScriptExecutionService.init(endPointSelectorJson)
154             }
155
156             // If packages are defined, then install in remote server
157             if (packages == null) {
158                 // set env preparation log to empty...
159                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
160                 packages = mutableListOf<Object>().asJsonType()
161             }
162             prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
163             // in cases where the exception is caught in BP side due to timeout, we do not have `err_msg` returned by cmd-exec (inside `payload`),
164             // hence `artifact` field will be empty
165         } catch (grpcEx: io.grpc.StatusRuntimeException) {
166             val errorType = if (grpcEx.status.code == Status.DEADLINE_EXCEEDED.code) CDS_BP_CE_TIMEOUT_ERROR_TOTAL else CDS_BP_CE_GRPC_ERROR_TOTAL
167             meterRegistry.counter(errorType, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
168
169             val componentLevelWarningMsg = if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
170             val grpcErrMsg = "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
171             // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
172             // set prepare-env-log to the error msg, and cmd-exec-log to empty
173             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
174             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
175             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
176             log.error(grpcErrMsg, grpcEx)
177         } catch (e: Exception) {
178             meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
179
180             val catchallErrMsg = "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
181             // no environment prepare log from executor in case of timeout (as cmd-exec side hasn't finished to transfer output), set it to error msg. Execution logs is empty.
182             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
183             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
184             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
185             log.error(catchallErrMsg, e)
186         }
187         // if Env preparation was successful, then proceed with command execution in this Env
188         if (noBlueprintErrors()) {
189             try {
190                 // Populate command execution properties and pass it to the remote server
191                 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
192
193                 val remoteExecutionInput = RemoteScriptExecutionInput(
194                     originatorId = executionServiceInput.commonHeader.originatorId,
195                     requestId = processId,
196                     subRequestId = executionServiceInput.commonHeader.subRequestId,
197                     remoteIdentifier = remoteIdentifier,
198                     command = scriptCommand,
199                     properties = properties,
200                     timeOut = executionTimeout.toLong()
201                 )
202
203                 val exeCmdTimer = Timer.start()
204                 val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
205                 exeCmdTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())))
206
207                 checkNotNull(remoteExecutionOutput) {
208                     "Error: Request-id $processId did not return a result from remote command execution."
209                 }
210                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
211                 val returnedPayload = remoteExecutionOutput.payload
212                 val returnedErrMsg = remoteExecutionOutput.errMsg
213                 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
214                 // It would contain `err_msg` key. It is valid to return it.
215                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
216                     setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
217                     // check if the payload is set (in case user Python script handles the error and sets the payload to return
218                     val retErrMsg: String = if (returnedErrMsg.isNullOrEmpty()) "cmd-exec has failed, please see cmd-exec log for more details."
219                     else "cmd-exec failed and returned: $returnedErrMsg"
220                     addError(StatusType.FAILURE.name, STEP_EXEC_CMD, retErrMsg)
221                 } else {
222                     setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
223                 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
224             } catch (grpcEx: io.grpc.StatusRuntimeException) {
225                 val errorType = if (grpcEx.status.code == Status.DEADLINE_EXCEEDED.code) CDS_BP_CE_TIMEOUT_ERROR_TOTAL else CDS_BP_CE_GRPC_ERROR_TOTAL
226                 meterRegistry.counter(errorType, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())).increment()
227
228                 val componentLevelWarningMsg =
229                     if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
230                 val timeoutErrMsg =
231                     "Command executor timed out executing after $executionTimeout seconds requestId ($processId). $componentLevelWarningMsg grpcErr: ${grpcEx.status}"
232                 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonType(), logging = isLogResponseEnabled)
233                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
234                 log.error(timeoutErrMsg, grpcEx)
235             } catch (e: Exception) {
236                 meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())).increment()
237                 val catchAllErrMsg = "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
238                 setNodeOutputErrors(STEP_PREPARE_ENV, listOf(catchAllErrMsg).asJsonType(), logging = isLogResponseEnabled)
239                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
240                 log.error(catchAllErrMsg, e)
241             }
242         }
243         log.debug("Trying to close GRPC channel. request ($processId)")
244         remoteScriptExecutionService.close()
245     }
246
247     private fun getScriptFile(): File {
248         val context = bluePrintRuntimeService.bluePrintContext()
249         val operationAssignment: OperationAssignment = context
250             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
251
252         val artifactName: String = operationAssignment.implementation?.primary
253             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
254
255         val artifactDefinition =
256             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
257         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
258         return normalizedFile(context.rootPath, artifactDefinition.file)
259     }
260
261     private fun getScriptName(): String {
262         return getScriptFile().name
263     }
264
265     private fun commandExecutorMetricTags(executionServiceInput: ExecutionServiceInput, step: String, scriptName: String): MutableList<Tag> =
266         executionServiceInput.actionIdentifiers.let {
267             mutableListOf(
268                 Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, it.blueprintName),
269                 Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, it.blueprintVersion),
270                 Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, it.actionName),
271                 Tag.of(BluePrintConstants.METRIC_TAG_STEP, step),
272                 Tag.of(BluePrintConstants.METRIC_TAG_SCRIPT_NAME, scriptName)
273             )
274         }
275
276     // wrapper for call to prepare_env step on cmd-exec - reupload CBA and call prepare env again if cmd-exec reported CBA uuid mismatch
277     private suspend fun prepareEnv(originatorId: String, requestId: String, subRequestId: String, remoteIdentifier: RemoteIdentifier, packages: JsonNode, envPrepTimeout: Int, cbaNameVerUuid: String, archiveType: String?, cbaBinData: ByteString?, isLogResponseEnabled: Boolean, retries: Int = 3) {
278         val prepareEnvInput = PrepareRemoteEnvInput(
279             originatorId = originatorId,
280             requestId = requestId,
281             subRequestId = subRequestId,
282             remoteIdentifier = remoteIdentifier,
283             packages = packages,
284             timeOut = envPrepTimeout.toLong()
285         )
286         val preEnvTimer = Timer.start()
287         val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
288         preEnvTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())))
289
290         log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
291         val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
292         setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
293
294         // there are no artifacts for env. prepare, but we reuse it for err_log...
295         if (prepareEnvOutput.status != StatusType.SUCCESS) {
296             // Check for the flag that blueprint is mismatched first, if so, reupload the blueprint
297             if (prepareEnvOutput.payload.has("reupload_cba")) {
298                 log.info("Cmd-exec is missing the CBA $cbaNameVerUuid, it will be reuploaded.")
299                 uploadCba(remoteIdentifier, requestId, subRequestId, originatorId, archiveType, cbaBinData, cbaNameVerUuid, prepareEnvOutput, isLogResponseEnabled, logs)
300                 // call prepare_env again.
301                 if (retries > 0) {
302                     log.info("Calling prepare environment again")
303                     prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
304                 } else {
305                     meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
306                     val errMsg = "Something is wrong: prepare_env step attempted to call itself too many times after upload CBA step!"
307                     log.error(errMsg)
308                     setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
309                     addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, errMsg)
310                 }
311             } else {
312                 meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
313                 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
314                 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
315             }
316         } else {
317             setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
318         }
319     }
320
321     private suspend fun uploadCba(remoteIdentifier: RemoteIdentifier, requestId: String, subRequestId: String, originatorId: String, archiveType: String?, cbaBinData: ByteString?, cbaNameVerUuid: String, prepareEnvOutput: RemoteScriptExecutionOutput, isLogResponseEnabled: Boolean, logs: JsonNode) {
322         val uploadCbaInput = RemoteScriptUploadBlueprintInput(
323             remoteIdentifier = remoteIdentifier,
324             requestId = requestId,
325             subRequestId = subRequestId,
326             originatorId = originatorId,
327             timeOut = DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC.toLong(),
328             archiveType = archiveType!!,
329             binData = cbaBinData!!
330         )
331         val uploadCbaTimer = Timer.start()
332         val cbaUploadOutput = remoteScriptExecutionService.uploadBlueprint(uploadCbaInput)
333         uploadCbaTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_UPLOAD_CBA, getScriptName())))
334
335         if (cbaUploadOutput.status != StatusType.SUCCESS) {
336             meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_UPLOAD_CBA, getScriptName())).increment()
337             log.error("Error uploading CBA $cbaNameVerUuid error(${cbaUploadOutput.payload})")
338             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
339             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
340         } else {
341             log.info("Finished uploading CBA $cbaNameVerUuid")
342         }
343     }
344
345     private fun noBlueprintErrors() =
346         bluePrintRuntimeService.getBluePrintError().stepErrors(stepName).isNullOrEmpty()
347
348     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
349         addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
350     }
351
352     private fun formatNestedJsonNode(node: JsonNode): String {
353         val sb = StringBuilder()
354         if (node.isValueNode) {
355             sb.append(" $node")
356         } else {
357             node.forEach { sb.append(" $it") }
358         }
359         return sb.toString()
360     }
361
362     /**
363      * Utility function to set the output properties of the executor node
364      */
365     private fun setNodeOutputProperties(
366         status: StatusType,
367         step: String,
368         executionLogs: JsonNode,
369         artifacts: JsonNode,
370         logging: Boolean = true
371     ) {
372
373         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
374         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
375         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
376
377         if (logging) {
378             log.info("Executor status : $step : $status")
379             log.info("Executor logs   : $step : $executionLogs")
380             log.info("Executor artifacts: $step : $artifacts")
381         }
382     }
383
384     /**
385      * Utility function to set the output properties and errors of the executor node, in case of errors
386      */
387     private fun setNodeOutputErrors(
388         step: String,
389         executionLogs: JsonNode = "[]".asJsonPrimitive(),
390         artifacts: JsonNode = "{}".asJsonPrimitive(),
391         logging: Boolean = true
392     ) {
393         val status = StatusType.FAILURE.name
394         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
395         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
396         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
397
398         if (logging) {
399             log.info("Executor status : $step : $status")
400             log.info("Executor logs   : $step : $executionLogs")
401             log.info("Executor artifacts: $step : $artifacts")
402         }
403     }
404 }