9ed13c1467a3d41552198cad0a75be2c54e61e90
[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  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
18
19 import com.fasterxml.jackson.databind.JsonNode
20 import kotlinx.coroutines.GlobalScope
21 import kotlinx.coroutines.TimeoutCancellationException
22 import kotlinx.coroutines.async
23 import kotlinx.coroutines.withTimeout
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
29 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
30 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
31 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
32 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
33 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
34 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
35 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
36 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
37 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
38 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
39 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
40 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
41 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
42 import org.slf4j.LoggerFactory
43 import org.springframework.beans.factory.config.ConfigurableBeanFactory
44 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
45 import org.springframework.context.annotation.Scope
46 import org.springframework.stereotype.Component
47
48 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
49 @Component("component-remote-python-executor")
50 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
51 open class ComponentRemotePythonExecutor(
52     private val remoteScriptExecutionService: RemoteScriptExecutionService,
53     private var bluePrintPropertiesService: BluePrintPropertiesService
54 ) : AbstractComponentFunction() {
55
56     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
57
58     companion object {
59         const val SELECTOR_CMD_EXEC = "blueprintsprocessor.remote-script-command"
60         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
61         const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
62         const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
63
64         const val INPUT_COMMAND = "command"
65         const val INPUT_PACKAGES = "packages"
66         const val DEFAULT_SELECTOR = "remote-python"
67         const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
68         const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
69
70         const val STEP_PREPARE_ENV = "prepare-env"
71         const val STEP_EXEC_CMD = "execute-command"
72         const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
73         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
74         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
75         const val ATTRIBUTE_RESPONSE_DATA = "response-data"
76         const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
77         const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
78         const val TIMEOUT_DELTA = 100L
79     }
80
81     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
82
83         log.debug("Processing : $operationInputs")
84
85         val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
86
87         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
88         val blueprintName = bluePrintContext.name()
89         val blueprintVersion = bluePrintContext.version()
90
91         val operationAssignment: OperationAssignment = bluePrintContext
92             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
93
94         val artifactName: String = operationAssignment.implementation?.primary
95             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
96
97         val artifactDefinition =
98             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
99
100         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
101
102         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
103
104         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
105
106         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
107         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
108         val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
109
110         val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
111
112         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
113         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
114             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
115
116         val command = getOperationInput(INPUT_COMMAND).asText()
117
118         /**
119          * Timeouts that are specific to the command executor.
120          * Note: the interface->input->timeout is the component level timeout.
121          */
122         val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
123             ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
124         val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
125             ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
126
127         // component level timeout should be => env_prep_timeout + execution_timeout
128         val timeout = implementation.timeout
129
130         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
131         if (args != null && args.isNotEmpty()) {
132             scriptCommand = scriptCommand.plus(" ").plus(args)
133         }
134
135         try {
136             // Open GRPC Connection
137             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
138                 remoteScriptExecutionService.init(endPointSelector.asText())
139             } else {
140                 // Get endpoint from DSL
141                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
142                 remoteScriptExecutionService.init(endPointSelectorJson)
143             }
144
145             // If packages are defined, then install in remote server
146             if (packages != null) {
147                 val prepareEnvInput = PrepareRemoteEnvInput(
148                     requestId = processId,
149                     remoteIdentifier = RemoteIdentifier(
150                         blueprintName = blueprintName,
151                         blueprintVersion = blueprintVersion),
152                     packages = packages,
153                     timeOut = envPrepTimeout.toLong()
154
155                 )
156                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
157                 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
158                 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
159                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
160
161                 // there are no artifacts for env. prepare, but we reuse it for err_log...
162                 if (prepareEnvOutput.status != StatusType.SUCCESS) {
163                     setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
164                     addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
165                 } else {
166                     setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
167                 }
168             } else {
169                 // set env preparation log to empty...
170                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
171             }
172             // 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`),
173             // hence `artifact` field will be empty
174         } catch (grpcEx: io.grpc.StatusRuntimeException) {
175             val componentLevelWarningMsg = if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
176             val grpcErrMsg = "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
177             // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
178             // set prepare-env-log to the error msg, and cmd-exec-log to empty
179             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
180             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
181             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
182             log.error(grpcErrMsg, grpcEx)
183         } catch (e: Exception) {
184             val catchallErrMsg = "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
185             // 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.
186             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
187             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
188             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
189             log.error(catchallErrMsg, e)
190         }
191         // if Env preparation was successful, then proceed with command execution in this Env
192         if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
193             try {
194                 // Populate command execution properties and pass it to the remote server
195                 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
196
197                 val remoteExecutionInput = RemoteScriptExecutionInput(
198                     requestId = processId,
199                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
200                     command = scriptCommand,
201                     properties = properties,
202                     timeOut = executionTimeout.toLong())
203
204                 val remoteExecutionOutputDeferred = GlobalScope.async {
205                     remoteScriptExecutionService.executeCommand(remoteExecutionInput)
206                 }
207
208                 val remoteExecutionOutput = withTimeout(executionTimeout * 1000L + TIMEOUT_DELTA) {
209                     remoteExecutionOutputDeferred.await()
210                 }
211
212                 checkNotNull(remoteExecutionOutput) {
213                     "Error: Request-id $processId did not return a result from remote command execution."
214                 }
215                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
216                 val returnedPayload = remoteExecutionOutput.payload
217                 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
218                 // It would contain `err_msg` key. It is valid to return it.
219                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
220                     setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
221                     addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
222                 } else {
223                     setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
224                 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
225             } catch (timeoutEx: TimeoutCancellationException) {
226                 val componentLevelWarningMsg = if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
227                 val timeoutErrMsg = "Command executor execution timeout. DetailedMessage: (${timeoutEx.message}) requestId ($processId). $componentLevelWarningMsg"
228                 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonPrimitive(), logging = isLogResponseEnabled)
229                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
230                 log.error(timeoutErrMsg, timeoutEx)
231             } catch (grpcEx: io.grpc.StatusRuntimeException) {
232                 val timeoutErrMsg = "Command executor timed out executing after $executionTimeout seconds requestId ($processId) grpcErr: ${grpcEx.status}"
233                 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonPrimitive(), logging = isLogResponseEnabled)
234                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
235                 log.error(timeoutErrMsg, grpcEx)
236             } catch (e: Exception) {
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).asJsonPrimitive(), 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     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
248         bluePrintRuntimeService.getBluePrintError()
249             .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
250     }
251
252     private fun formatNestedJsonNode(node: JsonNode): String {
253         val sb = StringBuilder()
254         if (node.isValueNode) {
255             sb.append(" $node")
256         } else {
257             node.forEach { sb.append(" $it") }
258         }
259         return sb.toString()
260     }
261
262     /**
263      * Utility function to set the output properties of the executor node
264      */
265     private fun setNodeOutputProperties(
266         status: StatusType,
267         step: String,
268         executionLogs: JsonNode,
269         artifacts: JsonNode,
270         logging: Boolean = true
271     ) {
272
273         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
274         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
275         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
276
277         if (logging) {
278             log.info("Executor status : $step : $status")
279             log.info("Executor logs   : $step : $executionLogs")
280             log.info("Executor artifacts: $step : $artifacts")
281         }
282     }
283
284     /**
285      * Utility function to set the output properties and errors of the executor node, in case of errors
286      */
287     private fun setNodeOutputErrors(
288         step: String,
289         executionLogs: JsonNode = "[]".asJsonPrimitive(),
290         artifacts: JsonNode = "{}".asJsonPrimitive(),
291         logging: Boolean = true
292     ) {
293         val status = StatusType.FAILURE.name
294         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
295         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
296         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
297
298         if (logging) {
299             log.info("Executor status : $step : $status")
300             log.info("Executor logs   : $step : $executionLogs")
301             log.info("Executor artifacts: $step : $artifacts")
302         }
303     }
304 }