6437cdf03f8388139b747d325406b697fc2be059
[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 org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
20 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
21 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
22 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
23 import org.onap.ccsdk.cds.controllerblueprints.command.api.ResponseStatus
24 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
25 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
26 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
27 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
28 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
29 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
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 import java.lang.Exception
37
38 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
39 @Component("component-remote-python-executor")
40 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
41 open class ComponentRemotePythonExecutor(private val remoteScriptExecutionService: RemoteScriptExecutionService)
42     : AbstractComponentFunction() {
43
44     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
45
46     companion object {
47         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
48         const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
49         const val INPUT_COMMAND = "command"
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 = getOperationInput(INPUT_DYNAMIC_PROPERTIES)
77         val command = getOperationInput(INPUT_COMMAND).asText()
78
79         // TODO("Python execution command and Resolve some expressions with dynamic properties")
80         val scriptCommand = command.replace(pythonScript.name, pythonScript.absolutePath)
81
82         val dependencies = operationAssignment.implementation?.dependencies
83
84         try {
85             // Open GRPC Connection
86             remoteScriptExecutionService.init(endPointSelector.asText())
87
88             var executionLogs = ""
89
90             // If dependencies are defined, then install in remote server
91             if (dependencies != null && dependencies.isNotEmpty()) {
92                 val prepareEnvInput = PrepareRemoteEnvInput(requestId = processId,
93                     remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName,
94                         blueprintVersion = blueprintVersion),
95                     remoteScriptType = RemoteScriptType.PYTHON,
96                     packages = dependencies
97                 )
98                 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
99                 executionLogs = prepareEnvOutput.response
100                 setOutput(executionLogs)
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                 remoteScriptType = RemoteScriptType.PYTHON,
110                 command = scriptCommand)
111             val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
112             executionLogs += remoteExecutionOutput.response
113             setOutput(executionLogs)
114             check(remoteExecutionOutput.status == StatusType.SUCCESS) {
115                 "failed to get prepare remote command response status for requestId(${remoteExecutionOutput.requestId})"
116             }
117
118         } catch (e: Exception) {
119             log.error("", e)
120         } finally {
121             remoteScriptExecutionService.close()
122         }
123     }
124
125     private fun setOutput(executionLogs: String) {
126         bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
127             "execution-logs", JacksonUtils.jsonNodeFromObject(executionLogs))
128     }
129
130     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
131         bluePrintRuntimeService.getBluePrintError()
132             .addError("Failed in ComponentJythonExecutor : ${runtimeException.message}")
133     }
134 }