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.api.data.ExecutionServiceInput
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
29 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
30 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
31 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
32 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
33 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
34 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
35 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
36 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
37 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
38 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
39 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
40 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
41 import org.slf4j.LoggerFactory
42 import org.springframework.beans.factory.config.ConfigurableBeanFactory
43 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
44 import org.springframework.context.annotation.Scope
45 import org.springframework.stereotype.Component
47 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
48 @Component("component-remote-python-executor")
49 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
50 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService) : AbstractComponentFunction() {
52 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
55 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
56 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
57 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
59 const val INPUT_COMMAND = "command"
60 const val INPUT_PACKAGES = "packages"
61 const val DEFAULT_SELECTOR = "remote-python"
62 const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
63 const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
65 const val STEP_PREPARE_ENV = "prepare-env"
66 const val STEP_EXEC_CMD = "execute-command"
67 const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
68 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
69 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
70 const val ATTRIBUTE_RESPONSE_DATA = "response-data"
71 const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
72 const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
73 const val TIMEOUT_DELTA = 100L
76 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
78 log.debug("Processing : $operationInputs")
80 val isLogResponseEnabled = false
82 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
83 val blueprintName = bluePrintContext.name()
84 val blueprintVersion = bluePrintContext.version()
86 val operationAssignment: OperationAssignment = bluePrintContext
87 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
89 val artifactName: String = operationAssignment.implementation?.primary
90 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
92 val artifactDefinition =
93 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
95 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
97 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
99 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
101 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
102 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
103 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
105 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
107 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
108 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
109 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
111 val command = getOperationInput(INPUT_COMMAND).asText()
114 * Timeouts that are specific to the command executor.
115 * Note: the interface->input->timeout is the component level timeout.
117 val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
118 ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
119 val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
120 ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
122 // component level timeout should be => env_prep_timeout + execution_timeout
123 val timeout = implementation.timeout
125 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
126 if (args != null && args.isNotEmpty()) {
127 scriptCommand = scriptCommand.plus(" ").plus(args)
131 // Open GRPC Connection
132 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
133 remoteScriptExecutionService.init(endPointSelector.asText())
135 // Get endpoint from DSL
136 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
137 remoteScriptExecutionService.init(endPointSelectorJson)
140 // If packages are defined, then install in remote server
141 if (packages != null) {
142 val prepareEnvInput = PrepareRemoteEnvInput(
143 requestId = processId,
144 remoteIdentifier = RemoteIdentifier(
145 blueprintName = blueprintName,
146 blueprintVersion = blueprintVersion),
148 timeOut = envPrepTimeout.toLong()
151 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
152 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
153 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
154 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
156 // there are no artifacts for env. prepare, but we reuse it for err_log...
157 if (prepareEnvOutput.status != StatusType.SUCCESS) {
158 setNodeOutputErrors(STEP_PREPARE_ENV, "".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
159 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
161 setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
164 // set env preparation log to empty...
165 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
167 // 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`),
168 // hence `artifact` field will be empty
169 } catch (grpcEx: io.grpc.StatusRuntimeException) {
170 val componentLevelWarningMsg = if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
171 val grpcErrMsg = "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
172 // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
173 // set prepare-env-log to the error msg, and cmd-exec-log to empty
174 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
175 setNodeOutputErrors(STEP_PREPARE_ENV, "".asJsonPrimitive(), "".asJsonPrimitive(), isLogResponseEnabled)
176 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
177 log.error(grpcErrMsg, grpcEx)
179 } catch (e: Exception) {
180 val catchallErrMsg = "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
181 // 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.
182 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
183 setNodeOutputErrors(STEP_PREPARE_ENV, "".asJsonPrimitive(), "".asJsonPrimitive(), isLogResponseEnabled)
184 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
185 log.error(catchallErrMsg, e)
187 // if Env preparation was successful, then proceed with command execution in this Env
188 if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
190 // Populate command execution properties and pass it to the remote server
191 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
193 val remoteExecutionInput = RemoteScriptExecutionInput(
194 requestId = processId,
195 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
196 command = scriptCommand,
197 properties = properties,
198 timeOut = executionTimeout.toLong())
200 val remoteExecutionOutputDeferred = GlobalScope.async {
201 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
204 val remoteExecutionOutput = withTimeout(executionTimeout * 1000L + TIMEOUT_DELTA) {
205 remoteExecutionOutputDeferred.await()
208 checkNotNull(remoteExecutionOutput) {
209 "Error: Request-id $processId did not return a restul from remote command execution."
211 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
212 val returnedPayload = remoteExecutionOutput.payload
213 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
214 // It would contain `err_msg` key. It is valid to return it.
215 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
216 setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
217 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
219 setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
220 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
221 } catch (timeoutEx: TimeoutCancellationException) {
222 val componentLevelWarningMsg = if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
223 val timeoutErrMsg = "Command executor execution timeout. DetailedMessage: (${timeoutEx.message}) requestId ($processId). $componentLevelWarningMsg"
224 setNodeOutputErrors(STEP_EXEC_CMD, timeoutErrMsg.asJsonPrimitive(), logging = isLogResponseEnabled)
225 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
226 log.error(timeoutErrMsg, timeoutEx)
227 } catch (grpcEx: io.grpc.StatusRuntimeException) {
228 val timeoutErrMsg = "Command executor timed out executing after $executionTimeout seconds requestId ($processId) grpcErr: ${grpcEx.status}"
229 setNodeOutputErrors(STEP_EXEC_CMD, timeoutErrMsg.asJsonPrimitive(), logging = isLogResponseEnabled)
230 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
231 log.error(timeoutErrMsg, grpcEx)
232 } catch (e: Exception) {
233 val catchAllErrMsg = "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
234 setNodeOutputErrors(STEP_PREPARE_ENV, catchAllErrMsg.asJsonPrimitive(), logging = isLogResponseEnabled)
235 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
236 log.error(catchAllErrMsg, e)
239 log.debug("Trying to close GRPC channel. request ($processId)")
240 remoteScriptExecutionService.close()
243 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
244 bluePrintRuntimeService.getBluePrintError()
245 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
248 private fun formatNestedJsonNode(node: JsonNode): String {
249 val sb = StringBuilder()
250 if (node.isValueNode) {
253 node.forEach { sb.append(" $it") }
259 * Utility function to set the output properties of the executor node
261 private fun setNodeOutputProperties(
264 executionLogs: JsonNode,
266 logging: Boolean = true
269 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
270 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
271 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
274 log.info("Executor status : $step : $status")
275 log.info("Executor logs : $step : $executionLogs")
276 log.info("Executor artifacts: $step : $artifacts")
281 * Utility function to set the output properties and errors of the executor node, in cas of errors
283 private fun setNodeOutputErrors(
285 executionLogs: JsonNode = "N/A".asJsonPrimitive(),
286 artifacts: JsonNode = "N/A".asJsonPrimitive(),
287 logging: Boolean = true
289 val status = StatusType.FAILURE.name
290 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
291 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
292 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
295 log.info("Executor status : $step : $status")
296 log.info("Executor logs : $step : $executionLogs")
297 log.info("Executor artifacts: $step : $artifacts")