2022-10-24 17:03:35 -05:00
|
|
|
import { CoreV1Api } from "@kubernetes/client-node";
|
|
|
|
|
|
|
|
import getKubeConfig from "../../../../utils/config/kubernetes";
|
2022-10-26 10:15:25 -05:00
|
|
|
import createLogger from "../../../../utils/logger";
|
|
|
|
|
|
|
|
const logger = createLogger("kubernetesStatusService");
|
2022-10-24 17:03:35 -05:00
|
|
|
|
|
|
|
export default async function handler(req, res) {
|
|
|
|
const APP_LABEL = "app.kubernetes.io/name";
|
2022-12-08 16:03:29 -06:00
|
|
|
const { service, podSelector } = req.query;
|
2022-10-24 17:03:35 -05:00
|
|
|
|
|
|
|
const [namespace, appName] = service;
|
|
|
|
if (!namespace && !appName) {
|
|
|
|
res.status(400).send({
|
|
|
|
error: "kubernetes query parameters are required",
|
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
2022-12-08 16:03:29 -06:00
|
|
|
const labelSelector = podSelector !== undefined ? podSelector : `${APP_LABEL}=${appName}`;
|
|
|
|
logger.info("labelSelector %s/%s = %s", namespace, appName, labelSelector);
|
2022-10-24 17:03:35 -05:00
|
|
|
try {
|
|
|
|
const kc = getKubeConfig();
|
2022-10-27 16:53:54 -05:00
|
|
|
if (!kc) {
|
|
|
|
res.status(500).send({
|
|
|
|
error: "No kubernetes configuration"
|
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
2022-10-24 17:03:35 -05:00
|
|
|
const coreApi = kc.makeApiClient(CoreV1Api);
|
2022-10-26 10:15:25 -05:00
|
|
|
const podsResponse = await coreApi.listNamespacedPod(namespace, null, null, null, null, labelSelector)
|
|
|
|
.then((response) => response.body)
|
|
|
|
.catch((err) => {
|
|
|
|
logger.error("Error getting pods: %d %s %s", err.statusCode, err.body, err.response);
|
|
|
|
return null;
|
|
|
|
});
|
|
|
|
if (!podsResponse) {
|
|
|
|
res.status(500).send({
|
|
|
|
error: "Error communicating with kubernetes"
|
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const pods = podsResponse.items;
|
2022-10-24 17:03:35 -05:00
|
|
|
|
|
|
|
if (pods.length === 0) {
|
2022-10-26 10:15:25 -05:00
|
|
|
res.status(404).send({
|
2022-10-24 17:03:35 -05:00
|
|
|
error: "not found",
|
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
2022-12-08 16:03:29 -06:00
|
|
|
const someReady = pods.find(pod => pod.status.phase === "Running");
|
|
|
|
const allReady = pods.every((pod) => pod.status.phase === "Running");
|
|
|
|
let status = "down";
|
|
|
|
if (allReady) {
|
|
|
|
status = "running";
|
|
|
|
} else if (someReady) {
|
|
|
|
status = "partial";
|
|
|
|
}
|
2022-10-24 17:03:35 -05:00
|
|
|
res.status(200).json({
|
|
|
|
status
|
|
|
|
});
|
2022-10-26 10:15:25 -05:00
|
|
|
} catch (e) {
|
|
|
|
logger.error(e);
|
2022-10-24 17:03:35 -05:00
|
|
|
res.status(500).send({
|
|
|
|
error: "unknown error",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|