2 * Copyright © 2019 IBM.
3 * Modifications Copyright © 2020 Bell Canada.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.google.protobuf.ByteString
22 import kotlinx.coroutines.GlobalScope
23 import kotlinx.coroutines.TimeoutCancellationException
24 import kotlinx.coroutines.async
25 import kotlinx.coroutines.withTimeout
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
28 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
29 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
30 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
31 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionOutput
32 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptUploadBlueprintInput
33 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
34 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository
35 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
36 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
37 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
38 import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException
39 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
40 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
41 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
42 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
43 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
44 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
45 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
46 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
47 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
48 import org.slf4j.LoggerFactory
49 import org.springframework.beans.factory.config.ConfigurableBeanFactory
50 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
51 import org.springframework.context.annotation.Scope
52 import org.springframework.stereotype.Component
54 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
55 @Component("component-remote-python-executor")
56 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
57 open class ComponentRemotePythonExecutor(
58 private val remoteScriptExecutionService: RemoteScriptExecutionService,
59 private val bluePrintPropertiesService: BlueprintPropertiesService,
60 private val blueprintModelRepository: BlueprintModelRepository
61 ) : AbstractComponentFunction() {
63 private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
67 const val SELECTOR_CMD_EXEC = "blueprintsprocessor.remote-script-command"
68 const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
69 const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
70 const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
72 const val INPUT_COMMAND = "command"
73 const val INPUT_PACKAGES = "packages"
74 const val DEFAULT_SELECTOR = "remote-python"
75 const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
76 const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
78 const val STEP_PREPARE_ENV = "prepare-env"
79 const val STEP_EXEC_CMD = "execute-command"
80 const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
81 const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
82 const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
83 const val ATTRIBUTE_RESPONSE_DATA = "response-data"
84 const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
85 const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
86 const val TIMEOUT_DELTA = 100L
87 const val DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC = 30
90 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
92 log.debug("Processing : $operationInputs")
94 val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
96 val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
97 val blueprintName = bluePrintContext.name()
98 val blueprintVersion = bluePrintContext.version()
100 // fetch the template (plus cba bindata) from repository
101 val cbaModel = blueprintModelRepository.findByArtifactNameAndArtifactVersion(blueprintName, blueprintVersion)
102 val blueprintUUID = cbaModel?.id!!
103 val cbaBinData = ByteString.copyFrom(cbaModel?.blueprintModelContent?.content)
104 val archiveType = cbaModel?.blueprintModelContent?.contentType // TODO: should be enum
105 val remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion, blueprintUUID = blueprintUUID)
106 val originatorId = executionServiceInput.commonHeader.originatorId
107 val subRequestId = executionServiceInput.commonHeader.subRequestId
108 val requestId = processId
110 val operationAssignment: OperationAssignment = bluePrintContext
111 .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
113 val artifactName: String = operationAssignment.implementation?.primary
114 ?: throw BlueprintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
116 val artifactDefinition =
117 bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
119 checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
121 val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
123 checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
125 val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
126 val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
127 val packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
129 val argsNode = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
131 // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
132 val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
133 ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
135 val command = getOperationInput(INPUT_COMMAND).asText()
136 val cbaNameVerUuid = "blueprintName($blueprintName) blueprintVersion($blueprintVersion) blueprintUUID($blueprintUUID)"
139 * Timeouts that are specific to the command executor.
140 * Note: the interface->input->timeout is the component level timeout.
142 val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
143 ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
144 val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
145 ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
147 // component level timeout should be => env_prep_timeout + execution_timeout
148 val timeout = implementation.timeout
150 var scriptCommand = command.replace(pythonScript.name, artifactDefinition.file)
151 if (args != null && args.isNotEmpty()) {
152 scriptCommand = scriptCommand.plus(" ").plus(args)
156 // Open GRPC Connection
157 if (DEFAULT_SELECTOR == endPointSelector.asText()) {
158 remoteScriptExecutionService.init(endPointSelector.asText())
160 // Get endpoint from DSL
161 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
162 remoteScriptExecutionService.init(endPointSelectorJson)
165 // If packages are defined, then install in remote server
166 if (packages != null) {
167 val prepareEnvInput = PrepareRemoteEnvInput(
168 originatorId = executionServiceInput.commonHeader.originatorId,
169 requestId = processId,
170 subRequestId = executionServiceInput.commonHeader.subRequestId,
171 remoteIdentifier = remoteIdentifier,
173 timeOut = envPrepTimeout.toLong()
175 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
176 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
177 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
178 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
180 // there are no artifacts for env. prepare, but we reuse it for err_log...
181 if (prepareEnvOutput.status != StatusType.SUCCESS) {
182 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
183 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
185 setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
188 if (packages == null) {
189 // set env preparation log to empty...
190 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
192 prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
194 // in cases where the exception is caught in BP side due to timeout, we do not have `err_msg` returned by cmd-exec (inside `payload`),
195 // hence `artifact` field will be empty
197 } catch (grpcEx: io.grpc.StatusRuntimeException) {
198 val componentLevelWarningMsg =
199 if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
201 "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
202 // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
203 // set prepare-env-log to the error msg, and cmd-exec-log to empty
204 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
205 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
206 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
207 log.error(grpcErrMsg, grpcEx)
208 } catch (e: Exception) {
210 "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
211 // no environment prepare log from executor in case of timeout (as cmd-exec side hasn't finished to transfer output), set it to error msg. Execution logs is empty.
212 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
213 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
214 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
215 log.error(catchallErrMsg, e)
217 // if Env preparation was successful, then proceed with command execution in this Env
218 if (noBlueprintErrors()) {
220 // Populate command execution properties and pass it to the remote server
221 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
223 val remoteExecutionInput = RemoteScriptExecutionInput(
224 originatorId = executionServiceInput.commonHeader.originatorId,
225 requestId = processId,
226 subRequestId = executionServiceInput.commonHeader.subRequestId,
227 remoteIdentifier = remoteIdentifier,
228 command = scriptCommand,
229 properties = properties,
230 timeOut = executionTimeout.toLong()
233 val remoteExecutionOutputDeferred = GlobalScope.async {
234 remoteScriptExecutionService.executeCommand(remoteExecutionInput)
237 val remoteExecutionOutput = withTimeout(executionTimeout * 1000L + TIMEOUT_DELTA) {
238 remoteExecutionOutputDeferred.await()
241 checkNotNull(remoteExecutionOutput) {
242 "Error: Request-id $processId did not return a result from remote command execution."
244 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
245 val returnedPayload = remoteExecutionOutput.payload
246 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
247 // It would contain `err_msg` key. It is valid to return it.
248 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
249 setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
250 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
252 setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
253 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
254 } catch (timeoutEx: TimeoutCancellationException) {
255 val componentLevelWarningMsg =
256 if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
258 "Command executor execution timeout. DetailedMessage: (${timeoutEx.message}) requestId ($processId). $componentLevelWarningMsg"
259 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonType(), logging = isLogResponseEnabled)
260 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
261 log.error(timeoutErrMsg, timeoutEx)
262 } catch (grpcEx: io.grpc.StatusRuntimeException) {
264 "Command executor timed out executing after $executionTimeout seconds requestId ($processId) grpcErr: ${grpcEx.status}"
265 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonType(), logging = isLogResponseEnabled)
266 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
267 log.error(timeoutErrMsg, grpcEx)
268 } catch (e: Exception) {
270 "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
271 setNodeOutputErrors(STEP_PREPARE_ENV, listOf(catchAllErrMsg).asJsonType(), logging = isLogResponseEnabled)
272 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
273 log.error(catchAllErrMsg, e)
276 log.debug("Trying to close GRPC channel. request ($processId)")
277 remoteScriptExecutionService.close()
280 // wrapper for call to prepare_env step on cmd-exec - reupload CBA and call prepare env again if cmd-exec reported CBA uuid mismatch
281 private suspend fun prepareEnv(originatorId: String, requestId: String, subRequestId: String, remoteIdentifier: RemoteIdentifier, packages: JsonNode, envPrepTimeout: Int, cbaNameVerUuid: String, archiveType: String?, cbaBinData: ByteString?, isLogResponseEnabled: Boolean, innerCall: Boolean = false) {
282 val prepareEnvInput = PrepareRemoteEnvInput(
283 originatorId = originatorId,
284 requestId = requestId,
285 subRequestId = subRequestId,
286 remoteIdentifier = remoteIdentifier,
288 timeOut = envPrepTimeout.toLong()
290 val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
291 log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
292 val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
293 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
295 // there are no artifacts for env. prepare, but we reuse it for err_log...
296 if (prepareEnvOutput.status != StatusType.SUCCESS) {
297 // Check for the flag that blueprint is mismatched first, if so, reupload the blueprint
298 if (prepareEnvOutput.payload.has("reupload_cba")) {
299 log.info("Cmd-exec is missing the CBA $cbaNameVerUuid, it will be reuploaded.")
300 uploadCba(remoteIdentifier, requestId, subRequestId, originatorId, archiveType, cbaBinData, cbaNameVerUuid, prepareEnvOutput, isLogResponseEnabled, logs)
301 // call prepare_env again.
303 log.info("Calling prepare environment again")
304 prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
306 val errMsg = "Something is wrong: prepare_env step attempted to call itself too many times after upload CBA step!"
308 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
309 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, errMsg)
312 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
313 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
316 setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
320 private suspend fun uploadCba(remoteIdentifier: RemoteIdentifier, requestId: String, subRequestId: String, originatorId: String, archiveType: String?, cbaBinData: ByteString?, cbaNameVerUuid: String, prepareEnvOutput: RemoteScriptExecutionOutput, isLogResponseEnabled: Boolean, logs: JsonNode) {
322 val uploadCbaInput = RemoteScriptUploadBlueprintInput(
323 remoteIdentifier = remoteIdentifier,
324 requestId = requestId,
325 subRequestId = subRequestId,
326 originatorId = originatorId,
327 timeOut = DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC.toLong(),
328 archiveType = archiveType!!,
329 binData = cbaBinData!!
332 val cbaUploadOutput = remoteScriptExecutionService.uploadBlueprint(uploadCbaInput)
333 if (cbaUploadOutput.status != StatusType.SUCCESS) {
334 log.error("Error uploading CBA $cbaNameVerUuid error(${cbaUploadOutput.payload})")
335 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
336 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
338 log.info("Finished uploading CBA $cbaNameVerUuid")
342 private fun noBlueprintErrors() = bluePrintRuntimeService.getBlueprintError().errors.isEmpty()
344 override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
345 bluePrintRuntimeService.getBlueprintError()
346 .addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
349 private fun formatNestedJsonNode(node: JsonNode): String {
350 val sb = StringBuilder()
351 if (node.isValueNode) {
354 node.forEach { sb.append(" $it") }
360 * Utility function to set the output properties of the executor node
362 private fun setNodeOutputProperties(
365 executionLogs: JsonNode,
367 logging: Boolean = true
370 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
371 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
372 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
375 log.info("Executor status : $step : $status")
376 log.info("Executor logs : $step : $executionLogs")
377 log.info("Executor artifacts: $step : $artifacts")
382 * Utility function to set the output properties and errors of the executor node, in case of errors
384 private fun setNodeOutputErrors(
386 executionLogs: JsonNode = "[]".asJsonPrimitive(),
387 artifacts: JsonNode = "{}".asJsonPrimitive(),
388 logging: Boolean = true
390 val status = StatusType.FAILURE.name
391 setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
392 setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
393 setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
396 log.info("Executor status : $step : $status")
397 log.info("Executor logs : $step : $executionLogs")
398 log.info("Executor artifacts: $step : $artifacts")