homepage/src/pages/api/docker/status/[...service].js

77 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-08-24 10:44:35 +03:00
import Docker from "dockerode";
2022-09-07 16:53:24 +03:00
2022-09-26 15:25:10 +03:00
import getDockerArguments from "utils/config/docker";
2022-08-24 10:44:35 +03:00
export default async function handler(req, res) {
const { service } = req.query;
const [containerName, containerServer] = service;
if (!containerName && !containerServer) {
return res.status(400).send({
error: "docker query parameters are required",
});
}
try {
const dockerArgs = getDockerArguments(containerServer);
const docker = new Docker(dockerArgs.conn);
2022-08-27 00:55:13 +03:00
const containers = await docker.listContainers({
all: true,
});
2022-08-24 10:44:35 +03:00
// bad docker connections can result in a <Buffer ...> object?
// in any case, this ensures the result is the expected array
if (!Array.isArray(containers)) {
return res.status(500).send({
error: "query failed",
});
}
2022-09-07 16:53:24 +03:00
const containerNames = containers.map((container) => container.Names[0].replace(/^\//, ""));
2022-08-24 10:44:35 +03:00
const containerExists = containerNames.includes(containerName);
if (containerExists) {
const container = docker.getContainer(containerName);
const info = await container.inspect();
return res.status(200).json({
status: info.State.Status,
health: info.State.Health?.Status,
2022-08-24 10:44:35 +03:00
});
}
if (dockerArgs.swarm) {
const tasks = await docker.listTasks({
filters: {
service: [containerName],
// A service can have several offline containers, we only look for an active one.
"desired-state": ["running"],
},
})
.catch(() => []);
// For now we are only interested in the first one (in case replicas > 1).
// TODO: Show the result for all replicas/containers?
const taskContainerId = tasks.at(0)?.Status?.ContainerStatus?.ContainerID;
if (taskContainerId) {
const container = docker.getContainer(taskContainerId);
const info = await container.inspect();
return res.status(200).json({
status: info.State.Status,
health: info.State.Health?.Status,
});
}
}
2022-08-24 10:44:35 +03:00
return res.status(200).send({
error: "not found",
2022-08-24 10:44:35 +03:00
});
} catch {
return res.status(500).send({
error: "unknown error",
});
}
}