Skip to content

Instantly share code, notes, and snippets.

@AaronMcCaughan
Last active August 14, 2019 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AaronMcCaughan/f777f874b020e24c14946ec24cced1e6 to your computer and use it in GitHub Desktop.
Save AaronMcCaughan/f777f874b020e24c14946ec24cced1e6 to your computer and use it in GitHub Desktop.
/**************************************************************
**********ENVIRONMENT HEALTH CHECK SAMPLE SCRIPT *************
**************************************************************
This script will connect to Jenkins using Basic Authentication and trigger the execution of a Job using API' requests. It will then copy the log file from Jenkins to the execution log in Plutora
The script accepts the input parameters below, triggers the execution of a Jenkins job and captures the console output in Plutora.
The paramaters entered into the UI need to be named as follows and are case sensitive:
- host = <This is the url of your instance of Jenkins>
- user = <This is the user to authenticate with Jenkins>
- password = <This is the password to authenticate with Jenkins>
- token = <This is the build authentication token configured under build triggers of the selected job>
- jobName = <This is the name of build job>
- buildWithParamaters = <true or false>
The outcome of your test should return the result via a Promise.Resolve();
resolve('Online'); Sets the environment health status to 'Online'
resolve('Offline'); Sets the environment health status to 'Offline'
resolve('Issue'); Sets the environment health status to 'Issue'
resolve('Unknown'); Sets the environment health status to 'Unknown'
Any thrown errors during script execution or a call to Reject will be treated as a result of Unknown
reject(true); Sets the environment health status to 'Unknown'
*/
/********************************************************
*************STEP 1: Import npm's************************
********************************************************/
const https = require("https");
const http = require("http");
/********************************************************
*******STEP 2: Define you API and SSH parameters*********
********************************************************/
//EXAMPLE SETTINGS
let options = {
host: '',
port: 80,
path: '',
method: 'GET',
headers: {
accept: 'application/json',
authorization:''
}
};
/********************************************************
****STEP 3: Create an API Request function********
********************************************************/
let req = function (options) {
return new Promise((resolve, reject) => {
http.get(options, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
try {
resolve(JSON.parse(data));
}
catch (error) {
resolve(data);
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
reject(err.message);
});
});
}
/********************************************************
********STEP 4: Define the main run function ************
********************************************************/
let run = function (args) {
return new Promise((resolve, reject) => {
//Resolve credentials from paramaters set via Plutora UI.
options.headers.authorization = "Basic " + new Buffer(`${args.arguments.user}:${args.arguments.password}`).toString('base64');
options.host = args.arguments.host;
options.path = `/job/${args.arguments.jobName}/lastBuild/api/json`;
options.jobName = args.arguments.jobName;
let buildType = args.arguments.buildWithParamaters === 'true' ? 'buildWithParameters' : 'build';
let number = 0;
return req(options)
.then((data) => {
number = data.number + 1;
})
.then(() => {
options.path = `/job/${options.jobName}/${buildType}?token=${args.arguments.token}`;
return req(options)
})
.then(() => {
options.path = `/job/${options.jobName}/${number}/api/json?tree=building,number,result,executor[progress]`;
return pollProgress(number, 100)
})
.then(result => resolve(result))
.catch(err => {
console.log(err);
reject(err)
});
})
};
/********************************************************
******* Optional: Define support functions *************
********************************************************/
const pollProgress = async (number, retries) => {
return new Promise(async (resolve, reject) => {
let attempts = 0;
let isBuilding = true;
let result;
do {
++attempts;
await sleep(5000);
await req(options).then(data => {
if (data.building || data === "") {
//notifier.progress('Building...' + (data.executor ? data.executor.progress : 0) + '%');
console.log('Execution in progress. Completed...' + (data.executor ? data.executor.progress : 0) + '%');
} else if (data.building === false) {
isBuilding = false;
result = data.result;
}
}).catch(err => {
isBuilding = false;
return reject(err);
});
} while (attempts <= retries && isBuilding === true);
if (!result) {
console.log("Job not completed in time; Final progress unknown.");
return resolve('Offline');
}
options.path = `/job/${options.jobName}/` + number + "/consoleText";
return req(options).then((log) => {
console.log("Build Number: " + number);
console.log("Build Log: " + log);
if (result === "SUCCESS") {
return resolve('Online');
} else {
return resolve('Offline');
}
}, (err) => {
return reject(console.log(err));
});
});
};
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
/********************************************************
***************STEP 5: EXPORT RUN METHOD ***********************
********************************************************/
module.exports = {
run: run
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment