lasthourcloud/apps/api/src/lib/docker.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-07-22 20:23:16 +00:00
import { executeDockerCmd } from './common';
2022-07-20 13:35:26 +00:00
export async function checkContainer({ dockerId, container, remove = false }: { dockerId: string, container: string, remove?: boolean }): Promise<boolean> {
2022-07-06 09:02:36 +00:00
let containerFound = false;
try {
2022-07-20 13:35:26 +00:00
const { stdout } = await executeDockerCmd({
dockerId,
command:
`docker inspect --format '{{json .State}}' ${container}`
});
2022-07-06 09:02:36 +00:00
const parsedStdout = JSON.parse(stdout);
const status = parsedStdout.Status;
const isRunning = status === 'running';
if (status === 'created') {
2022-07-20 13:35:26 +00:00
await executeDockerCmd({
dockerId,
command:
`docker rm ${container}`
});
2022-07-06 09:02:36 +00:00
}
if (remove && status === 'exited') {
2022-07-20 13:35:26 +00:00
await executeDockerCmd({
dockerId,
command:
`docker rm ${container}`
});
2022-07-06 09:02:36 +00:00
}
if (isRunning) {
containerFound = true;
}
} catch (err) {
// Container not found
}
return containerFound;
}
2022-07-21 12:43:53 +00:00
export async function isContainerExited(dockerId: string, containerName: string): Promise<boolean> {
2022-07-06 09:02:36 +00:00
let isExited = false;
try {
2022-07-21 12:43:53 +00:00
const { stdout } = await executeDockerCmd({ dockerId, command: `docker inspect -f '{{.State.Status}}' ${containerName}` })
2022-07-06 09:02:36 +00:00
if (stdout.trim() === 'exited') {
isExited = true;
}
} catch (error) {
//
}
return isExited;
}
export async function removeContainer({
id,
2022-07-20 13:35:26 +00:00
dockerId
2022-07-06 09:02:36 +00:00
}: {
id: string;
2022-07-20 13:35:26 +00:00
dockerId: string;
2022-07-06 09:02:36 +00:00
}): Promise<void> {
try {
2022-07-21 12:43:53 +00:00
const { stdout } = await executeDockerCmd({ dockerId, command: `docker inspect --format '{{json .State}}' ${id}` })
2022-07-06 09:02:36 +00:00
if (JSON.parse(stdout).Running) {
2022-07-21 12:43:53 +00:00
await executeDockerCmd({ dockerId, command: `docker stop -t 0 ${id}` })
await executeDockerCmd({ dockerId, command: `docker rm ${id}` })
2022-07-06 09:02:36 +00:00
}
} catch (error) {
console.log(error);
throw error;
}
}