96a7bb71284e82af09e35f37a6b56d8ab1a97df0
[ccsdk/cds.git] /
1 /*
2  *  Copyright © 2019 Bell Canada.
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.functions.ansible.executor
18
19 import com.fasterxml.jackson.databind.JsonNode
20 import com.fasterxml.jackson.databind.ObjectMapper
21 import com.fasterxml.jackson.databind.node.ObjectNode
22 import java.net.URLEncoder
23 import java.util.NoSuchElementException
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
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.*
29 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
30 import org.slf4j.LoggerFactory
31 import org.springframework.beans.factory.config.ConfigurableBeanFactory
32 import org.springframework.context.annotation.Scope
33 import org.springframework.http.HttpMethod
34 import org.springframework.stereotype.Component
35
36 /**
37  * ComponentRemoteAnsibleExecutor
38  *
39  * Component that launches a run of a job template (INPUT_JOB_TEMPLATE_NAME) representing an Ansible playbook,
40  * and its parameters, via the AWX server identified by the INPUT_ENDPOINT_SELECTOR parameter.
41  *
42  * It supports extra_vars, limit, tags, skip-tags, inventory (by name or Id) Ansible parameters.
43  * It reports the results of the execution via properties, named execute-command-status and execute-command-logs
44  *
45  * @author Serge Simard
46  */
47 @Component("component-remote-ansible-executor")
48 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
49 open class ComponentRemoteAnsibleExecutor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService)
50     : AbstractComponentFunction() {
51
52     private val log = LoggerFactory.getLogger(ComponentRemoteAnsibleExecutor::class.java)!!
53
54     // HTTP related constants
55     private val HTTP_SUCCESS = 200..202
56     private val GET = HttpMethod.GET.name
57     private val POST = HttpMethod.POST.name
58
59     companion object {
60         // input fields names accepted by this executor
61         const val INPUT_ENDPOINT_SELECTOR = "endpoint-selector"
62         const val INPUT_JOB_TEMPLATE_NAME = "job-template-name"
63         const val INPUT_LIMIT_TO_HOST = "limit"
64         const val INPUT_INVENTORY = "inventory"
65         const val INPUT_EXTRA_VARS = "extra-vars"
66         const val INPUT_TAGS = "tags"
67         const val INPUT_SKIP_TAGS = "skip-tags"
68
69         // output fields names (and values) populated by this executor; aligned with job details status field values.
70         const val ATTRIBUTE_EXEC_CMD_STATUS = "ansible-command-status"
71         const val ATTRIBUTE_EXEC_CMD_LOG = "ansible-command-logs"
72         const val ATTRIBUTE_EXEC_CMD_STATUS_ERROR = "error"
73
74         const val CHECKDELAY: Long = 10000
75     }
76
77     override suspend fun processNB(executionRequest: ExecutionServiceInput) {
78
79         try {
80             val restClientService = getAWXRestClient()
81
82             val jobTemplateName = getOperationInput(INPUT_JOB_TEMPLATE_NAME).asText()
83             val jtId = lookupJobTemplateIDByName(restClientService, jobTemplateName)
84             if (jtId.isNotEmpty()) {
85                 runJobTemplateOnAWX(restClientService, jobTemplateName, jtId)
86             } else {
87                 val message = "Job template ${jobTemplateName} does not exists"
88                 log.error(message)
89                 setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
90             }
91         } catch (e: Exception) {
92             log.error("Failed to process on remote executor (${e.message})", e)
93             setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, "Failed to process on remote executor (${e.message})")
94         }
95     }
96
97
98     override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
99         val message = "Error in ComponentRemoteAnsibleExecutor : ${runtimeException.message}"
100         log.error(message,runtimeException)
101         setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
102     }
103
104     /** Creates a TokenAuthRestClientService, since this executor expect type property to be "token-auth" and the
105      * token to be an OAuth token (access_token response field) generated via the AWX /api/o/token rest endpoint
106      * The token field is of the form "Bearer access_token_from_response", for example :
107      *  "blueprintsprocessor.restclient.awx.type=token-auth"
108      *  "blueprintsprocessor.restclient.awx.url=http://awx-endpoint"
109      *  "blueprintsprocessor.restclient.awx.token=Bearer J9gEtMDzxcqw25574fioY9VAhLDIs1"
110      *
111      * Also supports json endpoint definition via DSL entry, e.g.:
112      *     "ansible-remote-endpoint": {
113      *        "type": "token-auth",
114      *        "url": "http://awx-endpoint",
115      *        "token": "Bearer J9gEtMDzxcqw25574fioY9VAhLDIs1"
116      *     }
117      */
118     private fun getAWXRestClient(): BlueprintWebClientService {
119
120         val endpointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
121
122         try {
123             return blueprintRestLibPropertyService.blueprintWebClientService(endpointSelector)
124         } catch (e : NoSuchElementException) {
125             throw IllegalArgumentException("No value provided for input selector $endpointSelector", e)
126         }
127     }
128
129     /**
130      * Finds the job template ID based on the job template name provided in the request
131      */
132     private fun lookupJobTemplateIDByName(awxClient : BlueprintWebClientService, job_template_name: String?): String {
133         val mapper = ObjectMapper()
134
135         // Get Job Template details by name
136         var response = awxClient.exchangeResource(GET, "/api/v2/job_templates/${job_template_name}/", "")
137         val jtDetails: JsonNode = mapper.readTree(response.body)
138         return jtDetails.at("/id").asText()
139     }
140
141     /**
142      * Performs the job template execution on AWX, ie. prepare arguments as per job template
143      * requirements (ask fields) and provided overriding values. Then it launches the run, and monitors
144      * its execution. Finally, it retrieves the job results via the stdout api.
145      * The status and output attributes are populated in the process.
146      */
147     private fun runJobTemplateOnAWX(awxClient : BlueprintWebClientService, job_template_name: String?, jtId: String) {
148         val mapper = ObjectMapper()
149
150         setNodeOutputProperties( "preparing".asJsonPrimitive(), "".asJsonPrimitive())
151
152         // Get Job Template requirements
153         var response = awxClient.exchangeResource(GET, "/api/v2/job_templates/${jtId}/launch/","")
154         val jtLaunchReqs: JsonNode = mapper.readTree(response.body)
155         var payload = prepareLaunchPayload(awxClient, jtLaunchReqs)
156         log.info("Running job with $payload, for requestId $processId.")
157
158         // Launch the job for the targeted template
159         var jtLaunched : JsonNode = JacksonUtils.jsonNode("{}") as ObjectNode
160         response = awxClient.exchangeResource(POST, "/api/v2/job_templates/${jtId}/launch/", payload)
161         if (response.status in HTTP_SUCCESS) {
162             jtLaunched = mapper.readTree(response.body)
163             val fieldsIgnored: JsonNode = jtLaunched.at("/ignored_fields")
164             if (fieldsIgnored.rootFieldsToMap().isNotEmpty()) {
165                 log.warn("Ignored fields : $fieldsIgnored, for requestId $processId.")
166             }
167         }
168
169         if (response.status in HTTP_SUCCESS) {
170             val jobId: String = jtLaunched.at("/id").asText()
171
172             // Poll current job status while job is not executed
173             var jobStatus = "unknown"
174             var jobEndTime = "null"
175             while (jobEndTime == "null") {
176                 response = awxClient.exchangeResource(GET, "/api/v2/jobs/${jobId}/", "")
177                 val jobLaunched: JsonNode = mapper.readTree(response.body)
178                 jobStatus = jobLaunched.at("/status").asText()
179                 jobEndTime = jobLaunched.at("/finished").asText()
180                 Thread.sleep(CHECKDELAY)
181             }
182
183             log.info("Execution of job template $job_template_name in job #$jobId finished with status ($jobStatus) for requestId $processId")
184
185             // Get job execution results (stdout)
186             val plainTextHeaders = mutableMapOf<String, String>()
187             plainTextHeaders["Content-Type"] = "text/plain ;utf-8"
188             response = awxClient.exchangeResource(GET, "/api/v2/jobs/${jobId}/stdout/?format=txt","", plainTextHeaders)
189
190             setNodeOutputProperties( jobStatus.asJsonPrimitive(), response.body.asJsonPrimitive())
191         } else {
192             // The job template requirements were not fulfilled with the values passed in. The message below will
193             // provide more information via the response, like the ignored_fields, or variables_needed_to_start,
194             // or resources_needed_to_start, in order to help user pinpoint the problems with the request.
195             val message = "Execution of job template $job_template_name could not be started for requestId $processId." +
196                     " (Response: ${response.body}) "
197             log.error(message)
198             setNodeOutputErrors( ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
199         }
200     }
201
202     /**
203      * Prepares the JSON payload expected by the job template api,
204      * by applying the overrides that were provided
205      * and allowed by the template definition flags in jtLaunchReqs
206      */
207     private fun prepareLaunchPayload(awxClient : BlueprintWebClientService, jtLaunchReqs: JsonNode): String {
208         val payload = JacksonUtils.jsonNode("{}") as ObjectNode
209
210         // Parameter defaults
211         val limitProp = getOptionalOperationInput(INPUT_LIMIT_TO_HOST)?.asText()
212         val tagsProp = getOptionalOperationInput(INPUT_TAGS)?.asText()
213         val skipTagsProp = getOptionalOperationInput(INPUT_SKIP_TAGS)?.asText()
214         val inventoryProp : String? = getOptionalOperationInput(INPUT_INVENTORY)?.asText()
215         val extraArgs : JsonNode = getOperationInput(INPUT_EXTRA_VARS)
216
217         val askLimitOnLaunch = jtLaunchReqs.at( "/ask_limit_on_launch").asBoolean()
218         if (askLimitOnLaunch && limitProp!!.isNotEmpty()) {
219             payload.put(INPUT_LIMIT_TO_HOST, limitProp)
220         }
221         val askTagsOnLaunch = jtLaunchReqs.at("/ask_tags_on_launch").asBoolean()
222         if (askTagsOnLaunch && tagsProp!!.isNotEmpty()) {
223             payload.put(INPUT_TAGS, tagsProp)
224         }
225         if (askTagsOnLaunch && skipTagsProp!!.isNotEmpty()) {
226             payload.put("skip_tags", skipTagsProp)
227         }
228         val askInventoryOnLaunch = jtLaunchReqs.at("/ask_inventory_on_launch").asBoolean()
229         if (askInventoryOnLaunch && inventoryProp != null) {
230             var inventoryKeyId = inventoryProp.toIntOrNull()
231             if (inventoryKeyId == null) {
232                 inventoryKeyId = resolveInventoryIdByName(awxClient, inventoryProp)
233             }
234             payload.put(INPUT_INVENTORY, inventoryKeyId)
235         }
236         val askVariablesOnLaunch = jtLaunchReqs.at("/ask_variables_on_launch").asBoolean()
237         if (askVariablesOnLaunch && extraArgs != null) {
238             payload.put("extra_vars", extraArgs)
239         }
240
241         val strPayload = "$payload"
242
243         return strPayload
244     }
245
246     private fun resolveInventoryIdByName(awxClient : BlueprintWebClientService, inventoryProp: String): Int? {
247         var invId : Int? = null
248
249         // Get Inventory by name
250         val encoded = URLEncoder.encode(inventoryProp)
251         val response = awxClient.exchangeResource(GET,"/api/v2/inventories/?name=$encoded","")
252         if (response.status in HTTP_SUCCESS) {
253             val mapper = ObjectMapper()
254
255             // Extract the inventory ID from response
256             val invDetails = mapper.readTree(response.body)
257             val nbInvFound = invDetails.at("/count").asInt()
258             if (nbInvFound == 1) {
259                 invId = invDetails["results"][0]["id"].asInt()
260                 log.info("Resolved inventory $inventoryProp to ID #: $invId")
261             }
262         }
263
264         if (invId == null) {
265             val message = "Could not resolve inventory $inventoryProp by name..."
266             log.error(message)
267             throw IllegalArgumentException(message)
268         }
269
270         return invId
271     }
272
273     /**
274      * Utility function to set the output properties of the executor node
275      */
276     private fun setNodeOutputProperties(status: JsonNode, message: JsonNode) {
277         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status)
278         log.info("Executor status: $status")
279         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message)
280         log.info("Executor message: $message")
281     }
282
283     /**
284      * Utility function to set the output properties and errors of the executor node, in cas of errors
285      */
286     private fun setNodeOutputErrors(status: String, message: String) {
287         setAttribute(ATTRIBUTE_EXEC_CMD_STATUS, status.asJsonPrimitive())
288         setAttribute(ATTRIBUTE_EXEC_CMD_LOG, message.asJsonPrimitive())
289
290         addError(status, ATTRIBUTE_EXEC_CMD_LOG, message)
291     }
292 }