add eslinting, fix linting issues

This commit is contained in:
Arthur Lu 2023-06-29 21:35:19 +00:00
parent ab8d9e16cc
commit b822f7f856
6 changed files with 149 additions and 123 deletions

33
.eslintrc.json Normal file
View File

@ -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"
]
}
}

View File

@ -11,5 +11,15 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"morgan": "^1.10.0" "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"
} }
} }

View File

@ -1,41 +1,44 @@
import { readFileSync, writeFileSync } from "fs"; import { readFileSync, writeFileSync } from "fs";
import { exit } from "process"; import { exit } from "process";
class localdb { class LocalDB {
#filename = "config/localdb.json"; #filename = "config/localdb.json";
#data = null; #data = null;
constructor () { constructor () {
try { try {
this.load(this.#filename); 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."); console.log("Error: localdb.json was not found. Please follow the directions in the README to initialize localdb.json.");
exit(1); exit(1);
} }
} }
load (path) { load (path) {
this.#data = JSON.parse(readFileSync(path)); this.#data = JSON.parse(readFileSync(path));
} }
save (path) { save (path) {
writeFileSync(path, JSON.stringify(this.#data)); writeFileSync(path, JSON.stringify(this.#data));
} }
getApplicationConfig () { getApplicationConfig () {
return this.#data.application; return this.#data.application;
} }
getResourceConfig () { getResourceConfig () {
return this.#data.resources; return this.#data.resources;
} }
getUserConfig (username) { getUserConfig (username) {
if (this.#data.users[username]) { if (this.#data.users[username]) {
return this.#data.users[username]; return this.#data.users[username];
} } else {
else {
return null; return null;
} }
} }
} }
export const db = new localdb(); export const db = new LocalDB();
export const pveAPI = db.getApplicationConfig().pveAPI; export const pveAPI = db.getApplicationConfig().pveAPI;
export const pveAPIToken = db.getApplicationConfig().pveAPIToken; export const pveAPIToken = db.getApplicationConfig().pveAPIToken;
export const listenPort = db.getApplicationConfig().listenPort; export const listenPort = db.getApplicationConfig().listenPort;

View File

@ -11,7 +11,7 @@ import { db, pveAPIToken, listenPort, hostname, domain } from "./db.js";
const app = express(); const app = express();
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser()) app.use(cookieParser());
app.use(cors({ origin: hostname })); app.use(cors({ origin: hostname }));
app.use(morgan("combined")); app.use(morgan("combined"));

View File

@ -1,21 +1,20 @@
import axios from 'axios'; import axios from "axios";
import { pveAPI, pveAPIToken } from "./db.js"; import { pveAPI, pveAPIToken } from "./db.js";
export async function requestPVE (path, method, cookies, body = null, token = null) { export async function requestPVE (path, method, cookies, body = null, token = null) {
let url = `${pveAPI}${path}`; const url = `${pveAPI}${path}`;
let content = { const content = {
method: method, method,
mode: "cors", mode: "cors",
credentials: "include", credentials: "include",
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded" "Content-Type": "application/x-www-form-urlencoded"
},
} }
};
if (token) { if (token) {
content.headers.Authorization = `PVEAPIToken=${token.user}@${token.realm}!${token.id}=${token.uuid}`; 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.CSRFPreventionToken = cookies.CSRFPreventionToken;
content.headers.Cookie = `PVEAuthCookie=${cookies.PVEAuthCookie}; CSRFPreventionToken=${cookies.CSRFPreventionToken}`; content.headers.Cookie = `PVEAuthCookie=${cookies.PVEAuthCookie}; CSRFPreventionToken=${cookies.CSRFPreventionToken}`;
} }
@ -25,10 +24,9 @@ export async function requestPVE(path, method, cookies, body = null, token = nul
} }
try { try {
let response = await axios.request(url, content); const response = await axios.request(url, content);
return response; return response;
} } catch (error) {
catch (error) {
return error.response; return error.response;
} }
} }
@ -36,73 +34,63 @@ export async function requestPVE(path, method, cookies, body = null, token = nul
export async function handleResponse (node, result, res) { export async function handleResponse (node, result, res) {
const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay)); const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay));
if (result.data.data && typeof (result.data.data) === "string" && result.data.data.startsWith("UPID:")) { if (result.data.data && typeof (result.data.data) === "string" && result.data.data.startsWith("UPID:")) {
let upid = result.data.data; const upid = result.data.data;
while (true) {
let taskStatus = await requestPVE(`/nodes/${node}/tasks/${upid}/status`, "GET", null, null, pveAPIToken); let taskStatus = await requestPVE(`/nodes/${node}/tasks/${upid}/status`, "GET", null, null, pveAPIToken);
if (taskStatus.data.data.status === "stopped" && taskStatus.data.data.exitstatus === "OK") { while (taskStatus.data.data.status !== "stopped") {
let result = taskStatus.data.data; await waitFor(1000);
let taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken); taskStatus = await requestPVE(`/nodes/${node}/tasks/${upid}/status`, "GET", null, null, pveAPIToken);
}
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; result.log = taskLog.data.data;
res.status(200).send(result); res.status(200).send(result);
res.end(); res.end();
return; } else {
} const result = taskStatus.data.data;
else if (taskStatus.data.data.status === "stopped") { const taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken);
let result = taskStatus.data.data;
let taskLog = await requestPVE(`/nodes/${node}/tasks/${upid}/log`, "GET", null, null, pveAPIToken);
result.log = taskLog.data.data; result.log = taskLog.data.data;
res.status(500).send(result); res.status(500).send(result);
res.end(); res.end();
return;
} }
else { } else {
await waitFor(1000);
}
}
}
else {
res.status(result.status).send(result.data); res.status(result.status).send(result.data);
res.end(); res.end();
} }
} }
export async function getUsedResources (req, resourceMeta) { export async function getUsedResources (req, resourceMeta) {
let response = await requestPVE("/cluster/resources", "GET", req.cookies); const response = await requestPVE("/cluster/resources", "GET", req.cookies);
let used = {}; const used = {};
let diskprefixes = []; const diskprefixes = [];
for (let resourceName of Object.keys(resourceMeta)) { for (const resourceName of Object.keys(resourceMeta)) {
if (resourceMeta[resourceName].type === "storage") { if (resourceMeta[resourceName].type === "storage") {
used[resourceName] = 0; used[resourceName] = 0;
for (let diskPrefix of resourceMeta[resourceName].disks) { for (const diskPrefix of resourceMeta[resourceName].disks) {
diskprefixes.push(diskPrefix); diskprefixes.push(diskPrefix);
} }
} } else if (resourceMeta[resourceName].type === "list") {
else if (resourceMeta[resourceName].type === "list") {
used[resourceName] = []; used[resourceName] = [];
} } else {
else {
used[resourceName] = 0; used[resourceName] = 0;
} }
} }
for (let instance of response.data.data) { for (const instance of response.data.data) {
if (instance.type === "lxc" || instance.type === "qemu") { if (instance.type === "lxc" || instance.type === "qemu") {
let config = await requestPVE(`/nodes/${instance.node}/${instance.type}/${instance.vmid}/config`, "GET", req.cookies); let config = await requestPVE(`/nodes/${instance.node}/${instance.type}/${instance.vmid}/config`, "GET", req.cookies);
config = config.data.data; 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") { if (Object.keys(used).includes(key) && resourceMeta[key].type === "numeric") {
used[key] += Number(config[key]); used[key] += Number(config[key]);
} } else if (diskprefixes.some(prefix => key.startsWith(prefix))) {
else if (diskprefixes.some(prefix => key.startsWith(prefix))) { const diskInfo = await getDiskInfo(instance.node, instance.type, instance.vmid, key);
let diskInfo = await getDiskInfo(instance.node, instance.type, instance.vmid, key);
if (diskInfo) { // only count if disk exists if (diskInfo) { // only count if disk exists
used[diskInfo.storage] += Number(diskInfo.size); 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]); used.network += Number(config[key].split("rate=")[1].split(",")[0]);
} } else if (key.startsWith("hostpci")) {
else if (key.startsWith("hostpci")) { const deviceInfo = await getDeviceInfo(instance.node, instance.type, instance.vmid, config[key].split(",")[0]);
let deviceInfo = await getDeviceInfo(instance.node, instance.type, instance.vmid, config[key].split(",")[0]);
if (deviceInfo) { // only count if device exists if (deviceInfo) { // only count if device exists
used.pci.push(deviceInfo.device_name); used.pci.push(deviceInfo.device_name);
} }
@ -115,33 +103,31 @@ export async function getUsedResources(req, resourceMeta) {
export async function getDiskInfo (node, type, vmid, disk) { export async function getDiskInfo (node, type, vmid, disk) {
try { try {
let config = await requestPVE(`/nodes/${node}/${type}/${vmid}/config`, "GET", null, null, pveAPIToken); const config = await requestPVE(`/nodes/${node}/${type}/${vmid}/config`, "GET", null, null, pveAPIToken);
let storageID = config.data.data[disk].split(":")[0]; const storageID = config.data.data[disk].split(":")[0];
let volID = config.data.data[disk].split(",")[0]; const volID = config.data.data[disk].split(",")[0];
let volInfo = await requestPVE(`/nodes/${node}/storage/${storageID}/content/${volID}`, "GET", null, null, pveAPIToken); const volInfo = await requestPVE(`/nodes/${node}/storage/${storageID}/content/${volID}`, "GET", null, null, pveAPIToken);
volInfo.data.data.storage = storageID; volInfo.data.data.storage = storageID;
return volInfo.data.data; return volInfo.data.data;
} } catch {
catch {
return null; return null;
} }
} }
export async function getDeviceInfo (node, type, vmid, qid) { export async function getDeviceInfo (node, type, vmid, qid) {
try { try {
let result = (await requestPVE(`/nodes/${node}/hardware/pci`, "GET", null, null, pveAPIToken)).data.data; const result = (await requestPVE(`/nodes/${node}/hardware/pci`, "GET", null, null, pveAPIToken)).data.data;
let deviceData = []; const deviceData = [];
result.forEach((element) => { result.forEach((element) => {
if (element.id.startsWith(qid)) { if (element.id.startsWith(qid)) {
deviceData.push(element); deviceData.push(element);
} }
}); });
deviceData.sort((a, b) => { return a.id < b.id }) deviceData.sort((a, b) => { return a.id < b.id; });
let device = deviceData[0]; const device = deviceData[0];
device.subfn = structuredClone(deviceData.slice(1)); device.subfn = structuredClone(deviceData.slice(1));
return device; return device;
} } catch {
catch {
return null; return null;
} }
} }
@ -150,13 +136,13 @@ export async function getNodeAvailDevices(node, cookies) {
// get node pci devices // get node pci devices
let nodeAvailPci = (await requestPVE(`/nodes/${node}/hardware/pci`, "GET", cookies, null, pveAPIToken)).data.data; 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 // 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; const vms = (await requestPVE(`/nodes/${node}/qemu`, "GET", cookies, null, pveAPIToken)).data.data;
for (let vm of vms) { for (const vm of vms) {
let config = (await requestPVE(`/nodes/${node}/qemu/${vm.vmid}/config`, "GET", cookies, null, pveAPIToken)).data.data; const config = (await requestPVE(`/nodes/${node}/qemu/${vm.vmid}/config`, "GET", cookies, null, pveAPIToken)).data.data;
Object.keys(config).forEach((key) => { Object.keys(config).forEach((key) => {
if (key.startsWith("hostpci")) { if (key.startsWith("hostpci")) {
let device_id = config[key].split(",")[0]; const deviceID = config[key].split(",")[0];
nodeAvailPci = nodeAvailPci.filter(element => !element.id.includes(device_id)); nodeAvailPci = nodeAvailPci.filter(element => !element.id.includes(deviceID));
} }
}); });
} }

View File

@ -6,67 +6,61 @@ export async function checkAuth(cookies, res, vmpath = null) {
if (db.getUserConfig(cookies.username) === null) { if (db.getUserConfig(cookies.username) === null) {
auth = false; 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(); res.end();
return false; return false;
} }
if (vmpath) { if (vmpath) {
let result = await requestPVE(`/${vmpath}/config`, "GET", cookies); const result = await requestPVE(`/${vmpath}/config`, "GET", cookies);
auth = result.status === 200; auth = result.status === 200;
} } else { // if no path is specified, then do a simple authentication
else { // if no path is specified, then do a simple authentication const result = await requestPVE("/version", "GET", cookies);
let result = await requestPVE("/version", "GET", cookies);
auth = result.status === 200; auth = result.status === 200;
} }
if (!auth) { 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(); res.end();
} }
return auth; return auth;
} }
export async function getUserResources (req, username) { export async function getUserResources (req, username) {
let dbResources = db.getResourceConfig(); const dbResources = db.getResourceConfig();
let used = await getUsedResources(req, dbResources); const used = await getUsedResources(req, dbResources);
let max = db.getUserConfig(username).resources.max; const max = db.getUserConfig(username).resources.max;
let avail = {}; const avail = {};
Object.keys(max).forEach((k) => { Object.keys(max).forEach((k) => {
if (dbResources[k] && dbResources[k].type === "list") { if (dbResources[k] && dbResources[k].type === "list") {
avail[k] = structuredClone(max[k]); avail[k] = structuredClone(max[k]);
used[k].forEach((usedDeviceName) => { 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); avail[k].splice(index, 1);
}); });
} } else {
else {
avail[k] = max[k] - used[k]; 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) { export async function approveResources (req, username, request) {
let user = await getUserResources(req, username) const user = await getUserResources(req, username);
let avail = user.avail; const avail = user.avail;
let resources = user.resources; const resources = user.resources;
let max = user.max;
let approved = true; let approved = true;
Object.keys(request).forEach((key) => { Object.keys(request).forEach((key) => {
if (!(key in avail)) { // if requested resource is not in avail, block if (!(key in avail)) { // if requested resource is not in avail, block
approved = false; approved = false;
} } else if (resources[key].type === "list") {
else if (resources[key].type === "list") { const inAvail = avail[key].some(availElem => request[key].includes(availElem));
let inAvail = avail[key].some(availElem => request[key].includes(availElem)); if (inAvail !== resources[key].whitelist) {
if (inAvail != resources[key].whitelist) {
approved = false; 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; 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; approved = false;
} }
}); });