Add remote python executor DSL properties
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / services / execution-service / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / services / execution / RemoteScriptExecutionService.kt
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.services.execution
18
19 import com.fasterxml.jackson.databind.JsonNode
20 import com.google.protobuf.Struct
21 import com.google.protobuf.Timestamp
22 import com.google.protobuf.util.JsonFormat
23 import io.grpc.ManagedChannel
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
25 import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService
26 import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService
27 import org.onap.ccsdk.cds.controllerblueprints.command.api.*
28 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
29 import org.slf4j.LoggerFactory
30 import org.springframework.beans.factory.config.ConfigurableBeanFactory
31 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
32 import org.springframework.context.annotation.Scope
33 import org.springframework.stereotype.Service
34
35 interface RemoteScriptExecutionService {
36     suspend fun init(selector: Any)
37     suspend fun prepareEnv(prepareEnvInput: PrepareRemoteEnvInput): RemoteScriptExecutionOutput
38     suspend fun executeCommand(remoteExecutionInput: RemoteScriptExecutionInput): RemoteScriptExecutionOutput
39     suspend fun close()
40 }
41
42 @Service(ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION)
43 @ConditionalOnProperty(prefix = "blueprintprocessor.remoteScriptCommand", name = arrayOf("enabled"),
44         havingValue = "true", matchIfMissing = false)
45 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
46 class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService)
47     : RemoteScriptExecutionService {
48
49     private val log = LoggerFactory.getLogger(GrpcRemoteScriptExecutionService::class.java)!!
50
51     private var channel: ManagedChannel? = null
52     private lateinit var commandExecutorServiceGrpc: CommandExecutorServiceGrpc.CommandExecutorServiceBlockingStub
53
54     override suspend fun init(selector: Any) {
55         // Get the GRPC Client Service based on selector
56         val grpcClientService: BluePrintGrpcClientService
57         if (selector is JsonNode) {
58             grpcClientService = bluePrintGrpcLibPropertyService.blueprintGrpcClientService(selector)
59         } else {
60             grpcClientService = bluePrintGrpcLibPropertyService.blueprintGrpcClientService(selector.toString())
61         }
62         // Get the GRPC Channel
63         channel = grpcClientService.channel()
64         // Create Non Blocking Stub
65         commandExecutorServiceGrpc = CommandExecutorServiceGrpc.newBlockingStub(channel)
66
67         checkNotNull(commandExecutorServiceGrpc) {
68             "failed to create command executor grpc client for selector($selector)"
69         }
70     }
71
72     override suspend fun prepareEnv(prepareEnvInput: PrepareRemoteEnvInput)
73             : RemoteScriptExecutionOutput {
74         val grpResponse = commandExecutorServiceGrpc.prepareEnv(prepareEnvInput.asGrpcData())
75
76         checkNotNull(grpResponse.status) {
77             "failed to get GRPC prepare env response status for requestId(${prepareEnvInput.requestId})"
78         }
79
80         val remoteScriptExecutionOutput = grpResponse.asJavaData()
81         log.debug("Received prepare env response from command server for requestId(${prepareEnvInput.requestId})")
82
83         return remoteScriptExecutionOutput
84     }
85
86     override suspend fun executeCommand(remoteExecutionInput: RemoteScriptExecutionInput)
87             : RemoteScriptExecutionOutput {
88
89         val grpResponse = commandExecutorServiceGrpc.executeCommand(remoteExecutionInput.asGrpcData())
90
91         checkNotNull(grpResponse.status) {
92             "failed to get GRPC response status for requestId(${remoteExecutionInput.requestId})"
93         }
94
95         val remoteScriptExecutionOutput = grpResponse.asJavaData()
96         log.debug("Received response from command server for requestId(${remoteExecutionInput.requestId})")
97
98         return remoteScriptExecutionOutput
99     }
100
101     override suspend fun close() {
102         channel?.shutdownNow()
103     }
104
105
106     fun PrepareRemoteEnvInput.asGrpcData(): PrepareEnvInput {
107         val correlationId = this.correlationId ?: this.requestId
108
109         val packageList = mutableListOf<Packages>()
110
111         this.packages.toList().forEach {
112             val pckage = Packages.newBuilder()
113             JsonFormat.parser().merge(it.toString(), pckage)
114             packageList.add(pckage.build())
115         }
116
117         return PrepareEnvInput.newBuilder()
118                 .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
119                 .setRequestId(this.requestId)
120                 .setCorrelationId(correlationId)
121                 .setTimeOut(this.timeOut.toInt())
122                 .addAllPackages(packageList)
123                 .setProperties(this.properties.asGrpcData())
124                 .build()
125     }
126
127     fun RemoteScriptExecutionInput.asGrpcData(): ExecutionInput {
128         val correlationId = this.correlationId ?: this.requestId
129         return ExecutionInput.newBuilder()
130                 .setRequestId(this.requestId)
131                 .setCorrelationId(correlationId)
132                 .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
133                 .setCommand(this.command)
134                 .setTimeOut(this.timeOut.toInt())
135                 .setProperties(this.properties.asGrpcData())
136                 .setTimestamp(Timestamp.getDefaultInstance())
137                 .build()
138     }
139
140     fun RemoteIdentifier.asGrpcData(): Identifiers? {
141         return Identifiers.newBuilder()
142                 .setBlueprintName(this.blueprintName)
143                 .setBlueprintVersion(this.blueprintVersion)
144                 .build()
145     }
146
147     fun Map<String, JsonNode>.asGrpcData(): Struct {
148         val struct = Struct.newBuilder()
149         JsonFormat.parser().merge(JacksonUtils.getJson(this), struct)
150         return struct.build()
151     }
152
153     fun ExecutionOutput.asJavaData(): RemoteScriptExecutionOutput {
154         return RemoteScriptExecutionOutput(
155                 requestId = this.requestId,
156                 response = this.responseList,
157                 status = StatusType.valueOf(this.status.name)
158         )
159     }
160
161 }