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 org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
21 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
22 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
23 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
24 import org.onap.ccsdk.cds.controllerblueprints.core.*
25 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
26 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
27 import org.slf4j.LoggerFactory
28 import org.springframework.beans.factory.config.ConfigurableBeanFactory
29 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
30 import org.springframework.context.annotation.Scope
31 import org.springframework.stereotype.Component
33 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
34 @Component("component-remote-python-executor")
35 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
36 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService)
37 : AbstractComponentFunction() {
39 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
42 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
43 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
44 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
45 const val INPUT_COMMAND = "command"
46 const val INPUT_PACKAGES = "packages"
47 const val DEFAULT_SELECTOR = "remote-python"
49 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
50 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
53 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
55 log.info("Processing : $operationInputs")
57 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
58 val blueprintName = bluePrintContext.name()
59 val blueprintVersion = bluePrintContext.version()
61 val operationAssignment: OperationAssignment = bluePrintContext
62 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
64 val artifactName: String = operationAssignment.implementation?.primary
65 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
67 val artifactDefinition =
68 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
70 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
72 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
74 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
76 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
77 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
78 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
80 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
82 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
83 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
84 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
86 val command = getOperationInput(INPUT_COMMAND).asText()
87 var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
88 if (args != null && args.isNotEmpty()) {
89 scriptCommand = scriptCommand.plus(" ").plus(args)
93 // Open GRPC Connection
94 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
95 remoteScriptExecutionService.init(endPointSelector.asText())
97 // Get endpoint from DSL
98 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
99 remoteScriptExecutionService.init(endPointSelectorJson)
102 // If packages are defined, then install in remote server
103 if (packages != null) {
104 val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
105 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
106 blueprintVersion = blueprintVersion),
109 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
110 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
111 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response))
112 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
113 check(prepareEnvOutput.status == StatusType.SUCCESS) {
114 "failed to get prepare remote env response status for requestId(${prepareEnvInput.requestId})"
117 // Populate command execution properties and pass it to the remote server
118 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
120 val remoteExecutionInput = RemoteScriptExecutionInput(
121 requestId = processId,
122 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
123 command = scriptCommand,
124 properties = properties)
125 val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
126 log.info("$ATTRIBUTE_EXEC_CMD_LOG - ${remoteExecutionOutput.response}")
127 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response))
128 check(remoteExecutionOutput.status == StatusType.SUCCESS) {
129 "failed to get prepare remote command response status for requestId(${remoteExecutionOutput.requestId})"
132 } catch (e: Exception) {
133 log.error("Failed to process on remote executor", e)
135 remoteScriptExecutionService.close()
139 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
140 bluePrintRuntimeService.getBluePrintError()
141 .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}")
144 private fun formatNestedJsonNode(node: JsonNode): String {
145 val sb = StringBuilder()
146 if (node.isValueNode) {
149 node.forEach { sb.append(" $it") }