vcloud-client
Version:
Library which consumes directly VCloud API
307 lines (260 loc) • 8.75 kB
JavaScript
const http = require('../rest');
const {default: axios} = require("axios");
const chalk = require("chalk");
let config = {};
const VCLOUD_ACCEPT_VERSION_HEADER = process.env.VCLOUD_API_VERSION ? `application/*+json;version=${process.env.VCLOUD_API_VERSION}` : 'application/*+json;version=36.2'
const getHeader = () => {
return {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
}
const setParams = (...params) => {
if (params?.length > 0) {
let result = `?${params.at(0)}`;
for (let i = 1; i < params.length; i++) {
result = `${result}&${params.at(i)}`;
}
return result;
}
return '';
}
const paginatedCall = async (url, type, filter = undefined) => {
return await paginatedWithStateCall(url, type, filter);
}
const paginatedWithStateCall = async (url,
type = undefined,
filter = undefined,
result = [],
page = 1) => {
let totalPages = 0;
do {
const httpRequest = `${url}${setParams(type, filter, `page=${page}`)}`;
const res = await http.instance().get(httpRequest, {
headers: getHeader()
});
totalPages = Math.ceil(res.data.total / res.data.pageSize);
page++;
result = [...result, ...res?.data?.record];
} while (page <= totalPages)
return result;
}
/**
*
* @param {*} baseUrl Base url pointing to VCloud API. Should match to the following pattern: https://vcloud_server/api
* @param {*} user User who logs in
* @param {*} password Password of the user
* @param {*} organization VCloud organization name of the user
*
* @returns True if authenticated false if not
*
*/
const login = async (baseUrl, user, password, organization) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"Authorization": "Basic " + Buffer.from(user + "@" + organization + ":" + password).toString("base64")
}
const httpRequest = `${baseUrl}/sessions`;
const res = await http.instance().post(httpRequest, null, {
headers: headers
});
if (res?.status === 200) {
config = http.serviceConfiguration('Vcloud', baseUrl, res?.headers['x-vcloud-authorization'])
}
config.checkInternalData();
return true;
} catch (e) {
console.log(e);
}
return false;
}
const findOrganizationVDCsOdAndCh = async (organizationName) => {
try {
return await paginatedCall(`${config.url}/query`, `format=records&type=adminOrgVdc`, `filter=((name==OD_*),(name==CH_*);(orgName==${organizationName}))`)
} catch(ex) {
console.log(ex);
}
}
const findVMByMultiplesVDCHref = async (...vdcs) => {
try {
let filter = '';
for (const vdc of vdcs) {
filter = `${filter}vdc==${vdc.href},`
}
filter = `filter=(${filter.substring(0, Math.max(0, filter.lastIndexOf(',')))})`;
if (filter === 'filter=()'){
return [];
}
return await paginatedCall(`${config.url}/query`, 'type=adminVM', filter)
} catch(ex) {
console.log(ex);
}
}
/**
* Retrieves all the VM that matches with the name supplied by parameter
*
* @param {*} baseUrl Base url pointing to VCloud API. Should match to the following pattern: https://vcloud_server/api
* @param {*} token Valid security token
* @param {*} vmName name of the VM to search. Allows *
* @param {*} page result's page
*
* @returns
*/
const findVMByName = async (vmName, page) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
let httpRequest = `${config.url}/query?type=adminVM&filter=(name==${vmName})&page=${page}`;
let res = await http.instance().get(httpRequest, {
headers: headers
});
return res.data;
}
catch(ex) {
printError(ex);
}
}
/**
*
* @param {*} organizationName
* @param {*} page
* @returns
*/
const findOrganizationVDC = async (organizationName, page) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
let httpRequest = `${config.url}/query?type=adminOrgVdc&filter=(orgName==${organizationName})&page=${page}`;
let res = await http.instance().get(httpRequest, {
headers: headers
});
return res.data;
}
catch(ex) {
printError(ex);
}
}
/**
*
* @param {*} organizationHref
* @param {*} page
* @returns
*/
const findOrganizationVDCByHref = async (organizationHref, page) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
let httpRequest = `${config.url}/query?type=adminOrgVdc&filter=(org==${organizationHref})&page=${page}`;
let res = await http.instance().get(httpRequest, {
headers: headers
});
return res.data;
}
catch(ex) {
printError(ex);
}
}
const getAllOrganizations = async (page) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
let httpRequest = `${config.url}/query?type=organization&page=${page}`;
let res = await http.instance().get(httpRequest, {
headers: headers
});
return res.data;
}
catch(ex) {
printError(ex);
}
}
/**
*
* @param {*} vdcHref
* @param {*} page
* @returns
*/
const findVMByVDCHref = async (vdcHref, page) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
let httpRequest = `${config.url}/query?type=adminVM&filter=(vdc==${vdcHref})&page=${page}`;
let res = await http.instance().get(httpRequest, {
headers: headers
});
return res.data;
}
catch(ex) {
printError(ex);
}
}
const findAdminTasksByObjectType = async (baseUrl, token, objectType, page) => {
return findAdminTasks(baseUrl, token, null, objectType, null, null, null, page);
}
const findAllAdminTasks = async (baseUrl, token, organizationName, objectType, objectName, page) => {
return findAdminTasks(baseUrl, token, organizationName, objectType, objectName, null, null, page);
}
/**
*
* @param {*} organizationName Organization name
* @param {*} objectType Type (i.e: "vm")
* @param {*} objectName Name (i.e: "DevOps")
* @param {*} from Started from (UTC), mandatory format 2021-06-09T03:46:22.941Z
* @param {*} to Ended to (UTC), mandatory format 2021-06-09T03:46:22.941Z
* @param {*} page
* @returns
*/
const findAdminTasks = async (organizationName, objectType, objectName, from, to, page) => {
try {
const headers = {
"Accept": VCLOUD_ACCEPT_VERSION_HEADER,
"x-vcloud-authorization": config.token,
"Cookie": "vcloud-token=" + config.token
}
let filter = `filter=(objectType==${objectType}`;
if(organizationName) {
filter = `${filter};orgName==${organizationName}`;
}
if(objectName) {
filter = `${filter};objectName==${objectName}`;
}
if(from) {
filter = `${filter};startDate=gt=${from}`;
}
if(to) {
filter = `${filter};endDate=lt=${to}`;
}
// Close the parenthesis
filter = `${filter})`;
let httpRequest = `${config.url}/query?type=adminTask&${filter}&page=${page}&sortAsc=startDate`;
let res = await http.instance().get(httpRequest, {
headers: headers
});
return res.data;
}
catch(ex) {
printError(ex);
}
}
function printError(ex) {
console.log(chalk.bgRed('Error', ex));
console.log(chalk.bgRedBright(ex.stack));
}
module.exports = {login, findOrganizationVDCsOdAndCh, findVMByMultiplesVDCHref, findVMByName, findOrganizationVDC, findOrganizationVDCByHref, getAllOrganizations, findVMByVDCHref, findAdminTasksByObjectType, findAllAdminTasks, findAdminTasks}