488e0d054941b9a8105dd4259c2cafa8454242e0
[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.node.MissingNode
20 import com.fasterxml.jackson.databind.node.NullNode
21 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
22 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
23 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
24 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
25 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
26 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
27 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
28 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
29 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
30 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
31 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
32 import org.slf4j.LoggerFactory
33 import org.springframework.beans.factory.config.ConfigurableBeanFactory
34 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
35 import org.springframework.context.annotation.Scope
36 import org.springframework.stereotype.Component
37 import java.lang.Exception
38
39 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
40 @Component("component-remote-python-executor")
41 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
42 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService)
43     : AbstractComponentFunction() {
44
45     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
46
47     companion object {
48         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
49         const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
50         const val INPUT_COMMAND = "command"
51         const val INPUT_PACKAGES = "packages"
52
53         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
54         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
55     }
56
57     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
58
59         log.info("Processing : $operationInputs")
60
61         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
62         val blueprintName = bluePrintContext.name()
63         val blueprintVersion = bluePrintContext.version()
64
65         val operationAssignment: OperationAssignment = bluePrintContext
66             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
67
68         val artifactName: String = operationAssignment.implementation?.primary
69             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
70
71         val artifactDefinition =
72             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
73
74         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
75
76         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
77
78         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
79
80         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
81         val dynamicProperties = getOperationInput(INPUT_DYNAMIC_PROPERTIES)
82         val command = getOperationInput(INPUT_COMMAND).asText()
83         val packages = getOperationInput(INPUT_PACKAGES)
84
85         // TODO("Python execution command and Resolve some expressions with dynamic properties")
86         val scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
87
88         try {
89             // Open GRPC Connection
90             remoteScriptExecutionService.init(endPointSelector.asText())
91
92             // If packages are defined, then install in remote server
93             if (packages !is MissingNode && packages !is NullNode) {
94                 val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
95                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
96                         blueprintVersion = blueprintVersion),
97                     packages = packages
98                 )
99                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
100                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, prepareEnvOutput.response.asJsonPrimitive())
101                 check(prepareEnvOutput.status == StatusType.SUCCESS) {
102                     "failed to get prepare remote env response status for requestId(${prepareEnvInput.requestId})"
103                 }
104             }
105
106             val remoteExecutionInput = RemoteScriptExecutionInput(
107                 requestId = processId,
108                 remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion),
109                 command = scriptCommand)
110             val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
111             setAttribute(ATTRIBUTE_EXEC_CMD_LOG, remoteExecutionOutput.response.asJsonPrimitive())
112             check(remoteExecutionOutput.status == StatusType.SUCCESS) {
113                 "failed to get prepare remote command response status for requestId(${remoteExecutionOutput.requestId})"
114             }
115
116         } catch (e: Exception) {
117             log.error("Failed to process on remote executor", e)
118         } finally {
119             remoteScriptExecutionService.close()
120         }
121     }
122
123     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
124         bluePrintRuntimeService.getBluePrintError()
125             .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}")
126     }
127 }