3250cd3a250852cc2a50173c3bcf50d58a4bded6
[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 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.*
25 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
26 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
27 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
28 import org.onap.ccsdk.cds.controllerblueprints.core.*
29 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import org.slf4j.LoggerFactory
32 import org.springframework.beans.factory.config.ConfigurableBeanFactory
33 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
34 import org.springframework.context.annotation.Scope
35 import org.springframework.stereotype.Component
36
37 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
38 @Component("component-remote-python-executor")
39 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
40 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService)
41     : AbstractComponentFunction() {
42
43     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
44
45     companion object {
46         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
47         const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
48         const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
49         const val INPUT_COMMAND = "command"
50         const val INPUT_PACKAGES = "packages"
51         const val DEFAULT_SELECTOR = "remote-python"
52
53         const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
54         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
55         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
56         const val ATTRIBUTE_RESPONSE_DATA = "response-data"
57     }
58
59     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
60
61         log.debug("Processing : $operationInputs")
62
63         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
64         val blueprintName = bluePrintContext.name()
65         val blueprintVersion = bluePrintContext.version()
66
67         val operationAssignment: OperationAssignment = bluePrintContext
68             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
69
70         val artifactName: String = operationAssignment.implementation?.primary
71             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
72
73         val artifactDefinition =
74             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
75
76         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
77
78         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
79
80         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
81
82         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
83         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
84         val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
85
86         val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
87
88         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
89         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
90             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
91
92         val command = getOperationInput(INPUT_COMMAND).asText()
93         var scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
94         if (args != null && args.isNotEmpty()) {
95             scriptCommand = scriptCommand.plus(" ").plus(args)
96         }
97
98         try {
99             // Open GRPC Connection
100             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
101                 remoteScriptExecutionService.init(endPointSelector.asText())
102             } else {
103                 // Get endpoint from DSL
104                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
105                 remoteScriptExecutionService.init(endPointSelectorJson)
106             }
107
108             // If packages are defined, then install in remote server
109             if (packages != null) {
110                 val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
111                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
112                         blueprintVersion = blueprintVersion),
113                     packages = packages
114                 )
115                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
116                 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
117                 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
118                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
119                 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
120
121                 if (prepareEnvOutput.status != StatusType.SUCCESS) {
122                     setNodeOutputErrors(prepareEnvOutput.status.name, logs)
123                 } else {
124                     setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(), logs, "".asJsonPrimitive())
125                 }
126             }
127
128             // Populate command execution properties and pass it to the remote server
129             val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
130
131             val remoteExecutionInput = RemoteScriptExecutionInput(
132                 requestId = processId,
133                 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
134                 command = scriptCommand,
135                 properties = properties,
136                 timeOut = timeout.toLong())
137
138
139             val remoteExecutionOutputDeferred = GlobalScope.async {
140                 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
141             }
142
143             val remoteExecutionOutput = withTimeout(timeout * 1000L) {
144                 remoteExecutionOutputDeferred.await()
145             }
146
147             checkNotNull(remoteExecutionOutput) {
148                 "Error: Request-id $processId did not return a restul from remote command execution."
149             }
150
151             val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
152             if (remoteExecutionOutput.status != StatusType.SUCCESS) {
153                 setNodeOutputErrors(remoteExecutionOutput.status.name, logs, remoteExecutionOutput.payload)
154             } else {
155                 setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
156                     remoteExecutionOutput.payload)
157             }
158
159         } catch (timeoutEx: TimeoutCancellationException) {
160             setNodeOutputErrors(status = "Command executor timed out after $timeout seconds", message = "".asJsonPrimitive())
161             log.error("Command executor timed out after $timeout seconds", timeoutEx)
162         } catch (grpcEx: io.grpc.StatusRuntimeException) {
163             setNodeOutputErrors(status = "Command executor timed out in GRPC call", message = "${grpcEx.status}".asJsonPrimitive())
164             log.error("Command executor time out during GRPC call", grpcEx)
165         } catch (e: Exception) {
166             log.error("Failed to process on remote executor", e)
167         } finally {
168             remoteScriptExecutionService.close()
169         }
170     }
171
172     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
173         bluePrintRuntimeService.getBluePrintError()
174             .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
175     }
176
177     private fun formatNestedJsonNode(node: JsonNode): String {
178         val sb = StringBuilder()
179         if (node.isValueNode) {
180             sb.append(" $node")
181         } else {
182             node.forEach { sb.append(" $it") }
183         }
184         return sb.toString()
185     }
186
187     /**
188      * Utility function to set the output properties of the executor node
189      */
190     private fun setNodeOutputProperties(status: JsonNode, message: JsonNode, artifacts: JsonNode) {
191         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
192         log.info("Executor status   : $status")
193         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
194         log.info("Executor artifacts: $artifacts")
195         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
196         log.info("Executor message  : $message")
197     }
198
199     /**
200      * Utility function to set the output properties and errors of the executor node, in cas of errors
201      */
202     private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive()) {
203         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
204         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
205         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
206
207         addError(status, ATTRIBUTE_EXEC_CMD_LOG, message.asText())
208     }
209 }