6ad1e1f11899915753409228197c5fa59de9f29d
[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 = prepareEnvOutput.response
118                 val logsEnv = logs.toString().asJsonPrimitive()
119                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logsEnv)
120
121                 if (prepareEnvOutput.status != StatusType.SUCCESS) {
122                     setAttribute(ATTRIBUTE_EXEC_CMD_LOG, "N/A".asJsonPrimitive())
123                     setNodeOutputErrors(prepareEnvOutput.status.name, logsEnv)
124                 } else {
125                     setNodeOutputProperties(prepareEnvOutput.status.name.asJsonPrimitive(), logsEnv, "".asJsonPrimitive())
126                 }
127             }
128
129             // if Env preparation was successful, then proceed with command execution in this Env
130             if (bluePrintRuntimeService.getBluePrintError().errors.isEmpty()) {
131                 // Populate command execution properties and pass it to the remote server
132                 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
133
134                 val remoteExecutionInput = RemoteScriptExecutionInput(
135                     requestId = processId,
136                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
137                     command = scriptCommand,
138                     properties = properties,
139                     timeOut = timeout.toLong())
140
141
142                 val remoteExecutionOutputDeferred = GlobalScope.async {
143                     remoteScriptExecutionService.executeCommand(remoteExecutionInput)
144                 }
145
146                 val remoteExecutionOutput = withTimeout(timeout * 1000L) {
147                     remoteExecutionOutputDeferred.await()
148                 }
149
150                 checkNotNull(remoteExecutionOutput) {
151                     "Error: Request-id $processId did not return a restul from remote command execution."
152                 }
153
154
155                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
156                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
157                     setNodeOutputErrors(remoteExecutionOutput.status.name, logs, remoteExecutionOutput.payload)
158                 } else {
159                     setNodeOutputProperties(remoteExecutionOutput.status.name.asJsonPrimitive(), logs,
160                         remoteExecutionOutput.payload)
161                 }
162             }
163
164         } catch (timeoutEx: TimeoutCancellationException) {
165             setNodeOutputErrors(status = "Command executor timed out after $timeout seconds", message = "".asJsonPrimitive())
166             log.error("Command executor timed out after $timeout seconds", timeoutEx)
167         } catch (grpcEx: io.grpc.StatusRuntimeException) {
168             setNodeOutputErrors(status = "Command executor timed out in GRPC call", message = "${grpcEx.status}".asJsonPrimitive())
169             log.error("Command executor time out during GRPC call", grpcEx)
170         } catch (e: Exception) {
171             log.error("Failed to process on remote executor", e)
172         } finally {
173             remoteScriptExecutionService.close()
174         }
175     }
176
177     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
178         bluePrintRuntimeService.getBluePrintError()
179             .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
180     }
181
182     private fun formatNestedJsonNode(node: JsonNode): String {
183         val sb = StringBuilder()
184         if (node.isValueNode) {
185             sb.append(" $node")
186         } else {
187             node.forEach { sb.append(" $it") }
188         }
189         return sb.toString()
190     }
191
192     /**
193      * Utility function to set the output properties of the executor node
194      */
195     private fun setNodeOutputProperties(status: JsonNode, message: JsonNode, artifacts: JsonNode) {
196         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
197         log.info("Executor status   : $status")
198         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
199         log.info("Executor artifacts: $artifacts")
200         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
201         log.info("Executor message  : $message")
202     }
203
204     /**
205      * Utility function to set the output properties and errors of the executor node, in cas of errors
206      */
207     private fun setNodeOutputErrors(status: String, message: JsonNode, artifacts: JsonNode = "".asJsonPrimitive()) {
208         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
209         log.info("Executor status   : $status")
210         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
211         log.info("Executor message  : $message")
212         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
213         log.info("Executor artifacts: $artifacts")
214
215         addError(status, ATTRIBUTE_EXEC_CMD_LOG, message.toString())
216     }
217 }