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