fa5d882b02f6258da5ed1df2d5414456e7cd9ffc
[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
48         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
49         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
50     }
51
52     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
53
54         log.info("Processing : $operationInputs")
55
56         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
57         val blueprintName = bluePrintContext.name()
58         val blueprintVersion = bluePrintContext.version()
59
60         val operationAssignment: OperationAssignment = bluePrintContext
61                 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
62
63         val artifactName: String = operationAssignment.implementation?.primary
64                 ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
65
66         val artifactDefinition =
67                 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
68
69         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
70
71         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
72
73         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
74
75         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
76         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
77         val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
78
79         val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
80
81         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
82         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
83             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
84
85         val command = getOperationInput(INPUT_COMMAND).asText()
86         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
87         if (args != null && args.isNotEmpty()) {
88             scriptCommand = scriptCommand.plus(" ").plus(args)
89         }
90
91         try {
92             // Open GRPC Connection
93             remoteScriptExecutionService.init(endPointSelector.asText())
94
95             // If packages are defined, then install in remote server
96             if (packages != null) {
97                 val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
98                         remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
99                                 blueprintVersion = blueprintVersion),
100                         packages = packages
101                 )
102                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
103                 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
104                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response))
105                 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
106                 check(prepareEnvOutput.status == StatusType.SUCCESS) {
107                     "failed to get prepare remote env response status for requestId(${prepareEnvInput.requestId})"
108                 }
109             }
110             // Populate command execution properties and pass it to the remote server
111             val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
112
113             val remoteExecutionInput = RemoteScriptExecutionInput(
114                     requestId = processId,
115                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
116                     command = scriptCommand,
117                     properties = properties)
118             val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
119             log.info("$ATTRIBUTE_EXEC_CMD_LOG  - ${remoteExecutionOutput.response}")
120             setAttribute(ATTRIBUTE_EXEC_CMD_LOG, JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response))
121             check(remoteExecutionOutput.status == StatusType.SUCCESS) {
122                 "failed to get prepare remote command response status for requestId(${remoteExecutionOutput.requestId})"
123             }
124
125         } catch (e: Exception) {
126             log.error("Failed to process on remote executor", e)
127         } finally {
128             remoteScriptExecutionService.close()
129         }
130     }
131
132     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
133         bluePrintRuntimeService.getBluePrintError()
134                 .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}")
135     }
136
137     private fun formatNestedJsonNode(node: JsonNode): String {
138         val sb = StringBuilder()
139         if (node.isValueNode) {
140             sb.append(" $node")
141         } else {
142             node.forEach { sb.append(" $it") }
143         }
144         return sb.toString()
145     }
146 }