a15e2f1ab2ae4109a77954f52a8ca85c6cb74418
[ccsdk/cds.git] /
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         // NOTE: this was reverted back to absolute path for SR7 compatibility.
142         // CMD-EXEC SR10 onwards will look for absence of blueprint UUID in the absolute path.
143         // If such request is found, UUID will be appended.
144         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
145         if (args != null && args.isNotEmpty()) {
146             scriptCommand = scriptCommand.plus(" ").plus(args)
147         }
148
149         try {
150             // Open GRPC Connection
151             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
152                 remoteScriptExecutionService.init(endPointSelector.asText())
153             } else {
154                 // Get endpoint from DSL
155                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
156                 remoteScriptExecutionService.init(endPointSelectorJson)
157             }
158
159             // If packages are defined, then install in remote server
160             if (packages == null) {
161                 // set env preparation log to empty...
162                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
163                 packages = mutableListOf<Object>().asJsonType()
164             }
165             prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
166             // 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`),
167             // hence `artifact` field will be empty
168         } catch (grpcEx: io.grpc.StatusRuntimeException) {
169             val errorType = if (grpcEx.status.code == Status.DEADLINE_EXCEEDED.code) CDS_BP_CE_TIMEOUT_ERROR_TOTAL else CDS_BP_CE_GRPC_ERROR_TOTAL
170             meterRegistry.counter(errorType, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
171
172             val componentLevelWarningMsg = if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
173             val grpcErrMsg = "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
174             // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
175             // set prepare-env-log to the error msg, and cmd-exec-log to empty
176             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
177             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
178             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
179             log.error(grpcErrMsg, grpcEx)
180         } catch (e: Exception) {
181             meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
182
183             val catchallErrMsg = "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
184             // 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.
185             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
186             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
187             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
188             log.error(catchallErrMsg, e)
189         }
190         // if Env preparation was successful, then proceed with command execution in this Env
191         if (noBlueprintErrors()) {
192             try {
193                 // Populate command execution properties and pass it to the remote server
194                 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
195
196                 val remoteExecutionInput = RemoteScriptExecutionInput(
197                     originatorId = executionServiceInput.commonHeader.originatorId,
198                     requestId = processId,
199                     subRequestId = executionServiceInput.commonHeader.subRequestId,
200                     remoteIdentifier = remoteIdentifier,
201                     command = scriptCommand,
202                     properties = properties,
203                     timeOut = executionTimeout.toLong()
204                 )
205
206                 val exeCmdTimer = Timer.start()
207                 val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
208                 exeCmdTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())))
209
210                 checkNotNull(remoteExecutionOutput) {
211                     "Error: Request-id $processId did not return a result from remote command execution."
212                 }
213                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
214                 val returnedPayload = remoteExecutionOutput.payload
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                     addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
220                 } else {
221                     setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
222                 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
223             } catch (grpcEx: io.grpc.StatusRuntimeException) {
224                 val errorType = if (grpcEx.status.code == Status.DEADLINE_EXCEEDED.code) CDS_BP_CE_TIMEOUT_ERROR_TOTAL else CDS_BP_CE_GRPC_ERROR_TOTAL
225                 meterRegistry.counter(errorType, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())).increment()
226
227                 val componentLevelWarningMsg =
228                     if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
229                 val timeoutErrMsg =
230                     "Command executor timed out executing after $executionTimeout seconds requestId ($processId). $componentLevelWarningMsg grpcErr: ${grpcEx.status}"
231                 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonType(), logging = isLogResponseEnabled)
232                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
233                 log.error(timeoutErrMsg, grpcEx)
234             } catch (e: Exception) {
235                 meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_EXEC_CMD, getScriptName())).increment()
236                 val catchAllErrMsg = "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
237                 setNodeOutputErrors(STEP_PREPARE_ENV, listOf(catchAllErrMsg).asJsonType(), logging = isLogResponseEnabled)
238                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
239                 log.error(catchAllErrMsg, e)
240             }
241         }
242         log.debug("Trying to close GRPC channel. request ($processId)")
243         remoteScriptExecutionService.close()
244     }
245
246     private fun getScriptFile(): File {
247         val context = bluePrintRuntimeService.bluePrintContext()
248         val operationAssignment: OperationAssignment = context
249             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
250
251         val artifactName: String = operationAssignment.implementation?.primary
252             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
253
254         val artifactDefinition =
255             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
256         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
257         return normalizedFile(context.rootPath, artifactDefinition.file)
258     }
259
260     private fun getScriptName(): String {
261         return getScriptFile().name
262     }
263
264     private fun commandExecutorMetricTags(executionServiceInput: ExecutionServiceInput, step: String, scriptName: String): MutableList<Tag> =
265         executionServiceInput.actionIdentifiers.let {
266             mutableListOf(
267                 Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, it.blueprintName),
268                 Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, it.blueprintVersion),
269                 Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, it.actionName),
270                 Tag.of(BluePrintConstants.METRIC_TAG_STEP, step),
271                 Tag.of(BluePrintConstants.METRIC_TAG_SCRIPT_NAME, scriptName)
272             )
273         }
274
275     // wrapper for call to prepare_env step on cmd-exec - reupload CBA and call prepare env again if cmd-exec reported CBA uuid mismatch
276     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) {
277         val prepareEnvInput = PrepareRemoteEnvInput(
278             originatorId = originatorId,
279             requestId = requestId,
280             subRequestId = subRequestId,
281             remoteIdentifier = remoteIdentifier,
282             packages = packages,
283             timeOut = envPrepTimeout.toLong()
284         )
285         val preEnvTimer = Timer.start()
286         val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
287         preEnvTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())))
288
289         log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
290         val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
291         setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
292
293         // there are no artifacts for env. prepare, but we reuse it for err_log...
294         if (prepareEnvOutput.status != StatusType.SUCCESS) {
295             // Check for the flag that blueprint is mismatched first, if so, reupload the blueprint
296             if (prepareEnvOutput.payload.has("reupload_cba")) {
297                 log.info("Cmd-exec is missing the CBA $cbaNameVerUuid, it will be reuploaded.")
298                 uploadCba(remoteIdentifier, requestId, subRequestId, originatorId, archiveType, cbaBinData, cbaNameVerUuid, prepareEnvOutput, isLogResponseEnabled, logs)
299                 // call prepare_env again.
300                 if (retries > 0) {
301                     log.info("Calling prepare environment again")
302                     prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
303                 } else {
304                     meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
305                     val errMsg = "Something is wrong: prepare_env step attempted to call itself too many times after upload CBA step!"
306                     log.error(errMsg)
307                     setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
308                     addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, errMsg)
309                 }
310             } else {
311                 meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_PREPARE_ENV, getScriptName())).increment()
312                 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
313                 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
314             }
315         } else {
316             setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
317         }
318     }
319
320     private suspend fun uploadCba(remoteIdentifier: RemoteIdentifier, requestId: String, subRequestId: String, originatorId: String, archiveType: String?, cbaBinData: ByteString?, cbaNameVerUuid: String, prepareEnvOutput: RemoteScriptExecutionOutput, isLogResponseEnabled: Boolean, logs: JsonNode) {
321         val uploadCbaInput = RemoteScriptUploadBlueprintInput(
322             remoteIdentifier = remoteIdentifier,
323             requestId = requestId,
324             subRequestId = subRequestId,
325             originatorId = originatorId,
326             timeOut = DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC.toLong(),
327             archiveType = archiveType!!,
328             binData = cbaBinData!!
329         )
330         val uploadCbaTimer = Timer.start()
331         val cbaUploadOutput = remoteScriptExecutionService.uploadBlueprint(uploadCbaInput)
332         uploadCbaTimer.stop(meterRegistry.timer(CDS_BP_CE_EXECUTION_DURATION_SECONDS, commandExecutorMetricTags(executionServiceInput, STEP_UPLOAD_CBA, getScriptName())))
333
334         if (cbaUploadOutput.status != StatusType.SUCCESS) {
335             meterRegistry.counter(CDS_BP_CE_GRPC_ERROR_TOTAL, commandExecutorMetricTags(executionServiceInput, STEP_UPLOAD_CBA, getScriptName())).increment()
336             log.error("Error uploading CBA $cbaNameVerUuid error(${cbaUploadOutput.payload})")
337             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
338             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
339         } else {
340             log.info("Finished uploading CBA $cbaNameVerUuid")
341         }
342     }
343
344     private fun noBlueprintErrors() =
345         bluePrintRuntimeService.getBluePrintError().stepErrors(stepName).isNullOrEmpty()
346
347     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
348         addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
349     }
350
351     private fun formatNestedJsonNode(node: JsonNode): String {
352         val sb = StringBuilder()
353         if (node.isValueNode) {
354             sb.append(" $node")
355         } else {
356             node.forEach { sb.append(" $it") }
357         }
358         return sb.toString()
359     }
360
361     /**
362      * Utility function to set the output properties of the executor node
363      */
364     private fun setNodeOutputProperties(
365         status: StatusType,
366         step: String,
367         executionLogs: JsonNode,
368         artifacts: JsonNode,
369         logging: Boolean = true
370     ) {
371
372         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
373         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
374         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
375
376         if (logging) {
377             log.info("Executor status : $step : $status")
378             log.info("Executor logs   : $step : $executionLogs")
379             log.info("Executor artifacts: $step : $artifacts")
380         }
381     }
382
383     /**
384      * Utility function to set the output properties and errors of the executor node, in case of errors
385      */
386     private fun setNodeOutputErrors(
387         step: String,
388         executionLogs: JsonNode = "[]".asJsonPrimitive(),
389         artifacts: JsonNode = "{}".asJsonPrimitive(),
390         logging: Boolean = true
391     ) {
392         val status = StatusType.FAILURE.name
393         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
394         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
395         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
396
397         if (logging) {
398             log.info("Executor status : $step : $status")
399             log.info("Executor logs   : $step : $executionLogs")
400             log.info("Executor artifacts: $step : $artifacts")
401         }
402     }
403 }