2 * Copyright © 2019 Bell Canada.
3 * Modifications Copyright © 2018-2019 IBM.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.onap.ccsdk.cds.blueprintsprocessor.functions.ansible.executor
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
41 import java.net.URLEncoder
42 import java.util.NoSuchElementException
45 * ComponentRemoteAnsibleExecutor
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.
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
53 * @author Serge Simard
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
61 AbstractComponentFunction() {
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")
69 var checkDelay: Long = 15_000
72 private val log = LoggerFactory.getLogger(ComponentRemoteAnsibleExecutor::class.java)
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"
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"
91 override suspend fun processNB(executionRequest: ExecutionServiceInput) {
94 val restClientService = getAWXRestClient()
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()
101 jobTemplateName = getOperationInput(INPUT_WORKFLOW_JOB_TEMPLATE_NAME).asText()
102 workflowURIPrefix = "workflow_"
105 val jtId = lookupJobTemplateIDByName(restClientService, jobTemplateName, workflowURIPrefix)
106 if (jtId.isNotEmpty()) {
107 runJobTemplateOnAWX(restClientService, jobTemplateName, jtId, workflowURIPrefix)
109 val message = "Workflow/Job template $jobTemplateName does not exists"
111 setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
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})")
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)
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"
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"
139 private fun getAWXRestClient(): BlueprintWebClientService {
141 val endpointSelector = getOperationInput(INPUT_ENDPOINT_SELECTOR)
144 return blueprintRestLibPropertyService.blueprintWebClientService(endpointSelector)
145 } catch (e: NoSuchElementException) {
146 throw IllegalArgumentException("No value provided for input selector $endpointSelector", e)
151 * Finds the job template ID based on the job template name provided in the request
153 private fun lookupJobTemplateIDByName(
154 awxClient: BlueprintWebClientService,
155 job_template_name: String?,
156 workflowPrefix: String
158 val encodedJTName = URI(
160 "/api/v2/${workflowPrefix}job_templates/$job_template_name/",
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()
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.
176 private suspend fun runJobTemplateOnAWX(
177 awxClient: BlueprintWebClientService,
178 job_template_name: String?,
180 workflowPrefix: String
182 setNodeOutputProperties("preparing".asJsonPrimitive(), "".asJsonPrimitive(), "".asJsonPrimitive())
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())
190 log.info("Running job with $payload, for requestId $processId.")
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.")
203 if (response.status in HTTP_SUCCESS) {
204 val jobId: String = jtLaunched.at("/id").asText()
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()
217 log.info("Execution of job template $job_template_name in job #$jobId finished with status ($jobStatus) for requestId $processId")
219 populateJobRunResponse(awxClient, jobId, workflowPrefix, jobStatus)
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}) "
227 setNodeOutputErrors(ATTRIBUTE_EXEC_CMD_STATUS_ERROR, message)
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
235 private fun populateJobRunResponse(
236 awxClient: BlueprintWebClientService,
238 workflowPrefix: String,
242 val collectedResponses = StringBuilder(4096)
243 val artifacts: MutableMap<String, JsonNode> = mutableMapOf()
245 collectJobIdsRelatedToJobRun(awxClient, jobId, workflowPrefix).forEach { aJobId ->
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
252 .append("Output for Job $aJobId :" + System.lineSeparator())
254 .append(System.lineSeparator())
255 log.info("Response for job $aJobId: \n $jobOutput \n")
257 log.warn("Could not gather response for job $aJobId. Status=${response.status}")
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())
270 log.info("Artifacts for job $jobId: \n $artifacts \n")
272 setNodeOutputProperties(jobStatus.asJsonPrimitive(), collectedResponses.toString().asJsonPrimitive(), artifacts.asJsonNode())
276 * List all the job Ids for a give workflow, i.e. sub jobs, or the jobId if not a workflow instance
278 private fun collectJobIdsRelatedToJobRun(awxClient: BlueprintWebClientService, jobId: String, workflowPrefix: String): Array<String> {
280 var jobIds: Array<String>
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")
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())
294 jobIds = arrayOf(jobId)
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
304 private fun prepareLaunchPayload(
305 awxClient: BlueprintWebClientService,
306 jtLaunchReqs: JsonNode,
309 val payload = JacksonUtils.objectMapper.createObjectNode()
311 // Parameter defaults
312 val inventoryProp = getOptionalOperationInput(INPUT_INVENTORY)
313 val extraArgs = getOperationInput(INPUT_EXTRA_VARS)
316 val limitProp = getOptionalOperationInput(INPUT_LIMIT_TO_HOST)
317 val tagsProp = getOptionalOperationInput(INPUT_TAGS)
318 val skipTagsProp = getOptionalOperationInput(INPUT_SKIP_TAGS)
320 val askLimitOnLaunch = jtLaunchReqs.at("/ask_limit_on_launch").asBoolean()
321 if (askLimitOnLaunch && !limitProp.isNullOrMissing()) {
322 payload.set<JsonNode>(INPUT_LIMIT_TO_HOST, limitProp)
324 val askTagsOnLaunch = jtLaunchReqs.at("/ask_tags_on_launch").asBoolean()
325 if (askTagsOnLaunch && !tagsProp.isNullOrMissing()) {
326 payload.set<JsonNode>(INPUT_TAGS, tagsProp)
328 if (askTagsOnLaunch && !skipTagsProp.isNullOrMissing()) {
329 payload.set<JsonNode>("skip_tags", skipTagsProp)
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()
340 payload.set<JsonNode>(INPUT_INVENTORY, inventoryKeyId)
343 payload.set<JsonNode>("extra_vars", extraArgs)
345 return payload.asJsonString(false)
348 private fun resolveInventoryIdByName(awxClient: BlueprintWebClientService, inventoryProp: String): Int? {
349 var invId: Int? = null
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")
365 val message = "Could not resolve inventory $inventoryProp by name..."
367 throw IllegalArgumentException(message)
374 * Utility function to set the output properties of the executor node
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")
386 * Utility function to set the output properties and errors of the executor node, in cas of errors
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)
393 addError(status, ATTRIBUTE_EXEC_CMD_LOG, message)