91d51757aaa2ccff53ef3bbecc5a9ecd60a1a6c6
[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 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
32
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() {
38
39     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
40
41     companion object {
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"
48
49         const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
50         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
51         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
52         const val ATTRIBUTE_RESPONSE_DATA = "response-data"
53     }
54
55     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
56
57         log.debug("Processing : $operationInputs")
58
59         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
60         val blueprintName = bluePrintContext.name()
61         val blueprintVersion = bluePrintContext.version()
62
63         val operationAssignment: OperationAssignment = bluePrintContext
64             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
65
66         val artifactName: String = operationAssignment.implementation?.primary
67             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
68
69         val artifactDefinition =
70             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
71
72         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
73
74         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
75
76         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
77
78         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
79         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
80         val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
81
82         val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
83
84         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
85         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
86             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
87
88         val command = getOperationInput(INPUT_COMMAND).asText()
89         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
90         if (args != null && args.isNotEmpty()) {
91             scriptCommand = scriptCommand.plus(" ").plus(args)
92         }
93
94         try {
95             // Open GRPC Connection
96             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
97                 remoteScriptExecutionService.init(endPointSelector.asText())
98             } else {
99                 // Get endpoint from DSL
100                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
101                 remoteScriptExecutionService.init(endPointSelectorJson)
102             }
103
104             // If packages are defined, then install in remote server
105             if (packages != null) {
106                 val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
107                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
108                         blueprintVersion = blueprintVersion),
109                     packages = packages
110                 )
111                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
112                 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
113                 val logs = prepareEnvOutput.response
114                 val logsEnv = logs.toString().asJsonPrimitive()
115                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logsEnv)
116
117                 if (prepareEnvOutput.status != StatusType.SUCCESS) {
118                     setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
119                     setNodeOutputErrors(prepareEnvOutput.status.name, logsEnv)
120                 } else {
121                     setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(), logsEnv, "".asJsonPrimitive())
122                 }
123             }
124
125             // if Env preparation was successful, then proceed with command execution in this Env
126             if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
127                 // Populate command execution properties and pass it to the remote server
128                 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
129
130                 val remoteExecutionInput = RemoteScriptExecutionInput(
131                         requestId = processId,
132                         remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
133                         command = scriptCommand,
134                         properties = properties)
135                 val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
136
137                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
138                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
139                     setNodeOutputErrors(remoteExecutionOutput.status.name, logs, remoteExecutionOutput.payload)
140                 } else {
141                     setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
142                             remoteExecutionOutput.payload)
143                 }
144             }
145         } catch (e: Exception) {
146             log.error("Failed to process on remote executor", e)
147         } finally {
148             remoteScriptExecutionService.close()
149         }
150     }
151
152     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
153         bluePrintRuntimeService.getBluePrintError()
154             .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
155     }
156
157     private fun formatNestedJsonNode(node: JsonNode): String {
158         val sb = StringBuilder()
159         if (node.isValueNode) {
160             sb.append(" $node")
161         } else {
162             node.forEach { sb.append(" $it") }
163         }
164         return sb.toString()
165     }
166
167     /**
168      * Utility function to set the output properties of the executor node
169      */
170     private fun setNodeOutputProperties(status: JsonNode, message: JsonNode, artifacts: JsonNode) {
171         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
172         log.info("Executor status   : $status")
173         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
174         log.info("Executor artifacts: $artifacts")
175         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
176         log.info("Executor message  : $message")
177     }
178
179     /**
180      * Utility function to set the output properties and errors of the executor node, in cas of errors
181      */
182     private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive()  ) {
183         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
184         log.info("Executor status   : $status")
185         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
186         log.info("Executor message  : $message")
187         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
188         log.info("Executor artifacts: $artifacts")
189
190         addError(status, ATTRIBUTE_EXEC_CMD_LOG, message.toString())
191     }
192 }