2 * Copyright © 2019 IBM.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
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
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() {
56 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
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"
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"
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
81 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
83 log.debug("Processing : $operationInputs")
85 val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
87 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
88 val blueprintName = bluePrintContext.name()
89 val blueprintVersion = bluePrintContext.version()
91 val operationAssignment: OperationAssignment = bluePrintContext
92 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
94 val artifactName: String = operationAssignment.implementation?.primary
95 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
97 val artifactDefinition =
98 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
100 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
102 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
104 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
106 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
107 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
108 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
110 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
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) }
116 val command = getOperationInput(INPUT_COMMAND).asText()
119 * Timeouts that are specific to the command executor.
120 * Note: the interface->input->timeout is the component level timeout.
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
127 // component level timeout should be => env_prep_timeout + execution_timeout
128 val timeout = implementation.timeout
130 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
131 if (args != null && args.isNotEmpty()) {
132 scriptCommand = scriptCommand.plus(" ").plus(args)
136 // Open GRPC Connection
137 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
138 remoteScriptExecutionService.init(endPointSelector.asText())
140 // Get endpoint from DSL
141 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
142 remoteScriptExecutionService.init(endPointSelectorJson)
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),
153 timeOut = envPrepTimeout.toLong()
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)
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())
166 setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
169 // set env preparation log to empty...
170 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
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)
191 // if Env preparation was successful, then proceed with command execution in this Env
192 if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
194 // Populate command execution properties and pass it to the remote server
195 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
197 val remoteExecutionInput = RemoteScriptExecutionInput(
198 requestId = processId,
199 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
200 command = scriptCommand,
201 properties = properties,
202 timeOut = executionTimeout.toLong())
204 val remoteExecutionOutputDeferred = GlobalScope.async {
205 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
208 val remoteExecutionOutput = withTimeout(executionTimeout * 1000L + TIMEOUT_DELTA) {
209 remoteExecutionOutputDeferred.await()
212 checkNotNull(remoteExecutionOutput) {
213 "Error: Request-id $processId did not return a result from remote command execution."
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())
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)
243 log.debug("Trying to close GRPC channel. request ($processId)")
244 remoteScriptExecutionService.close()
247 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
248 bluePrintRuntimeService.getBluePrintError()
249 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
252 private fun formatNestedJsonNode(node: JsonNode): String {
253 val sb = StringBuilder()
254 if (node.isValueNode) {
257 node.forEach { sb.append(" $it") }
263 * Utility function to set the output properties of the executor node
265 private fun setNodeOutputProperties(
268 executionLogs: JsonNode,
270 logging: Boolean = true
273 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
274 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
275 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
278 log.info("Executor status : $step : $status")
279 log.info("Executor logs : $step : $executionLogs")
280 log.info("Executor artifacts: $step : $artifacts")
285 * Utility function to set the output properties and errors of the executor node, in case of errors
287 private fun setNodeOutputErrors(
289 executionLogs: JsonNode = "[]".asJsonPrimitive(),
290 artifacts: JsonNode = "{}".asJsonPrimitive(),
291 logging: Boolean = true
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)
299 log.info("Executor status : $step : $status")
300 log.info("Executor logs : $step : $executionLogs")
301 log.info("Executor artifacts: $step : $artifacts")