lasthourcloud/apps/api/src/jobs/cleanupStorage.ts

62 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-07-06 11:02:36 +02:00
import { parentPort } from 'node:worker_threads';
2022-07-22 15:16:51 +00:00
import { asyncExecShell, cleanupDockerStorage, executeDockerCmd, isDev, prisma, version } from '../lib/common';
2022-07-06 11:02:36 +02:00
import { getEngine } from '../lib/docker';
(async () => {
if (parentPort) {
const destinationDockers = await prisma.destinationDocker.findMany();
2022-07-22 15:16:51 +00:00
let enginesDone = new Set()
for (const destination of destinationDockers) {
if (enginesDone.has(destination.engine) || enginesDone.has(destination.remoteIpAddress)) return
if (destination.engine) enginesDone.add(destination.engine)
if (destination.remoteIpAddress) enginesDone.add(destination.remoteIpAddress)
2022-07-06 11:02:36 +02:00
let lowDiskSpace = false;
try {
let stdout = null
if (!isDev) {
2022-07-22 15:16:51 +00:00
const output = await executeDockerCmd({ dockerId: destination.id, command: `docker exec coolify sh -c 'df -kPT /'` })
stdout = output.stdout;
} else {
const output = await asyncExecShell(
`df -kPT /`
);
stdout = output.stdout;
2022-07-06 11:02:36 +02:00
}
let lines = stdout.trim().split('\n');
let header = lines[0];
let regex =
/^Filesystem\s+|Type\s+|1024-blocks|\s+Used|\s+Available|\s+Capacity|\s+Mounted on\s*$/g;
const boundaries = [];
let match;
while ((match = regex.exec(header))) {
boundaries.push(match[0].length);
2022-07-06 11:02:36 +02:00
}
boundaries[boundaries.length - 1] = -1;
const data = lines.slice(1).map((line) => {
const cl = boundaries.map((boundary) => {
const column = boundary > 0 ? line.slice(0, boundary) : line;
line = line.slice(boundary);
return column.trim();
});
return {
capacity: Number.parseInt(cl[5], 10) / 100
};
});
if (data.length > 0) {
const { capacity } = data[0];
if (capacity > 0.8) {
lowDiskSpace = true;
}
2022-07-06 11:02:36 +02:00
}
} catch (error) {
console.log(error);
2022-07-06 11:02:36 +02:00
}
2022-07-22 15:16:51 +00:00
await cleanupDockerStorage(destination.id, lowDiskSpace, false)
2022-07-06 11:02:36 +02:00
}
await prisma.$disconnect();
2022-07-06 11:02:36 +02:00
} else process.exit(0);
})();