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