00f8e5a19477867c4c4b00327ecf40c794ed802e
[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                 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
213                 // It would contain `err_msg` key. It is valid to return it.
214                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
215                     setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
216                     addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
217                 } else {
218                     setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
219                 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
220             } catch (grpcEx: io.grpc.StatusRuntimeException) {
221                 val errorType = if (grpcEx.status.code == Status.DEADLINE_EXCEEDED.code) CDS_BP_CE_TIMEOUT_ERROR_TOTAL else CDS_BP_CE_GRPC_ERROR_TOTAL
222                 meterRegistry.counter(errorType, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())).increment()
223
224                 val componentLevelWarningMsg =
225                     if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
226                 val timeoutErrMsg =
227                     "Command executor timed out executing after $executionTimeout seconds requestId ($processId). $componentLevelWarningMsg grpcErr: ${grpcEx.status}"
228                 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonType(), logging = isLogResponseEnabled)
229                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
230                 log.error(timeoutErrMsg, grpcEx)
231             } catch (e: Exception) {
232                 meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())).increment()
233                 val catchAllErrMsg = "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
234                 setNodeOutputErrors(STEP_PREPARE_ENV, listOf(catchAllErrMsg).asJsonType(), logging = isLogResponseEnabled)
235                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
236                 log.error(catchAllErrMsg, e)
237             }
238         }
239         log.debug("Trying to close GRPC channel. request ($processId)")
240         remoteScriptExecutionService.close()
241     }
242
243     private fun getScriptFile(): File {
244         val context = bluePrintRuntimeService.bluePrintContext()
245         val operationAssignment: OperationAssignment = context
246             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
247
248         val artifactName: String = operationAssignment.implementation?.primary
249             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
250
251         val artifactDefinition =
252             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
253         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
254         return normalizedFile(context.rootPath, artifactDefinition.file)
255     }
256
257     private fun getScriptName(): String {
258         return getScriptFile().name
259     }
260
261     private fun commandExecutorMetricTags(executionServiceInput: ExecutionServiceInput, step: String, scriptName: String): MutableList<Tag> =
262         executionServiceInput.actionIdentifiers.let {
263             mutableListOf(
264                 Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, it.blueprintName),
265                 Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, it.blueprintVersion),
266                 Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, it.actionName),
267                 Tag.of(BluePrintConstants.METRIC_TAG_STEP, step),
268                 Tag.of(BluePrintConstants.METRIC_TAG_SCRIPT_NAME, scriptName)
269             )
270         }
271
272     // wrapper for call to prepare_env step on cmd-exec - reupload CBA and call prepare env again if cmd-exec reported CBA uuid mismatch
273     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) {
274         val prepareEnvInput = PrepareRemoteEnvInput(
275             originatorId = originatorId,
276             requestId = requestId,
277             subRequestId = subRequestId,
278             remoteIdentifier = remoteIdentifier,
279             packages = packages,
280             timeOut = envPrepTimeout.toLong()
281         )
282         val preEnvTimer = Timer.start()
283         val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
284         preEnvTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())))
285
286         log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
287         val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
288         setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
289
290         // there are no artifacts for env. prepare, but we reuse it for err_log...
291         if (prepareEnvOutput.status != StatusType.SUCCESS) {
292             // Check for the flag that blueprint is mismatched first, if so, reupload the blueprint
293             if (prepareEnvOutput.payload.has("reupload_cba")) {
294                 log.info("Cmd-exec is missing the CBA $cbaNameVerUuid, it will be reuploaded.")
295                 uploadCba(remoteIdentifier, requestId, subRequestId, originatorId, archiveType, cbaBinData, cbaNameVerUuid, prepareEnvOutput, isLogResponseEnabled, logs)
296                 // call prepare_env again.
297                 if (retries > 0) {
298                     log.info("Calling prepare environment again")
299                     prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
300                 } else {
301                     meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
302                     val errMsg = "Something is wrong: prepare_env step attempted to call itself too many times after upload CBA step!"
303                     log.error(errMsg)
304                     setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
305                     addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, errMsg)
306                 }
307             } else {
308                 meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
309                 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
310                 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
311             }
312         } else {
313             setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
314         }
315     }
316
317     private suspend fun uploadCba(remoteIdentifier: RemoteIdentifier, requestId: String, subRequestId: String, originatorId: String, archiveType: String?, cbaBinData: ByteString?, cbaNameVerUuid: String, prepareEnvOutput: RemoteScriptExecutionOutput, isLogResponseEnabled: Boolean, logs: JsonNode) {
318         val uploadCbaInput = RemoteScriptUploadBlueprintInput(
319             remoteIdentifier = remoteIdentifier,
320             requestId = requestId,
321             subRequestId = subRequestId,
322             originatorId = originatorId,
323             timeOut = DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC.toLong(),
324             archiveType = archiveType!!,
325             binData = cbaBinData!!
326         )
327         val uploadCbaTimer = Timer.start()
328         val cbaUploadOutput = remoteScriptExecutionService.uploadBlueprint(uploadCbaInput)
329         uploadCbaTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_UPLOAD_CBA, getScriptName())))
330
331         if (cbaUploadOutput.status != StatusType.SUCCESS) {
332             meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_UPLOAD_CBA, getScriptName())).increment()
333             log.error("Error uploading CBA $cbaNameVerUuid error(${cbaUploadOutput.payload})")
334             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
335             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
336         } else {
337             log.info("Finished uploading CBA $cbaNameVerUuid")
338         }
339     }
340
341     private fun noBlueprintErrors() =
342         bluePrintRuntimeService.getBluePrintError().stepErrors(stepName).isNullOrEmpty()
343
344     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
345         addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
346     }
347
348     private fun formatNestedJsonNode(node: JsonNode): String {
349         val sb = StringBuilder()
350         if (node.isValueNode) {
351             sb.append(" $node")
352         } else {
353             node.forEach { sb.append(" $it") }
354         }
355         return sb.toString()
356     }
357
358     /**
359      * Utility function to set the output properties of the executor node
360      */
361     private fun setNodeOutputProperties(
362         status: StatusType,
363         step: String,
364         executionLogs: JsonNode,
365         artifacts: JsonNode,
366         logging: Boolean = true
367     ) {
368
369         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
370         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
371         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
372
373         if (logging) {
374             log.info("Executor status : $step : $status")
375             log.info("Executor logs   : $step : $executionLogs")
376             log.info("Executor artifacts: $step : $artifacts")
377         }
378     }
379
380     /**
381      * Utility function to set the output properties and errors of the executor node, in case of errors
382      */
383     private fun setNodeOutputErrors(
384         step: String,
385         executionLogs: JsonNode = "[]".asJsonPrimitive(),
386         artifacts: JsonNode = "{}".asJsonPrimitive(),
387         logging: Boolean = true
388     ) {
389         val status = StatusType.FAILURE.name
390         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
391         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
392         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
393
394         if (logging) {
395             log.info("Executor status : $step : $status")
396             log.info("Executor logs   : $step : $executionLogs")
397             log.info("Executor artifacts: $step : $artifacts")
398         }
399     }
400 }