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