2 * Copyright © 2019 IBM.
3 * Modifications Copyright © 2020 Bell Canada.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
20 import com.fasterxml.jackson.databind.JsonNode
21 import kotlinx.coroutines.GlobalScope
22 import kotlinx.coroutines.TimeoutCancellationException
23 import kotlinx.coroutines.async
24 import kotlinx.coroutines.withTimeout
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.StatusType
31 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
32 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
33 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
34 import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException
35 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
36 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
37 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
38 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
39 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
40 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
41 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
42 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
43 import org.slf4j.LoggerFactory
44 import org.springframework.beans.factory.config.ConfigurableBeanFactory
45 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
46 import org.springframework.context.annotation.Scope
47 import org.springframework.stereotype.Component
49 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
50 @Component("component-remote-python-executor")
51 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
52 open class ComponentRemotePythonExecutor(
53 private val remoteScriptExecutionService: RemoteScriptExecutionService,
54 private var bluePrintPropertiesService: BlueprintPropertiesService
55 ) : AbstractComponentFunction() {
57 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
61 const val SELECTOR_CMD_EXEC = "blueprintsprocessor.remote-script-command"
62 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
63 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
64 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
66 const val INPUT_COMMAND = "command"
67 const val INPUT_PACKAGES = "packages"
68 const val DEFAULT_SELECTOR = "remote-python"
69 const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
70 const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
72 const val STEP_PREPARE_ENV = "prepare-env"
73 const val STEP_EXEC_CMD = "execute-command"
74 const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
75 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
76 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
77 const val ATTRIBUTE_RESPONSE_DATA = "response-data"
78 const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
79 const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
80 const val TIMEOUT_DELTA = 100L
83 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
85 log.debug("Processing : $operationInputs")
87 val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
89 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
90 val blueprintName = bluePrintContext.name()
91 val blueprintVersion = bluePrintContext.version()
93 val operationAssignment: OperationAssignment = bluePrintContext
94 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
96 val artifactName: String = operationAssignment.implementation?.primary
97 ?: throw BlueprintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
99 val artifactDefinition =
100 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
102 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
104 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
106 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
108 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
109 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
110 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
112 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
114 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
115 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
116 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
118 val command = getOperationInput(INPUT_COMMAND).asText()
121 * Timeouts that are specific to the command executor.
122 * Note: the interface->input->timeout is the component level timeout.
124 val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
125 ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
126 val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
127 ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
129 // component level timeout should be => env_prep_timeout + execution_timeout
130 val timeout = implementation.timeout
132 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
133 if (args != null && args.isNotEmpty()) {
134 scriptCommand = scriptCommand.plus(" ").plus(args)
138 // Open GRPC Connection
139 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
140 remoteScriptExecutionService.init(endPointSelector.asText())
142 // Get endpoint from DSL
143 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
144 remoteScriptExecutionService.init(endPointSelectorJson)
147 // If packages are defined, then install in remote server
148 if (packages != null) {
149 val prepareEnvInput = PrepareRemoteEnvInput(
150 originatorId = executionServiceInput.commonHeader.originatorId,
151 requestId = processId,
152 subRequestId = executionServiceInput.commonHeader.subRequestId,
153 remoteIdentifier = RemoteIdentifier(
154 blueprintName = blueprintName,
155 blueprintVersion = blueprintVersion
158 timeOut = envPrepTimeout.toLong()
161 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
162 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
163 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
164 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
166 // there are no artifacts for env. prepare, but we reuse it for err_log...
167 if (prepareEnvOutput.status != StatusType.SUCCESS) {
168 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
169 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
171 setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
174 // set env preparation log to empty...
175 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
177 // 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`),
178 // hence `artifact` field will be empty
179 } catch (grpcEx: io.grpc.StatusRuntimeException) {
180 val componentLevelWarningMsg =
181 if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
183 "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
184 // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
185 // set prepare-env-log to the error msg, and cmd-exec-log to empty
186 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
187 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
188 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
189 log.error(grpcErrMsg, grpcEx)
190 } catch (e: Exception) {
192 "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
193 // 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.
194 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
195 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
196 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
197 log.error(catchallErrMsg, e)
199 // if Env preparation was successful, then proceed with command execution in this Env
200 if (bluePrintRuntimeService.getBlueprintError().errors.isEmpty()) {
202 // Populate command execution properties and pass it to the remote server
203 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
205 val remoteExecutionInput = RemoteScriptExecutionInput(
206 originatorId = executionServiceInput.commonHeader.originatorId,
207 requestId = processId,
208 subRequestId = executionServiceInput.commonHeader.subRequestId,
209 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
210 command = scriptCommand,
211 properties = properties,
212 timeOut = executionTimeout.toLong()
215 val remoteExecutionOutputDeferred = GlobalScope.async {
216 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
219 val remoteExecutionOutput = withTimeout(executionTimeout * 1000L + TIMEOUT_DELTA) {
220 remoteExecutionOutputDeferred.await()
223 checkNotNull(remoteExecutionOutput) {
224 "Error: Request-id $processId did not return a result from remote command execution."
226 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
227 val returnedPayload = remoteExecutionOutput.payload
228 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
229 // It would contain `err_msg` key. It is valid to return it.
230 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
231 setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
232 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
234 setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
235 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
236 } catch (timeoutEx: TimeoutCancellationException) {
237 val componentLevelWarningMsg =
238 if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
240 "Command executor execution timeout. DetailedMessage: (${timeoutEx.message}) requestId ($processId). $componentLevelWarningMsg"
241 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonPrimitive(), logging = isLogResponseEnabled)
242 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
243 log.error(timeoutErrMsg, timeoutEx)
244 } catch (grpcEx: io.grpc.StatusRuntimeException) {
246 "Command executor timed out executing after $executionTimeout seconds requestId ($processId) grpcErr: ${grpcEx.status}"
247 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonPrimitive(), logging = isLogResponseEnabled)
248 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
249 log.error(timeoutErrMsg, grpcEx)
250 } catch (e: Exception) {
252 "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
253 setNodeOutputErrors(STEP_PREPARE_ENV, listOf(catchAllErrMsg).asJsonPrimitive(), logging = isLogResponseEnabled)
254 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
255 log.error(catchAllErrMsg, e)
258 log.debug("Trying to close GRPC channel. request ($processId)")
259 remoteScriptExecutionService.close()
262 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
263 bluePrintRuntimeService.getBlueprintError()
264 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
267 private fun formatNestedJsonNode(node: JsonNode): String {
268 val sb = StringBuilder()
269 if (node.isValueNode) {
272 node.forEach { sb.append(" $it") }
278 * Utility function to set the output properties of the executor node
280 private fun setNodeOutputProperties(
283 executionLogs: JsonNode,
285 logging: Boolean = true
288 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
289 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
290 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
293 log.info("Executor status : $step : $status")
294 log.info("Executor logs : $step : $executionLogs")
295 log.info("Executor artifacts: $step : $artifacts")
300 * Utility function to set the output properties and errors of the executor node, in case of errors
302 private fun setNodeOutputErrors(
304 executionLogs: JsonNode = "[]".asJsonPrimitive(),
305 artifacts: JsonNode = "{}".asJsonPrimitive(),
306 logging: Boolean = true
308 val status = StatusType.FAILURE.name
309 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
310 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
311 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
314 log.info("Executor status : $step : $status")
315 log.info("Executor logs : $step : $executionLogs")
316 log.info("Executor artifacts: $step : $artifacts")