From b822f7f8563f395f10c04291a486db280f0acbad Mon Sep 17 00:00:00 2001 From: Arthur Lu Date: Thu, 29 Jun 2023 21:35:19 +0000 Subject: [PATCH] add eslinting, fix linting issues --- .eslintrc.json | 33 ++++++++++++ package.json | 12 ++++- src/db.js | 29 +++++----- src/main.js | 2 +- src/pve.js | 142 ++++++++++++++++++++++--------------------------- src/utils.js | 54 +++++++++---------- 6 files changed, 149 insertions(+), 123 deletions(-) create mode 100644 .eslintrc.json diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..3bee5ed --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,33 @@ +{ + "env": { + "es2021": true, + "node": true + }, + "extends": "standard", + "parserOptions": { + "ecmaVersion": "latest", + "sourceType": "module" + }, + "rules": { + "no-tabs": [ + "error", + { "allowIndentationTabs": true } + ], + "indent": [ + "error", + "tab" + ], + "linebreak-style": [ + "error", + "unix" + ], + "quotes": [ + "error", + "double" + ], + "semi": [ + "error", + "always" + ] + } +} diff --git a/package.json b/package.json index 8d2906f..891a879 100644 --- a/package.json +++ b/package.json @@ -11,5 +11,15 @@ "cors": "^2.8.5", "express": "^4.18.2", "morgan": "^1.10.0" + }, + "devDependencies": { + "eslint": "^8.43.0", + "eslint-config-standard": "^17.1.0", + "eslint-plugin-import": "^2.27.5", + "eslint-plugin-n": "^16.0.1", + "eslint-plugin-promise": "^6.1.1" + }, + "scripts": { + "lint": "eslint --fix src/*.js" } -} \ No newline at end of file +} diff --git a/src/db.js b/src/db.js index 1be8cd3..25a2dae 100644 --- a/src/db.js +++ b/src/db.js @@ -1,43 +1,46 @@ import { readFileSync, writeFileSync } from "fs"; import { exit } from "process"; -class localdb { +class LocalDB { #filename = "config/localdb.json"; #data = null; - constructor() { + constructor () { try { this.load(this.#filename); - } - catch { + } catch { console.log("Error: localdb.json was not found. Please follow the directions in the README to initialize localdb.json."); exit(1); } } - load(path) { + + load (path) { this.#data = JSON.parse(readFileSync(path)); } - save(path) { + + save (path) { writeFileSync(path, JSON.stringify(this.#data)); } - getApplicationConfig() { + + getApplicationConfig () { return this.#data.application; } - getResourceConfig() { + + getResourceConfig () { return this.#data.resources; } - getUserConfig(username) { + + getUserConfig (username) { if (this.#data.users[username]) { return this.#data.users[username]; - } - else { + } else { return null; } } } -export const db = new localdb(); +export const db = new LocalDB(); export const pveAPI = db.getApplicationConfig().pveAPI; export const pveAPIToken = db.getApplicationConfig().pveAPIToken; export const listenPort = db.getApplicationConfig().listenPort; export const hostname = db.getApplicationConfig().hostname; -export const domain = db.getApplicationConfig().domain; \ No newline at end of file +export const domain = db.getApplicationConfig().domain; diff --git a/src/main.js b/src/main.js index 054f682..6daed85 100644 --- a/src/main.js +++ b/src/main.js @@ -11,7 +11,7 @@ import { db, pveAPIToken, listenPort, hostname, domain } from "./db.js"; const app = express(); app.use(bodyParser.urlencoded({ extended: true })); -app.use(cookieParser()) +app.use(cookieParser()); app.use(cors({ origin: hostname })); app.use(morgan("combined")); diff --git a/src/pve.js b/src/pve.js index cf28874..c912205 100644 --- a/src/pve.js +++ b/src/pve.js @@ -1,21 +1,20 @@ -import axios from 'axios'; +import axios from "axios"; import { pveAPI, pveAPIToken } from "./db.js"; -export async function requestPVE(path, method, cookies, body = null, token = null) { - let url = `${pveAPI}${path}`; - let content = { - method: method, +export async function requestPVE (path, method, cookies, body = null, token = null) { + const url = `${pveAPI}${path}`; + const content = { + method, mode: "cors", credentials: "include", headers: { "Content-Type": "application/x-www-form-urlencoded" - }, - } + } + }; if (token) { content.headers.Authorization = `PVEAPIToken=${token.user}@${token.realm}!${token.id}=${token.uuid}`; - } - else if (cookies) { + } else if (cookies) { content.headers.CSRFPreventionToken = cookies.CSRFPreventionToken; content.headers.Cookie = `PVEAuthCookie=${cookies.PVEAuthCookie}; CSRFPreventionToken=${cookies.CSRFPreventionToken}`; } @@ -25,84 +24,73 @@ export async function requestPVE(path, method, cookies, body = null, token = nul } try { - let response = await axios.request(url, content); + const response = await axios.request(url, content); return response; - } - catch (error) { + } catch (error) { return error.response; } } -export async function handleResponse(node, result, res) { +export async function handleResponse (node, result, res) { const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay)); if (result.data.data && typeof (result.data.data) === "string" && result.data.data.startsWith("UPID:")) { - let upid = result.data.data; - while (true) { - let taskStatus = await requestPVE(`/nodes/${node}/tasks/${upid}/status`, "GET", null, null, pveAPIToken); - if (taskStatus.data.data.status === "stopped" && taskStatus.data.data.exitstatus === "OK") { - let result = taskStatus.data.data; - let taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken); - result.log = taskLog.data.data; - res.status(200).send(result); - res.end(); - return; - } - else if (taskStatus.data.data.status === "stopped") { - let result = taskStatus.data.data; - let taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken); - result.log = taskLog.data.data; - res.status(500).send(result); - res.end(); - return; - } - else { - await waitFor(1000); - } + const upid = result.data.data; + let taskStatus = await requestPVE(`/nodes/${node}/tasks/${upid}/status`, "GET", null, null, pveAPIToken); + while (taskStatus.data.data.status !== "stopped") { + await waitFor(1000); + taskStatus = await requestPVE(`/nodes/${node}/tasks/${upid}/status`, "GET", null, null, pveAPIToken); } - } - else { + if (taskStatus.data.data.exitstatus === "OK") { + const result = taskStatus.data.data; + const taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken); + result.log = taskLog.data.data; + res.status(200).send(result); + res.end(); + } else { + const result = taskStatus.data.data; + const taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken); + result.log = taskLog.data.data; + res.status(500).send(result); + res.end(); + } + } else { res.status(result.status).send(result.data); res.end(); } } -export async function getUsedResources(req, resourceMeta) { - let response = await requestPVE("/cluster/resources", "GET", req.cookies); - let used = {}; - let diskprefixes = []; - for (let resourceName of Object.keys(resourceMeta)) { +export async function getUsedResources (req, resourceMeta) { + const response = await requestPVE("/cluster/resources", "GET", req.cookies); + const used = {}; + const diskprefixes = []; + for (const resourceName of Object.keys(resourceMeta)) { if (resourceMeta[resourceName].type === "storage") { used[resourceName] = 0; - for (let diskPrefix of resourceMeta[resourceName].disks) { + for (const diskPrefix of resourceMeta[resourceName].disks) { diskprefixes.push(diskPrefix); } - } - else if (resourceMeta[resourceName].type === "list") { + } else if (resourceMeta[resourceName].type === "list") { used[resourceName] = []; - } - else { + } else { used[resourceName] = 0; } } - for (let instance of response.data.data) { + for (const instance of response.data.data) { if (instance.type === "lxc" || instance.type === "qemu") { let config = await requestPVE(`/nodes/${instance.node}/${instance.type}/${instance.vmid}/config`, "GET", req.cookies); config = config.data.data; - for (let key of Object.keys(config)) { + for (const key of Object.keys(config)) { if (Object.keys(used).includes(key) && resourceMeta[key].type === "numeric") { used[key] += Number(config[key]); - } - else if (diskprefixes.some(prefix => key.startsWith(prefix))) { - let diskInfo = await getDiskInfo(instance.node, instance.type, instance.vmid, key); + } else if (diskprefixes.some(prefix => key.startsWith(prefix))) { + const diskInfo = await getDiskInfo(instance.node, instance.type, instance.vmid, key); if (diskInfo) { // only count if disk exists used[diskInfo.storage] += Number(diskInfo.size); } - } - else if (key.startsWith("net") && config[key].includes("rate=")) { // only count net instances with a rate limit + } else if (key.startsWith("net") && config[key].includes("rate=")) { // only count net instances with a rate limit used.network += Number(config[key].split("rate=")[1].split(",")[0]); - } - else if (key.startsWith("hostpci")) { - let deviceInfo = await getDeviceInfo(instance.node, instance.type, instance.vmid, config[key].split(",")[0]); + } else if (key.startsWith("hostpci")) { + const deviceInfo = await getDeviceInfo(instance.node, instance.type, instance.vmid, config[key].split(",")[0]); if (deviceInfo) { // only count if device exists used.pci.push(deviceInfo.device_name); } @@ -113,52 +101,50 @@ export async function getUsedResources(req, resourceMeta) { return used; } -export async function getDiskInfo(node, type, vmid, disk) { +export async function getDiskInfo (node, type, vmid, disk) { try { - let config = await requestPVE(`/nodes/${node}/${type}/${vmid}/config`, "GET", null, null, pveAPIToken); - let storageID = config.data.data[disk].split(":")[0]; - let volID = config.data.data[disk].split(",")[0]; - let volInfo = await requestPVE(`/nodes/${node}/storage/${storageID}/content/${volID}`, "GET", null, null, pveAPIToken); + const config = await requestPVE(`/nodes/${node}/${type}/${vmid}/config`, "GET", null, null, pveAPIToken); + const storageID = config.data.data[disk].split(":")[0]; + const volID = config.data.data[disk].split(",")[0]; + const volInfo = await requestPVE(`/nodes/${node}/storage/${storageID}/content/${volID}`, "GET", null, null, pveAPIToken); volInfo.data.data.storage = storageID; return volInfo.data.data; - } - catch { + } catch { return null; } } -export async function getDeviceInfo(node, type, vmid, qid) { +export async function getDeviceInfo (node, type, vmid, qid) { try { - let result = (await requestPVE(`/nodes/${node}/hardware/pci`, "GET", null, null, pveAPIToken)).data.data; - let deviceData = []; + const result = (await requestPVE(`/nodes/${node}/hardware/pci`, "GET", null, null, pveAPIToken)).data.data; + const deviceData = []; result.forEach((element) => { if (element.id.startsWith(qid)) { deviceData.push(element); } }); - deviceData.sort((a, b) => { return a.id < b.id }) - let device = deviceData[0]; + deviceData.sort((a, b) => { return a.id < b.id; }); + const device = deviceData[0]; device.subfn = structuredClone(deviceData.slice(1)); return device; - } - catch { + } catch { return null; } } -export async function getNodeAvailDevices(node, cookies) { +export async function getNodeAvailDevices (node, cookies) { // get node pci devices let nodeAvailPci = (await requestPVE(`/nodes/${node}/hardware/pci`, "GET", cookies, null, pveAPIToken)).data.data; // for each node container, get its config and remove devices which are already used - let vms = (await requestPVE(`/nodes/${node}/qemu`, "GET", cookies, null, pveAPIToken)).data.data; - for (let vm of vms) { - let config = (await requestPVE(`/nodes/${node}/qemu/${vm.vmid}/config`, "GET", cookies, null, pveAPIToken)).data.data; + const vms = (await requestPVE(`/nodes/${node}/qemu`, "GET", cookies, null, pveAPIToken)).data.data; + for (const vm of vms) { + const config = (await requestPVE(`/nodes/${node}/qemu/${vm.vmid}/config`, "GET", cookies, null, pveAPIToken)).data.data; Object.keys(config).forEach((key) => { if (key.startsWith("hostpci")) { - let device_id = config[key].split(",")[0]; - nodeAvailPci = nodeAvailPci.filter(element => !element.id.includes(device_id)); + const deviceID = config[key].split(",")[0]; + nodeAvailPci = nodeAvailPci.filter(element => !element.id.includes(deviceID)); } }); } return nodeAvailPci; -} \ No newline at end of file +} diff --git a/src/utils.js b/src/utils.js index 62609db..247cc7a 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,74 +1,68 @@ import { getUsedResources, requestPVE } from "./pve.js"; import { db } from "./db.js"; -export async function checkAuth(cookies, res, vmpath = null) { +export async function checkAuth (cookies, res, vmpath = null) { let auth = false; if (db.getUserConfig(cookies.username) === null) { auth = false; - res.status(401).send({ auth: auth, path: vmpath ? `${vmpath}/config` : "/version", error: `user ${cookies.username} not found in localdb` }); + res.status(401).send({ auth, path: vmpath ? `${vmpath}/config` : "/version", error: `User ${cookies.username} not found in localdb.` }); res.end(); return false; } if (vmpath) { - let result = await requestPVE(`/${vmpath}/config`, "GET", cookies); + const result = await requestPVE(`/${vmpath}/config`, "GET", cookies); auth = result.status === 200; - } - else { // if no path is specified, then do a simple authentication - let result = await requestPVE("/version", "GET", cookies); + } else { // if no path is specified, then do a simple authentication + const result = await requestPVE("/version", "GET", cookies); auth = result.status === 200; } if (!auth) { - res.status(401).send({ auth: auth, path: vmpath ? `${vmpath}/config` : "/version", error: `user token did not pass authentication check` }); + res.status(401).send({ auth, path: vmpath ? `${vmpath}/config` : "/version", error: "User token did not pass authentication check." }); res.end(); } return auth; } -export async function getUserResources(req, username) { - let dbResources = db.getResourceConfig(); - let used = await getUsedResources(req, dbResources); - let max = db.getUserConfig(username).resources.max; - let avail = {}; +export async function getUserResources (req, username) { + const dbResources = db.getResourceConfig(); + const used = await getUsedResources(req, dbResources); + const max = db.getUserConfig(username).resources.max; + const avail = {}; Object.keys(max).forEach((k) => { if (dbResources[k] && dbResources[k].type === "list") { avail[k] = structuredClone(max[k]); used[k].forEach((usedDeviceName) => { - let index = avail[k].findIndex((maxElement) => usedDeviceName.includes(maxElement)); + const index = avail[k].findIndex((maxElement) => usedDeviceName.includes(maxElement)); avail[k].splice(index, 1); }); - } - else { + } else { avail[k] = max[k] - used[k]; } }); - return { used: used, max: max, avail: avail, resources: dbResources }; + return { used, max, avail, resources: dbResources }; } -export async function approveResources(req, username, request) { - let user = await getUserResources(req, username) - let avail = user.avail; - let resources = user.resources; - let max = user.max; +export async function approveResources (req, username, request) { + const user = await getUserResources(req, username); + const avail = user.avail; + const resources = user.resources; let approved = true; Object.keys(request).forEach((key) => { if (!(key in avail)) { // if requested resource is not in avail, block approved = false; - } - else if (resources[key].type === "list") { - let inAvail = avail[key].some(availElem => request[key].includes(availElem)); - if (inAvail != resources[key].whitelist) { + } else if (resources[key].type === "list") { + const inAvail = avail[key].some(availElem => request[key].includes(availElem)); + if (inAvail !== resources[key].whitelist) { approved = false; } - } - else if (isNaN(avail[key]) || isNaN(request[key])) { // if either the requested or avail resource is NaN, block + } else if (isNaN(avail[key]) || isNaN(request[key])) { // if either the requested or avail resource is NaN, block approved = false; - } - else if (avail[key] - request[key] < 0) { // if the avail resources is less than the requested resources, block + } else if (avail[key] - request[key] < 0) { // if the avail resources is less than the requested resources, block approved = false; } }); return approved; // if all requested resources pass, allow -} \ No newline at end of file +}