From 9519cd708684a9ce44aba10c8c00add4d41f071a Mon Sep 17 00:00:00 2001 From: Amal Joe Gladwin Maria Antony Date: Fri, 8 Feb 2019 02:21:55 +0530 Subject: [PATCH] Removing duplicate files in Ansible task --- .../Ansible/AnsibleCommandLineInterface.ts | 174 --------------- .../Src/Tasks/Ansible/AnsibleInterface.ts | 9 - .../Tasks/Ansible/AnsibleTowerInterface.ts | 206 ------------------ 3 files changed, 389 deletions(-) delete mode 100644 Extensions/Ansible/Src/Tasks/Ansible/AnsibleCommandLineInterface.ts delete mode 100644 Extensions/Ansible/Src/Tasks/Ansible/AnsibleInterface.ts delete mode 100644 Extensions/Ansible/Src/Tasks/Ansible/AnsibleTowerInterface.ts diff --git a/Extensions/Ansible/Src/Tasks/Ansible/AnsibleCommandLineInterface.ts b/Extensions/Ansible/Src/Tasks/Ansible/AnsibleCommandLineInterface.ts deleted file mode 100644 index 8c01f7ae6..000000000 --- a/Extensions/Ansible/Src/Tasks/Ansible/AnsibleCommandLineInterface.ts +++ /dev/null @@ -1,174 +0,0 @@ -import tl = require("vsts-task-lib/task"); -import { ansibleInterface } from './ansibleInterface'; -import * as ansibleUtils from './ansibleUtils'; -import { RemoteCommandOptions } from './ansibleUtils' -import { ansibleTaskParameters } from './ansibleTaskParameters'; - -var os = require('os'); -var shell = require('shelljs'); - -export class ansibleCommandLineInterface extends ansibleInterface { - constructor(params: ansibleTaskParameters) { - super(); - this._taskParameters = params; - this._remoteCmdOptions = new RemoteCommandOptions(); - this._additionalParams = ""; - this._cleanupCmd = []; - this._playbookPath = ""; - this._inventoryPath = ""; - this._sudoUser = ""; - } - - public async execute() { - try { - await this.setupConnection(); - let failOnStdErr: boolean = this._taskParameters.failOnStdErr; - this._remoteCmdOptions.failOnStdErr = failOnStdErr; - - await this._executeAnsiblePlaybook(); - - } catch (error) { - tl.setResult(tl.TaskResult.Failed, error); - } finally { - //clean up script file if needed - if (this._cleanupCmd && this._cleanupCmd.length > 0) { - try { - for (var i: number = 0; i < this._cleanupCmd.length; i++) { - await this.executeCommand(this._cleanupCmd[i]); - } - } catch (err) { - tl.warning(tl.loc('RemoteFileCleanUpFailed', err)); - } - } - this.terminateConnection(); - } - } - - protected async _executeAnsiblePlaybook() { - if (this._playbookPath == null || this._playbookPath.trim() == "") { - this._playbookPath = this._taskParameters.playbookPath; - } - tl.debug('PlaybookPath = ' + '"' + this._playbookPath + '"'); - if (this._inventoryPath == null || this._inventoryPath.trim() == "") { - let inventoryLocation = this._taskParameters.inventoryType; - if (inventoryLocation == 'file') { - this._inventoryPath = this._taskParameters.inventoryFilePath; - } else if (inventoryLocation == 'hostList') { - this._inventoryPath = await this.getInventoryPathForHostList(); - } else if (inventoryLocation == 'inlineContent') { - this._inventoryPath = await this.createAndGetInventoryPathForInline(); - } - } - tl.debug('InventoryFile = ' + this._inventoryPath); - this._sudoUser = await this.getSudoUser(); - this._additionalParams = await this.getAdditionalParam(); - - let playbookExecCmd = this._buildPlaybookExecutionCommand(); - tl.debug('Running ' + playbookExecCmd); - - await this.executeCommand(playbookExecCmd); - } - - protected async setupConnection() { - if (ansibleUtils.getAgentPlatform() === 'win32') { - throw tl.loc('AgentOnWindowsMachine'); - } - if (!ansibleUtils.getShellWhich('ansible')) { - throw tl.loc('AnisbleNotPresent'); - } - } - - protected terminateConnection() { - } - - protected async executeCommand(cmd: string): Promise { - return await ansibleUtils.runCommandOnSameMachine(cmd, this._remoteCmdOptions); - } - - protected async getSudoUser(): Promise { - let sudoEnabled: boolean = this._taskParameters.sudoEnable; - let sudoUser = this._taskParameters.sudoUser; - return new Promise((resolve, reject) => { - if (sudoEnabled == true) { - if (!sudoUser || sudoUser.trim() == "") { - sudoUser = 'root'; - } - tl.debug('Sudo User = ' + sudoUser); - resolve(sudoUser); - } else { - resolve(""); - } - }); - } - - protected async getAdditionalParam(): Promise { - var args: string = this._taskParameters.additionalParams; - return new Promise((resolve, reject) => { - if (args && args.trim()) { - resolve(args.trim()); - } else { - resolve(""); - } - }) - } - - protected async getInventoryPathForHostList(): Promise { - let hostList = this._taskParameters.inventoryHostList.trim(); - return new Promise((resolve, reject) => { - //host list should end with comma (,) - if (!hostList.endsWith(',')) - hostList = hostList.concat(','); - tl.debug("Host List = " + '"' + hostList + '"'); - resolve('"' + hostList + '"'); - }); - } - - protected async createAndGetInventoryPathForInline(): Promise { - let content = this._taskParameters.inventoryInline.trim(); - let dynamicInventory: boolean = this._taskParameters.inventoryDynamic; - var __this = this; - - return new Promise(async (resolve, reject) => { - try { - let remoteInventory = '/tmp/' + 'inventory.ini'; - let remoteInventoryPath = '"' + remoteInventory + '"'; - tl.debug('RemoteInventoryPath = ' + remoteInventoryPath); - - let inventoryCmd: string = 'echo ' + '"' + content + '"' + ' > ' + remoteInventory; - await __this.executeCommand(inventoryCmd); - if (dynamicInventory == true) { - await __this.executeCommand('chmod +x ' + remoteInventory); - } - this._cleanupCmd.push('rm -f ' + remoteInventory); - resolve(remoteInventory); - } catch (error) { - reject(error); - } - }); - } - - private _buildPlaybookExecutionCommand() { - let cmd = 'ansible-playbook '; - if (this._inventoryPath && this._inventoryPath.trim()) { - cmd = cmd.concat('-i ' + this._inventoryPath + ' '); - } - if (this._playbookPath && this._playbookPath.trim()) { - cmd = cmd.concat(this._playbookPath + " "); - } - if (this._sudoUser && this._sudoUser.trim()) { - cmd = cmd.concat('-b --become-user ' + this._sudoUser + ' '); - } - if (this._additionalParams && this._additionalParams.trim()) { - cmd = cmd.concat(this._additionalParams); - } - return cmd; - } - - protected _taskParameters: ansibleTaskParameters; - protected _cleanupCmd = []; - protected _remoteCmdOptions: RemoteCommandOptions; - protected _playbookPath: string; - protected _inventoryPath: string; - private _sudoUser: string; - private _additionalParams: string; -} \ No newline at end of file diff --git a/Extensions/Ansible/Src/Tasks/Ansible/AnsibleInterface.ts b/Extensions/Ansible/Src/Tasks/Ansible/AnsibleInterface.ts deleted file mode 100644 index d6cc1aea9..000000000 --- a/Extensions/Ansible/Src/Tasks/Ansible/AnsibleInterface.ts +++ /dev/null @@ -1,9 +0,0 @@ - -export class ansibleInterface { - constructor() { - } - public async execute() { - throw "selected interface not supported"; - } -} - diff --git a/Extensions/Ansible/Src/Tasks/Ansible/AnsibleTowerInterface.ts b/Extensions/Ansible/Src/Tasks/Ansible/AnsibleTowerInterface.ts deleted file mode 100644 index 0deb19dd9..000000000 --- a/Extensions/Ansible/Src/Tasks/Ansible/AnsibleTowerInterface.ts +++ /dev/null @@ -1,206 +0,0 @@ -import tl = require("vsts-task-lib/task"); -import path = require("path"); -import querystring = require('querystring'); -import util = require("util"); - -import { ansibleInterface } from './ansibleInterface'; -import {WebRequest, WebResponse, beginRequest} from './ansibleUtils'; - -export class ansibleTowerInterface extends ansibleInterface { - constructor() { - super(); - this.initializeTaskContants(); - } - - public async execute() { - try { - this._jobTemplateId = await this.getJobTemplateId(); - - var jobId = await this.launchJob(); - var status = await this.updateRunningStatusAndLogs(jobId); - if (status === 'successful') - tl.setResult(tl.TaskResult.Succeeded, ""); - else if (status === 'failed') - tl.setResult(tl.TaskResult.Failed, ""); - } - catch (error) { - tl.setResult(tl.TaskResult.Failed, error); - } - } - - private initializeTaskContants() { - try { - var connectedService = tl.getInput("connectionAnsibleTower", true); - var endpointAuth = tl.getEndpointAuthorization(connectedService, true); - this._username = endpointAuth.parameters["username"]; - this._password = endpointAuth.parameters["password"]; - this._hostname = tl.getEndpointUrl(connectedService, true); - this._jobTemplateName = tl.getInput("jobTemplateName"); - this._lastPolledEvent = 0; - - } catch (error) { - tl.setResult(tl.TaskResult.Failed, tl.loc("Ansible_ConstructorFailed", error.message)); - } - } - - private getEmptyRequestData(): string { - return querystring.stringify({}); - } - - private getBasicRequestHeader(): any { - var requestHeader: any = { - "Authorization": "Basic " + new Buffer(this._username + ":" + this._password).toString('base64') - }; - return requestHeader; - } - - private getJobLaunchApi(): string { - var ansibleJobLaunchUrl: string = util.format(this._jobLaunchUrlFormat, this._hostname, this._jobTemplateId); - return ansibleJobLaunchUrl; - } - - private getJobApi(jobId: string): string { - var ansibleJobUrl: string = util.format(this._jobUrlFormat, this._hostname, jobId); - return ansibleJobUrl; - } - - private getJobEventApi(jobId: string, pageSize: number, pageNumber: number): string { - var ansibleJobEventUrl: string = util.format(this._jobEventUrlFormat, this._hostname, jobId, pageSize, pageNumber); - return ansibleJobEventUrl; - } - - private async getJobTemplateId(): Promise { - - var jobTemplateId: string = null; - var request = new WebRequest(); - request.method = 'GET'; - request.uri = util.format(this._jobTemplateIdUrlFormat, this._hostname, this._jobTemplateName); - request.headers = this.getBasicRequestHeader(); - - var response = await beginRequest(request); - if (response.statusCode === 200) { - jobTemplateId = response.body['results'][0]['id']; - } else { - throw (tl.loc('JobTemplateNotPresent', this._jobTemplateName)); - } - return jobTemplateId; - } - - private async getJobStatus(jobId: string): Promise { - var status: string = null; - var request = new WebRequest(); - request.method = 'GET'; - request.uri = this.getJobApi(jobId); - request.headers = this.getBasicRequestHeader(); - - var response = await beginRequest(request); - if (response.statusCode === 200) { - status = response.body['status']; - } else { - throw (tl.loc('FailedToGetJobDetails', response.statusCode, response.statusMessage)); - } - return status; - } - - private async getJobEvents(jobId: string, lastDisplayedEvent: number): Promise { - var stdoutArray: string[] = []; - var pageSize = 10; - var pageNumber = Math.floor(lastDisplayedEvent / pageSize + 1); - var request = new WebRequest(); - request.method = 'GET'; - request.headers = this.getBasicRequestHeader(); - var jobEventUrl = this.getJobEventApi(jobId, pageSize, pageNumber); - - while (jobEventUrl) { - request.uri = jobEventUrl; - var response = await beginRequest(request); - if (response.statusCode === 200) { - var totalEvents = response.body['count']; - var results: any[] = response.body['results']; - var nextPageUrl = response.body['next']; - results.forEach((event) => { - if (event['counter'] > lastDisplayedEvent) - stdoutArray[event['counter']] = event['stdout']; - }); - jobEventUrl = (nextPageUrl != null) ? (this._hostname + nextPageUrl) : null; - } else { - throw (tl.loc('FailedToGetJobDetails', response.statusCode, response.statusMessage)); - } - } - - return stdoutArray; - } - - - private isJobInTerminalState(status: string): boolean { - return status === 'successful' || status === 'failed'; - } - - private async updateRunningStatusAndLogs(jobId: string): Promise { - var waitTimeInSeconds = 10; - var timeElapsed = 0; - var longRunningJobThreshold = 300; - var lastDisplayedEvent = 0; - var status: string = ""; - while (true) { - status = await this.getJobStatus(jobId); - if (status !== 'pending') { - var events = await this.getJobEvents(jobId, lastDisplayedEvent); - events.forEach((value, index) => { - lastDisplayedEvent = index; - console.log(value); - console.log(); - }); - } - if (this.isJobInTerminalState(status)) { - break; - } - - await this.sleepFor(waitTimeInSeconds); - - timeElapsed += waitTimeInSeconds; - if (timeElapsed >= longRunningJobThreshold) { - waitTimeInSeconds = 120; - } - } - - return status; - } - - private async launchJob(): Promise { - var jobId: string = null; - var request = new WebRequest(); - request.method = 'POST'; - request.uri = this.getJobLaunchApi(); - request.body = this.getEmptyRequestData(); - request.headers = this.getBasicRequestHeader(); - - var response = await beginRequest(request); - - if (response.statusCode === 201) { - jobId = response.body['id']; - } else { - throw (tl.loc('CouldnotLaunchJob', response.statusCode, response.statusMessage)); - } - return jobId; - } - - private sleepFor(sleepDurationInSeconds): Promise { - return new Promise((resolve, reeject) => { - setTimeout(resolve, sleepDurationInSeconds * 1000); - }); - } - - private _jobLaunchUrlFormat: string = "%s/api/v1/job_templates/%s/launch/"; - private _jobUrlFormat: string = "%s/api/v1/jobs/%s/"; - private _jobEventUrlFormat: string = "%s/api/v1/jobs/%s/job_events/?page_size=%s&page=%s"; - private _jobTemplateIdUrlFormat: string = "%s/api/v1/job_templates/?name__exact=%s"; - - private _connectedService: string; - private _jobTemplateName: string; - private _jobTemplateId: string; - private _username: string; - private _password: string; - private _hostname: string; - private _lastPolledEvent: number; -} \ No newline at end of file