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