Enabling Code Formatter
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / ansible-awx-executor / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / ansible / executor / ComponentRemoteAnsibleExecutor.kt
1 /*
2  *  Copyright © 2019 Bell Canada.
3  *  Modifications Copyright © 2018-2019 IBM.
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.ansible.executor
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.fasterxml.jackson.databind.ObjectMapper
22 import com.fasterxml.jackson.databind.node.TextNode
23 import kotlinx.coroutines.delay
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
25 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
26 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
27 import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
28 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode
29 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
30 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
31 import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing
32 import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
33 import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap
34 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
35 import org.slf4j.LoggerFactory
36 import org.springframework.beans.factory.config.ConfigurableBeanFactory
37 import org.springframework.context.annotation.Scope
38 import org.springframework.http.HttpMethod
39 import org.springframework.stereotype.Component
40 import java.net.URI
41 import java.net.URLEncoder
42 import java.util.NoSuchElementException
43
44 /**
45  * ComponentRemoteAnsibleExecutor
46  *
47  * Component that launches a run of a job template (INPUT_JOB_TEMPLATE_NAME) representing an Ansible playbook,
48  * and its parameters, via the AWX server identified by the INPUT_ENDPOINT_SELECTOR parameter.
49  *
50  * It supports extra_vars, limit, tags, skip-tags, inventory (by name or Id) Ansible parameters.
51  * It reports the results of the execution via properties, named execute-command-status and execute-command-logs
52  *
53  * @author Serge Simard
54  */
55 @Component("component-remote-ansible-executor")
56 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
57 open class ComponentRemoteAnsibleExecutor(
58     private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService,
59     private val mapper: ObjectMapper
60 ) :
61     AbstractComponentFunction() {
62
63     // HTTP related constants
64     private val HTTP_SUCCESS = 200..202
65     private val GET = HttpMethod.GET.name
66     private val POST = HttpMethod.POST.name
67     private val plainTextHeaders = mapOf("Accept" to "text/plain")
68
69     var checkDelay: Long = 15_000
70
71     companion object {
72
73         private val log = LoggerFactory.getLogger(ComponentRemoteAnsibleExecutor::class.java)
74
75         // input fields names accepted by this executor
76         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
77         const val INPUT_JOB_TEMPLATE_NAME = "job-template-name"
78         const val INPUT_WORKFLOW_JOB_TEMPLATE_NAME = "workflow-job-template-id"
79         const val INPUT_LIMIT_TO_HOST = "limit"
80         const val INPUT_INVENTORY = "inventory"
81         const val INPUT_EXTRA_VARS = "extra-vars"
82         const val INPUT_TAGS = "tags"
83         const val INPUT_SKIP_TAGS = "skip-tags"
84
85         // output fields names (and values) populated by this executor; aligned with job details status field values.
86         const val ATTRIBUTE_EXEC_CMD_ARTIFACTS = "ansible-artifacts"
87         const val ATTRIBUTE_EXEC_CMD_STATUS = "ansible-command-status"
88         const val ATTRIBUTE_EXEC_CMD_LOG = "ansible-command-logs"
89         const val ATTRIBUTE_EXEC_CMD_STATUS_ERROR = "error"
90     }
91
92     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
93
94         try {
95             val restClientService = getAWXRestClient()
96
97             // Get either a job template name or a workflow template name property
98             var workflowURIPrefix = ""
99             var jobTemplateName = getOperationInput(INPUT_JOB_TEMPLATE_NAME).returnNullIfMissing()?.textValue() ?: ""
100             val isWorkflowJT = jobTemplateName.isBlank()
101             if (isWorkflowJT) {
102                 jobTemplateName = getOperationInput(INPUT_WORKFLOW_JOB_TEMPLATE_NAME).asText()
103                 workflowURIPrefix = "workflow_"
104             }
105
106             val jtId = lookupJobTemplateIDByName(restClientService, jobTemplateName, workflowURIPrefix)
107             if (jtId.isNotEmpty()) {
108                 runJobTemplateOnAWX(restClientService, jobTemplateName, jtId, workflowURIPrefix)
109             } else {
110                 val message = "Workflow/Job template $jobTemplateName does not exists"
111                 log.error(message)
112                 setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
113             }
114         } catch (e: Exception) {
115             log.error("Failed to process on remote executor (${e.message})", e)
116             setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, "Failed to process on remote executor (${e.message})")
117         }
118     }
119
120     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
121         val message = "Error in ComponentRemoteAnsibleExecutor : ${runtimeException.message}"
122         log.error(message, runtimeException)
123         setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
124     }
125
126     /** Creates a TokenAuthRestClientService, since this executor expect type property to be "token-auth" and the
127      * token to be an OAuth token (access_token response field) generated via the AWX /api/o/token rest endpoint
128      * The token field is of the form "Bearer access_token_from_response", for example :
129      *  "blueprintsprocessor.restclient.awx.type=token-auth"
130      *  "blueprintsprocessor.restclient.awx.url=http://awx-endpoint"
131      *  "blueprintsprocessor.restclient.awx.token=Bearer J9gEtMDzxcqw25574fioY9VAhLDIs1"
132      *
133      * Also supports json endpoint definition via DSL entry, e.g.:
134      *     "ansible-remote-endpoint": {
135      *        "type": "token-auth",
136      *        "url": "http://awx-endpoint",
137      *        "token": "Bearer J9gEtMDzxcqw25574fioY9VAhLDIs1"
138      *     }
139      */
140     private fun getAWXRestClient(): BlueprintWebClientService {
141
142         val endpointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
143
144         try {
145             return blueprintRestLibPropertyService.blueprintWebClientService(endpointSelector)
146         } catch (e: NoSuchElementException) {
147             throw IllegalArgumentException("No value provided for input selector $endpointSelector", e)
148         }
149     }
150
151     /**
152      * Finds the job template ID based on the job template name provided in the request
153      */
154     private fun lookupJobTemplateIDByName(
155         awxClient: BlueprintWebClientService,
156         job_template_name: String?,
157         workflowPrefix: String
158     ): String {
159         val encodedJTName = URI(
160             null, null,
161             "/api/v2/${workflowPrefix}job_templates/$job_template_name/",
162             null, null
163         ).rawPath
164
165         // Get Job Template details by name
166         var response = awxClient.exchangeResource(GET, encodedJTName, "")
167         val jtDetails: JsonNode = mapper.readTree(response.body)
168         return jtDetails.at("/id").asText()
169     }
170
171     /**
172      * Performs the job template execution on AWX, ie. prepare arguments as per job template
173      * requirements (ask fields) and provided overriding values. Then it launches the run, and monitors
174      * its execution. Finally, it retrieves the job results via the stdout api.
175      * The status and output attributes are populated in the process.
176      */
177     private suspend fun runJobTemplateOnAWX(
178         awxClient: BlueprintWebClientService,
179         job_template_name: String?,
180         jtId: String,
181         workflowPrefix: String
182     ) {
183         setNodeOutputProperties("preparing".asJsonPrimitive(), "".asJsonPrimitive(), "".asJsonPrimitive())
184
185         // Get Job Template requirements
186         var response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}job_templates/$jtId/launch/", "")
187         // FIXME: handle non-successful SC
188         val jtLaunchReqs: JsonNode = mapper.readTree(response.body)
189         val payload = prepareLaunchPayload(awxClient, jtLaunchReqs, workflowPrefix.isNotBlank())
190
191         log.info("Running job with $payload, for requestId $processId.")
192
193         // Launch the job for the targeted template
194         var jtLaunched: JsonNode = JacksonUtils.objectMapper.createObjectNode()
195         response = awxClient.exchangeResource(POST, "/api/v2/${workflowPrefix}job_templates/$jtId/launch/", payload)
196         if (response.status in HTTP_SUCCESS) {
197             jtLaunched = mapper.readTree(response.body)
198             val fieldsIgnored: JsonNode = jtLaunched.at("/ignored_fields")
199             if (fieldsIgnored.rootFieldsToMap().isNotEmpty()) {
200                 log.warn("Ignored fields : $fieldsIgnored, for requestId $processId.")
201             }
202         }
203
204         if (response.status in HTTP_SUCCESS) {
205             val jobId: String = jtLaunched.at("/id").asText()
206
207             // Poll current job status while job is not executed
208             var jobStatus = "unknown"
209             var jobEndTime = "null"
210             while (jobEndTime == "null") {
211                 response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}jobs/$jobId/", "")
212                 val jobLaunched: JsonNode = mapper.readTree(response.body)
213                 jobStatus = jobLaunched.at("/status").asText()
214                 jobEndTime = jobLaunched.at("/finished").asText()
215                 delay(checkDelay)
216             }
217
218             log.info("Execution of job template $job_template_name in job #$jobId finished with status ($jobStatus) for requestId $processId")
219
220             populateJobRunResponse(awxClient, jobId, workflowPrefix, jobStatus)
221         } else {
222             // The job template requirements were not fulfilled with the values passed in. The message below will
223             // provide more information via the response, like the ignored_fields, or variables_needed_to_start,
224             // or resources_needed_to_start, in order to help user pinpoint the problems with the request.
225             val message = "Execution of job template $job_template_name could not be started for requestId $processId." +
226                 " (Response: ${response.body}) "
227             log.error(message)
228             setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
229         }
230     }
231
232     /**
233      * Extracts the output from either a job stdout call OR collects the workflow run output, as well as the artifacts
234      * and populate the component corresponding output properties
235      */
236     private fun populateJobRunResponse(
237         awxClient: BlueprintWebClientService,
238         jobId: String,
239         workflowPrefix: String,
240         jobStatus: String
241     ) {
242
243         val collectedResponses = StringBuilder(4096)
244         val artifacts: MutableMap<String, JsonNode> = mutableMapOf()
245
246         collectJobIdsRelatedToJobRun(awxClient, jobId, workflowPrefix).forEach { aJobId ->
247
248             // Collect the response text from the corresponding jobIds
249             var response = awxClient.exchangeResource(GET, "/api/v2/jobs/$aJobId/stdout/?format=txt", "", plainTextHeaders)
250             if (response.status in HTTP_SUCCESS) {
251                 val jobOutput = response.body
252                 collectedResponses
253                     .append("Output for Job $aJobId :" + System.lineSeparator())
254                     .append(jobOutput)
255                     .append(System.lineSeparator())
256                 log.info("Response for job $aJobId: \n $jobOutput \n")
257             } else {
258                 log.warn("Could not gather response for job $aJobId. Status=${response.status}")
259             }
260
261             // Collect artifacts variables from each job and gather them up in one json node
262             response = awxClient.exchangeResource(GET, "/api/v2/jobs/$aJobId/", "")
263             if (response.status in HTTP_SUCCESS) {
264                 val jobArtifacts = mapper.readTree(response.body).at("/artifacts")
265                 if (jobArtifacts != null) {
266                     artifacts.putAll(jobArtifacts.rootFieldsToMap())
267                 }
268             }
269         }
270
271         log.info("Artifacts for job $jobId: \n $artifacts \n")
272
273         setNodeOutputProperties(jobStatus.asJsonPrimitive(), collectedResponses.toString().asJsonPrimitive(), artifacts.asJsonNode())
274     }
275
276     /**
277      * List all the job Ids for a give workflow, i.e. sub jobs, or the jobId if not a workflow instance
278      */
279     private fun collectJobIdsRelatedToJobRun(awxClient: BlueprintWebClientService, jobId: String, workflowPrefix: String): Array<String> {
280
281         var jobIds: Array<String>
282
283         if (workflowPrefix.isNotEmpty()) {
284             var response = awxClient.exchangeResource(GET, "/api/v2/${workflowPrefix}jobs/$jobId/workflow_nodes/", "")
285             val jobDetails = mapper.readTree(response.body).at("/results")
286
287             // gather up job Id of all actual job nodes that ran during the workflow
288             jobIds = emptyArray()
289             for (jobDetail in jobDetails.elements()) {
290                 if (jobDetail.at("/do_not_run").asText() == "false") {
291                     jobIds = jobIds.plus(jobDetail.at("/summary_fields/job/id").asText())
292                 }
293             }
294         } else {
295             jobIds = arrayOf(jobId)
296         }
297         return jobIds
298     }
299
300     /**
301      * Prepares the JSON payload expected by the job template api,
302      * by applying the overrides that were provided
303      * and allowed by the template definition flags in jtLaunchReqs
304      */
305     private fun prepareLaunchPayload(
306         awxClient: BlueprintWebClientService,
307         jtLaunchReqs: JsonNode,
308         isWorkflow: Boolean
309     ): String {
310         val payload = JacksonUtils.objectMapper.createObjectNode()
311
312         // Parameter defaults
313         val inventoryProp = getOptionalOperationInput(INPUT_INVENTORY)
314         val extraArgs = getOperationInput(INPUT_EXTRA_VARS)
315
316         if (!isWorkflow) {
317             val limitProp = getOptionalOperationInput(INPUT_LIMIT_TO_HOST)
318             val tagsProp = getOptionalOperationInput(INPUT_TAGS)
319             val skipTagsProp = getOptionalOperationInput(INPUT_SKIP_TAGS)
320
321             val askLimitOnLaunch = jtLaunchReqs.at("/ask_limit_on_launch").asBoolean()
322             if (askLimitOnLaunch && !limitProp.isNullOrMissing()) {
323                 payload.set<JsonNode>(INPUT_LIMIT_TO_HOST, limitProp)
324             }
325             val askTagsOnLaunch = jtLaunchReqs.at("/ask_tags_on_launch").asBoolean()
326             if (askTagsOnLaunch && !tagsProp.isNullOrMissing()) {
327                 payload.set<JsonNode>(INPUT_TAGS, tagsProp)
328             }
329             if (askTagsOnLaunch && !skipTagsProp.isNullOrMissing()) {
330                 payload.set<JsonNode>("skip_tags", skipTagsProp)
331             }
332         }
333
334         val askInventoryOnLaunch = jtLaunchReqs.at("/ask_inventory_on_launch").asBoolean()
335         if (askInventoryOnLaunch && !inventoryProp.isNullOrMissing()) {
336             var inventoryKeyId = if (inventoryProp is TextNode) {
337                 resolveInventoryIdByName(awxClient, inventoryProp.textValue())?.asJsonPrimitive()
338             } else {
339                 inventoryProp
340             }
341             payload.set<JsonNode>(INPUT_INVENTORY, inventoryKeyId)
342         }
343
344         payload.set<JsonNode>("extra_vars", extraArgs)
345
346         return payload.asJsonString(false)
347     }
348
349     private fun resolveInventoryIdByName(awxClient: BlueprintWebClientService, inventoryProp: String): Int? {
350         var invId: Int? = null
351
352         // Get Inventory by name
353         val encoded = URLEncoder.encode(inventoryProp)
354         val response = awxClient.exchangeResource(GET, "/api/v2/inventories/?name=$encoded", "")
355         if (response.status in HTTP_SUCCESS) {
356             // Extract the inventory ID from response
357             val invDetails = mapper.readTree(response.body)
358             val nbInvFound = invDetails.at("/count").asInt()
359             if (nbInvFound == 1) {
360                 invId = invDetails["results"][0]["id"].asInt()
361                 log.info("Resolved inventory $inventoryProp to ID #: $invId")
362             }
363         }
364
365         if (invId == null) {
366             val message = "Could not resolve inventory $inventoryProp by name..."
367             log.error(message)
368             throw IllegalArgumentException(message)
369         }
370
371         return invId
372     }
373
374     /**
375      * Utility function to set the output properties of the executor node
376      */
377     private fun setNodeOutputProperties(status: JsonNode, message: JsonNode, artifacts: JsonNode) {
378         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
379         log.info("Executor status   : $status")
380         setAttribute(ATTRIBUTE_EXEC_CMD_ARTIFACTS, artifacts)
381         log.info("Executor artifacts: $artifacts")
382         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
383         log.info("Executor message  : $message")
384     }
385
386     /**
387      * Utility function to set the output properties and errors of the executor node, in cas of errors
388      */
389     private fun setNodeOutputErrors(status: String, message: String, artifacts: JsonNode = "".asJsonPrimitive()) {
390         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
391         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message.asJsonPrimitive())
392         setAttribute(ATTRIBUTE_EXEC_CMD_ARTIFACTS, artifacts)
393
394         addError(status, ATTRIBUTE_EXEC_CMD_LOG, message)
395     }
396 }