Revert "Renaming Files having BluePrint to have Blueprint"
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / python-executor / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / python / executor / ComponentRemotePythonExecutor.kt
1 /*
2  *  Copyright Â© 2019 IBM.
3  *  Modifications Copyright © 2020 Bell Canada.
4  *
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.google.protobuf.ByteString
22 import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
23 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
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.RemoteScriptUploadBlueprintInput
29 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
30 import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository
31 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
32 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant
33 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService
34 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
35 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
36 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
37 import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists
38 import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank
39 import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
40 import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
41 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
42 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
43 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
44 import org.slf4j.LoggerFactory
45 import org.springframework.beans.factory.config.ConfigurableBeanFactory
46 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
47 import org.springframework.context.annotation.Scope
48 import org.springframework.stereotype.Component
49
50 @ConditionalOnBean(name = [ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION])
51 @Component("component-remote-python-executor")
52 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
53 open class ComponentRemotePythonExecutor(
54     private val remoteScriptExecutionService: RemoteScriptExecutionService,
55     private val bluePrintPropertiesService: BluePrintPropertiesService,
56     private val blueprintModelRepository: BlueprintModelRepository
57 ) : AbstractComponentFunction() {
58
59     private val log = LoggerFactory.getLogger(ComponentRemotePythonExecutor::class.java)!!
60
61     companion object {
62
63         const val SELECTOR_CMD_EXEC = "blueprintsprocessor.remote-script-command"
64         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
65         const val INPUT_DYNAMIC_PROPERTIES = "dynamic-properties"
66         const val INPUT_ARGUMENT_PROPERTIES = "argument-properties"
67
68         const val INPUT_COMMAND = "command"
69         const val INPUT_PACKAGES = "packages"
70         const val DEFAULT_SELECTOR = "remote-python"
71         const val INPUT_ENV_PREPARE_TIMEOUT = "env-prepare-timeout"
72         const val INPUT_EXECUTE_TIMEOUT = "execution-timeout"
73
74         const val STEP_PREPARE_ENV = "prepare-env"
75         const val STEP_EXEC_CMD = "execute-command"
76         const val ATTRIBUTE_EXEC_CMD_STATUS = "status"
77         const val ATTRIBUTE_PREPARE_ENV_LOG = "prepare-environment-logs"
78         const val ATTRIBUTE_EXEC_CMD_LOG = "execute-command-logs"
79         const val ATTRIBUTE_RESPONSE_DATA = "response-data"
80         const val DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC = 120
81         const val DEFAULT_EXECUTE_TIMEOUT_IN_SEC = 180
82         const val TIMEOUT_DELTA = 100L
83         const val DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC = 30
84     }
85
86     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
87
88         log.debug("Processing : $operationInputs")
89
90         val isLogResponseEnabled = bluePrintPropertiesService.propertyBeanType("$SELECTOR_CMD_EXEC.response.log.enabled", Boolean::class.java)
91
92         val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
93         val blueprintName = bluePrintContext.name()
94         val blueprintVersion = bluePrintContext.version()
95
96         // fetch the template (plus cba bindata) from repository
97         val cbaModel = blueprintModelRepository.findByArtifactNameAndArtifactVersion(blueprintName, blueprintVersion)
98         val blueprintUUID = cbaModel?.id!!
99         val cbaBinData = ByteString.copyFrom(cbaModel?.blueprintModelContent?.content)
100         val archiveType = cbaModel?.blueprintModelContent?.contentType // TODO: should be enum
101         val remoteIdentifier = RemoteIdentifier(blueprintName = blueprintName, blueprintVersion = blueprintVersion, blueprintUUID = blueprintUUID)
102         val originatorId = executionServiceInput.commonHeader.originatorId
103         val subRequestId = executionServiceInput.commonHeader.subRequestId
104         val requestId = processId
105
106         val operationAssignment: OperationAssignment = bluePrintContext
107             .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName)
108
109         val artifactName: String = operationAssignment.implementation?.primary
110             ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
111
112         val artifactDefinition =
113             bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
114
115         checkNotBlank(artifactDefinition.file) { "couldn't get python script path($artifactName)" }
116
117         val pythonScript = normalizedFile(bluePrintContext.rootPath, artifactDefinition.file)
118
119         checkFileExists(pythonScript) { "python script(${pythonScript.absolutePath}) doesn't exists" }
120
121         val endPointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
122         val dynamicProperties = getOptionalOperationInput(INPUT_DYNAMIC_PROPERTIES)
123         var packages = getOptionalOperationInput(INPUT_PACKAGES)?.returnNullIfMissing()
124
125         // This prevents unescaping values, as well as quoting the each parameter, in order to allow for spaces in values
126         val args = getOptionalOperationInput(INPUT_ARGUMENT_PROPERTIES)?.returnNullIfMissing()
127             ?.rootFieldsToMap()?.toSortedMap()?.values?.joinToString(" ") { formatNestedJsonNode(it) }
128
129         val command = getOperationInput(INPUT_COMMAND).asText()
130         val cbaNameVerUuid = "blueprintName($blueprintName) blueprintVersion($blueprintVersion) blueprintUUID($blueprintUUID)"
131
132         /**
133          * Timeouts that are specific to the command executor.
134          * Note: the interface->input->timeout is the component level timeout.
135          */
136         val envPrepTimeout = getOptionalOperationInput(INPUT_ENV_PREPARE_TIMEOUT)?.asInt()
137             ?: DEFAULT_ENV_PREPARE_TIMEOUT_IN_SEC
138         val executionTimeout = getOptionalOperationInput(INPUT_EXECUTE_TIMEOUT)?.asInt()
139             ?: DEFAULT_EXECUTE_TIMEOUT_IN_SEC
140
141         // component level timeout should be => env_prep_timeout + execution_timeout
142         val timeout = implementation.timeout
143
144         var scriptCommand = command.replace(pythonScript.name, artifactDefinition.file)
145         if (args != null && args.isNotEmpty()) {
146             scriptCommand = scriptCommand.plus(" ").plus(args)
147         }
148
149         try {
150             // Open GRPC Connection
151             if (DEFAULT_SELECTOR == endPointSelector.asText()) {
152                 remoteScriptExecutionService.init(endPointSelector.asText())
153             } else {
154                 // Get endpoint from DSL
155                 val endPointSelectorJson = bluePrintRuntimeService.resolveDSLExpression(endPointSelector.asText())
156                 remoteScriptExecutionService.init(endPointSelectorJson)
157             }
158
159             // If packages are defined, then install in remote server
160             if (packages == null) {
161                 // set env preparation log to empty...
162                 setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, "".asJsonPrimitive())
163                 packages = mutableListOf<Object>().asJsonType()
164             }
165             prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled)
166             // 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`),
167             // hence `artifact` field will be empty
168         } catch (grpcEx: io.grpc.StatusRuntimeException) {
169             val componentLevelWarningMsg =
170                 if (timeout < envPrepTimeout) "Note: component-level timeout ($timeout) is shorter than env-prepare timeout ($envPrepTimeout). " else ""
171             val grpcErrMsg =
172                 "Command failed during env. preparation... timeout($envPrepTimeout) requestId ($processId).$componentLevelWarningMsg grpcError: (${grpcEx.cause?.message})"
173             // no execution log in case of timeout (as cmd-exec side hasn't finished to transfer output)
174             // set prepare-env-log to the error msg, and cmd-exec-log to empty
175             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, grpcErrMsg.asJsonPrimitive())
176             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
177             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, grpcErrMsg)
178             log.error(grpcErrMsg, grpcEx)
179         } catch (e: Exception) {
180             val catchallErrMsg =
181                 "Command executor failed during env. preparation.. catch-all case. timeout($envPrepTimeout) requestId ($processId). exception msg: ${e.message}"
182             // 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.
183             setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, catchallErrMsg.asJsonPrimitive())
184             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), "{}".asJsonPrimitive(), isLogResponseEnabled)
185             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, catchallErrMsg)
186             log.error(catchallErrMsg, e)
187         }
188         // if Env preparation was successful, then proceed with command execution in this Env
189         if (noBlueprintErrors()) {
190             try {
191                 // Populate command execution properties and pass it to the remote server
192                 val properties = dynamicProperties?.returnNullIfMissing()?.rootFieldsToMap() ?: hashMapOf()
193
194                 val remoteExecutionInput = RemoteScriptExecutionInput(
195                     originatorId = executionServiceInput.commonHeader.originatorId,
196                     requestId = processId,
197                     subRequestId = executionServiceInput.commonHeader.subRequestId,
198                     remoteIdentifier = remoteIdentifier,
199                     command = scriptCommand,
200                     properties = properties,
201                     timeOut = executionTimeout.toLong()
202                 )
203
204                 val remoteExecutionOutput = remoteScriptExecutionService.executeCommand(remoteExecutionInput)
205
206                 checkNotNull(remoteExecutionOutput) {
207                     "Error: Request-id $processId did not return a result from remote command execution."
208                 }
209                 val logs = JacksonUtils.jsonNodeFromObject(remoteExecutionOutput.response)
210                 val returnedPayload = remoteExecutionOutput.payload
211                 // In case of execution, `payload` (dictionary from Python execution) is preserved in `remoteExecutionOutput.payload`;
212                 // It would contain `err_msg` key. It is valid to return it.
213                 if (remoteExecutionOutput.status != StatusType.SUCCESS) {
214                     setNodeOutputErrors(STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
215                     addError(StatusType.FAILURE.name, STEP_EXEC_CMD, logs.toString())
216                 } else {
217                     setNodeOutputProperties(remoteExecutionOutput.status, STEP_EXEC_CMD, logs, returnedPayload, isLogResponseEnabled)
218                 } // In timeout exception cases, we don't have payload, hence `payload` is empty value.
219             } catch (grpcEx: io.grpc.StatusRuntimeException) {
220                 val componentLevelWarningMsg =
221                     if (timeout < executionTimeout) "Note: component-level timeout ($timeout) is shorter than execution timeout ($executionTimeout). " else ""
222                 val timeoutErrMsg =
223                     "Command executor timed out executing after $executionTimeout seconds requestId ($processId). $componentLevelWarningMsg grpcErr: ${grpcEx.status}"
224                 setNodeOutputErrors(STEP_EXEC_CMD, listOf(timeoutErrMsg).asJsonType(), logging = isLogResponseEnabled)
225                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, timeoutErrMsg)
226                 log.error(timeoutErrMsg, grpcEx)
227             } catch (e: Exception) {
228                 val catchAllErrMsg =
229                     "Command executor failed during process catch-all case requestId ($processId) timeout($envPrepTimeout) exception msg: ${e.message}"
230                 setNodeOutputErrors(STEP_PREPARE_ENV, listOf(catchAllErrMsg).asJsonType(), logging = isLogResponseEnabled)
231                 addError(StatusType.FAILURE.name, STEP_EXEC_CMD, catchAllErrMsg)
232                 log.error(catchAllErrMsg, e)
233             }
234         }
235         log.debug("Trying to close GRPC channel. request ($processId)")
236         remoteScriptExecutionService.close()
237     }
238
239     // wrapper for call to prepare_env step on cmd-exec - reupload CBA and call prepare env again if cmd-exec reported CBA uuid mismatch
240     private suspend fun prepareEnv(originatorId: String, requestId: String, subRequestId: String, remoteIdentifier: RemoteIdentifier, packages: JsonNode, envPrepTimeout: Int, cbaNameVerUuid: String, archiveType: String?, cbaBinData: ByteString?, isLogResponseEnabled: Boolean, retries: Int = 3) {
241         val prepareEnvInput = PrepareRemoteEnvInput(
242             originatorId = originatorId,
243             requestId = requestId,
244             subRequestId = subRequestId,
245             remoteIdentifier = remoteIdentifier,
246             packages = packages,
247             timeOut = envPrepTimeout.toLong()
248         )
249         val prepareEnvOutput = remoteScriptExecutionService.prepareEnv(prepareEnvInput)
250         log.info("$ATTRIBUTE_PREPARE_ENV_LOG - ${prepareEnvOutput.response}")
251         val logs = JacksonUtils.jsonNodeFromObject(prepareEnvOutput.response)
252         setAttribute(ATTRIBUTE_PREPARE_ENV_LOG, logs)
253
254         // there are no artifacts for env. prepare, but we reuse it for err_log...
255         if (prepareEnvOutput.status != StatusType.SUCCESS) {
256             // Check for the flag that blueprint is mismatched first, if so, reupload the blueprint
257             if (prepareEnvOutput.payload.has("reupload_cba")) {
258                 log.info("Cmd-exec is missing the CBA $cbaNameVerUuid, it will be reuploaded.")
259                 uploadCba(remoteIdentifier, requestId, subRequestId, originatorId, archiveType, cbaBinData, cbaNameVerUuid, prepareEnvOutput, isLogResponseEnabled, logs)
260                 // call prepare_env again.
261                 if (retries > 0) {
262                     log.info("Calling prepare environment again")
263                     prepareEnv(originatorId, requestId, subRequestId, remoteIdentifier, packages, envPrepTimeout, cbaNameVerUuid, archiveType, cbaBinData, isLogResponseEnabled, retries - 1)
264                 } else {
265                     val errMsg = "Something is wrong: prepare_env step attempted to call itself too many times after upload CBA step!"
266                     log.error(errMsg)
267                     setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
268                     addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, errMsg)
269                 }
270             } else {
271                 setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
272                 addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
273             }
274         } else {
275             setNodeOutputProperties(prepareEnvOutput.status, STEP_PREPARE_ENV, logs, prepareEnvOutput.payload, isLogResponseEnabled)
276         }
277     }
278
279     private suspend fun uploadCba(remoteIdentifier: RemoteIdentifier, requestId: String, subRequestId: String, originatorId: String, archiveType: String?, cbaBinData: ByteString?, cbaNameVerUuid: String, prepareEnvOutput: RemoteScriptExecutionOutput, isLogResponseEnabled: Boolean, logs: JsonNode) {
280         val uploadCbaInput = RemoteScriptUploadBlueprintInput(
281             remoteIdentifier = remoteIdentifier,
282             requestId = requestId,
283             subRequestId = subRequestId,
284             originatorId = originatorId,
285             timeOut = DEFAULT_CBA_UPLOAD_TIMEOUT_IN_SEC.toLong(),
286             archiveType = archiveType!!,
287             binData = cbaBinData!!
288         )
289
290         val cbaUploadOutput = remoteScriptExecutionService.uploadBlueprint(uploadCbaInput)
291         if (cbaUploadOutput.status != StatusType.SUCCESS) {
292             log.error("Error uploading CBA $cbaNameVerUuid error(${cbaUploadOutput.payload})")
293             setNodeOutputErrors(STEP_PREPARE_ENV, "[]".asJsonPrimitive(), prepareEnvOutput.payload, isLogResponseEnabled)
294             addError(StatusType.FAILURE.name, STEP_PREPARE_ENV, logs.toString())
295         } else {
296             log.info("Finished uploading CBA $cbaNameVerUuid")
297         }
298     }
299
300     private fun noBlueprintErrors() =
301         bluePrintRuntimeService.getBluePrintError().stepErrors(stepName).isNullOrEmpty()
302
303     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
304         addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}")
305     }
306
307     private fun formatNestedJsonNode(node: JsonNode): String {
308         val sb = StringBuilder()
309         if (node.isValueNode) {
310             sb.append(" $node")
311         } else {
312             node.forEach { sb.append(" $it") }
313         }
314         return sb.toString()
315     }
316
317     /**
318      * Utility function to set the output properties of the executor node
319      */
320     private fun setNodeOutputProperties(
321         status: StatusType,
322         step: String,
323         executionLogs: JsonNode,
324         artifacts: JsonNode,
325         logging: Boolean = true
326     ) {
327
328         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.name.asJsonPrimitive())
329         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
330         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
331
332         if (logging) {
333             log.info("Executor status : $step : $status")
334             log.info("Executor logs   : $step : $executionLogs")
335             log.info("Executor artifacts: $step : $artifacts")
336         }
337     }
338
339     /**
340      * Utility function to set the output properties and errors of the executor node, in case of errors
341      */
342     private fun setNodeOutputErrors(
343         step: String,
344         executionLogs: JsonNode = "[]".asJsonPrimitive(),
345         artifacts: JsonNode = "{}".asJsonPrimitive(),
346         logging: Boolean = true
347     ) {
348         val status = StatusType.FAILURE.name
349         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
350         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, executionLogs)
351         setAttribute(ATTRIBUTE_RESPONSE_DATA, artifacts)
352
353         if (logging) {
354             log.info("Executor status : $step : $status")
355             log.info("Executor logs   : $step : $executionLogs")
356             log.info("Executor artifacts: $step : $artifacts")
357         }
358     }
359 }