d4c8841a8c25d22f1912dfb163a76a2e8190a00e
[ccsdk/cds.git] /
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     }
79
80     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
81
82         log.debug("Processing : $operationInputs")
83
84         val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
85
86         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
87         val blueprintName = bluePrintContext.name()
88         val blueprintVersion = bluePrintContext.version()
89
90         val operationAssignment: OperationAssignment = bluePrintContext
91             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
92
93         val artifactName: String = operationAssignment.implementation?.primary
94             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
95
96         val artifactDefinition =
97             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
98
99         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
100
101         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
102
103         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
104
105         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
106         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
107         val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
108
109         val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
110
111         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
112         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
113             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
114
115         val command = getOperationInput(INPUT_COMMAND).asText()
116
117         /**
118          * Timeouts that are specific to the command executor.
119          * Note: the interface->input->timeout is the component level timeout.
120          */
121         val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
122             ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
123         val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
124             ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
125
126         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
127         if (args != null && args.isNotEmpty()) {
128             scriptCommand = scriptCommand.plus(" ").plus(args)
129         }
130
131         try {
132             // Open GRPC Connection
133             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
134                 remoteScriptExecutionService.init(endPointSelector.asText())
135             } else {
136                 // Get endpoint from DSL
137                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
138                 remoteScriptExecutionService.init(endPointSelectorJson)
139             }
140
141             // If packages are defined, then install in remote server
142             if (packages != null) {
143                 val prepareEnvInput = PrepareRemoteEnvInput(
144                     requestId = processId,
145                     remoteIdentifier = RemoteIdentifier(
146                         blueprintName = blueprintName,
147                         blueprintVersion = blueprintVersion),
148                     packages = packages,
149                     timeOut = envPrepTimeout.toLong()
150
151                 )
152                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
153                 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
154                 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
155                 val logsEnv = logs.toString().asJsonPrimitive()
156                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logsEnv)
157
158                 if (prepareEnvOutput.status != StatusType.SUCCESS) {
159                     val errorMessage = prepareEnvOutput.payload
160                     setNodeOutputErrors(prepareEnvOutput.status.name,
161                             STEP_PREPARE_ENV,
162                             logs,
163                             errorMessage,
164                             isLogResponseEnabled
165                     )
166                 } else {
167                     setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(),
168                             STEP_PREPARE_ENV,
169                             logsEnv,
170                             "".asJsonPrimitive(),
171                             isLogResponseEnabled
172                     )
173                 }
174             } else {
175                 // set env preparation log to empty...
176                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
177             }
178         } catch (grpcEx: io.grpc.StatusRuntimeException) {
179             val grpcErrMsg = "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId)."
180             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
181             setNodeOutputErrors(status = grpcErrMsg, step = STEP_PREPARE_ENV, error = "${grpcEx.status}".asJsonPrimitive(), logging = isLogResponseEnabled)
182             log.error(grpcErrMsg, grpcEx)
183             addError(grpcErrMsg)
184         } catch (e: Exception) {
185             val timeoutErrMsg = "Command executor failed during env. preparation.. timeout($envPrepTimeout) requestId ($processId)."
186             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, e.message.asJsonPrimitive())
187             setNodeOutputErrors(status = timeoutErrMsg, step = STEP_PREPARE_ENV, error = "${e.message}".asJsonPrimitive(), logging = isLogResponseEnabled)
188             log.error("Failed to process on remote executor requestId ($processId)", e)
189             addError(timeoutErrMsg)
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 = implementation.timeout.toLong())
203
204                 val remoteExecutionOutputDeferred = GlobalScope.async {
205                     remoteScriptExecutionService.executeCommand(remoteExecutionInput)
206                 }
207
208                 val remoteExecutionOutput = withTimeout(implementation.timeout * 1000L) {
209                     remoteExecutionOutputDeferred.await()
210                 }
211
212                 checkNotNull(remoteExecutionOutput) {
213                     "Error: Request-id $processId did not return a restul from remote command execution."
214                 }
215                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
216                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
217                     setNodeOutputErrors(remoteExecutionOutput.status.name,
218                             STEP_EXEC_CMD,
219                             logs,
220                             remoteExecutionOutput.payload,
221                             isLogResponseEnabled
222                     )
223                 } else {
224                     setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(),
225                             STEP_EXEC_CMD,
226                             logs,
227                             remoteExecutionOutput.payload,
228                             isLogResponseEnabled
229                     )
230                 }
231             } catch (timeoutEx: TimeoutCancellationException) {
232                 val timeoutErrMsg = "Command executor timed out executing after $executionTimeout seconds requestId ($processId)"
233                 setNodeOutputErrors(status = timeoutErrMsg,
234                         step = STEP_EXEC_CMD,
235                         logs = "".asJsonPrimitive(),
236                         error = "".asJsonPrimitive(),
237                         logging = isLogResponseEnabled
238                 )
239                 log.error(timeoutErrMsg, timeoutEx)
240             } catch (grpcEx: io.grpc.StatusRuntimeException) {
241                 val timeoutErrMsg = "Command executor timed out executing after $executionTimeout seconds requestId ($processId)"
242                 setNodeOutputErrors(status = timeoutErrMsg,
243                         step = STEP_EXEC_CMD,
244                         logs = "".asJsonPrimitive(),
245                         error = "".asJsonPrimitive(),
246                         logging = isLogResponseEnabled
247                 )
248                 log.error("Command executor time out during GRPC call", grpcEx)
249             } catch (e: Exception) {
250                 log.error("Failed to process on remote executor requestId ($processId)", e)
251             }
252         }
253         log.debug("Trying to close GRPC channel. request ($processId)")
254         remoteScriptExecutionService.close()
255     }
256
257     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
258         bluePrintRuntimeService.getBluePrintError()
259             .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
260     }
261
262     private fun formatNestedJsonNode(node: JsonNode): String {
263         val sb = StringBuilder()
264         if (node.isValueNode) {
265             sb.append(" $node")
266         } else {
267             node.forEach { sb.append(" $it") }
268         }
269         return sb.toString()
270     }
271
272     /**
273      * Utility function to set the output properties of the executor node
274      */
275     private fun setNodeOutputProperties(status: JsonNode, step: String, message: JsonNode, artifacts: JsonNode, logging: Boolean = true) {
276         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
277         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
278         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
279
280         if (logging) {
281             log.info("Executor status   : $step : $status")
282             log.info("Executor artifacts: $step : $artifacts")
283             log.info("Executor message  : $step : $message")
284         }
285     }
286
287     /**
288      * Utility function to set the output properties and errors of the executor node, in cas of errors
289      */
290     private fun setNodeOutputErrors(
291         status: String,
292         step: String,
293         logs: JsonNode = "N/A".asJsonPrimitive(),
294         error: JsonNode,
295         logging: Boolean = true
296     ) {
297         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
298         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, logs)
299         setAttribute(ATTRIBUTE_RESPONSE_DATA, "N/A".asJsonPrimitive())
300
301         if (logging) {
302             log.info("Executor status   : $step : $status")
303             log.info("Executor message  : $step : $error")
304             log.info("Executor logs     : $step : $logs")
305         }
306
307         addError(status, step, error.toString())
308     }
309 }