import getLogger from "@cocalc/backend/logger";
import { new_counter } from "@cocalc/server/metrics/metrics-recorder";
import { howLongDisconnectedMins } from "@cocalc/database/postgres/record-connect-error";
import type { PostgreSQL } from "@cocalc/database/postgres/types";
import { seconds2hms } from "@cocalc/util/misc";
import express, { Response } from "express";
import { createServer, Server } from "net";
import { isFloat } from "validator";
import { database_is_working } from "@cocalc/server/metrics/hub_register";
const logger = getLogger("hub:healthcheck");
const { debug: L } = logger;
const HEALTHCHECKS = new_counter(
"healthchecks_total",
"test healthcheck counter",
["status"],
);
interface HealthcheckData {
code: 200 | 404;
txt: string;
}
function init_self_terminate(): {
startup: number;
shutdown?: number;
drain?: number;
} {
const D = logger.extend("init_self_terminate").debug;
const startup = Date.now();
const conf = process.env.COCALC_HUB_SELF_TERMINATE;
if (conf == null) {
D("COCALC_HUB_SELF_TERMINATE env var not set, hence no self-termination");
return { startup };
}
const [from_str, to_str, drain_str] = conf.trim().split(",");
if (!isFloat(from_str, { gt: 0 }))
throw new Error("COCALC_HUB_SELF_TERMINATE/from not a positive float");
if (!isFloat(to_str, { gt: 0 }))
throw new Error("COCALC_HUB_SELF_TERMINATE/to not a positive float");
if (!isFloat(drain_str, { gt: 0 }))
throw new Error("COCALC_HUB_SELF_TERMINATE/drain not a positive float");
const from = parseFloat(from_str);
const to = parseFloat(to_str);
const drain_h = parseFloat(drain_str) / 60;
D("parsed data:", { from, to, drain_h });
if (from > to)
throw Error(
"COCALC_HUB_SELF_TERMINATE 'from' must be smaller than 'to', e.g. '24,48,15'",
);
const uptime = Math.random() * (to - from);
const hours2ms = 1000 * 60 * 60;
const shutdown = startup + (from + uptime) * hours2ms;
const drain = shutdown - drain_h * hours2ms;
if (startup > drain) {
throw new Error(
`COCALC_HUB_SELF_TERMINATE: startup must be smaller than drain – ${startup}>${drain}`,
);
}
D({
startup: new Date(startup).toISOString(),
drain: new Date(drain).toISOString(),
shutdown: new Date(shutdown).toISOString(),
uptime: seconds2hms((hours2ms * uptime) / 1000),
draintime: seconds2hms((drain_h * hours2ms) / 1000),
});
return { startup, shutdown, drain };
}
const { startup, shutdown, drain } = init_self_terminate();
let agent_port = 0;
let agent_host = "0.0.0.0";
export function set_agent_endpoint(port: number, host: string) {
L(`set_agent_endpoint ${agent_host}:${agent_port}`);
agent_port = port;
agent_host = host;
}
let agent_check_server: Server | undefined;
function setup_agent_check() {
if (agent_port == 0 || drain == null) {
L("setup_agent_check: agent_port not set, no agent checks");
return;
}
agent_check_server = createServer((c) => {
c.on("error", (err) => {
L(`agent_check: connection error`, err);
});
let msg = Date.now() < drain ? "ready up 100%" : "10%";
c.write(msg + "\r\n");
c.destroy();
});
agent_check_server.listen(agent_port, agent_host);
L(`setup_agent_check: listening on ${agent_host}:${agent_port}`);
}
export interface Check {
status: string;
abort?: boolean;
}
interface Opts {
db: PostgreSQL;
router: express.Router;
extra?: (() => Promise<Check>)[];
}
export function process_alive(): HealthcheckData {
let txt = "alive: YES";
let is_dead = true;
if (!database_is_working()) {
txt = "alive: NO – database not working";
} else if (shutdown != null && Date.now() > shutdown) {
txt = "alive: NO – shutdown initiated";
} else {
is_dead = false;
}
const code = is_dead ? 404 : 200;
return { txt, code };
}
function checkConcurrent(db: PostgreSQL): Check {
const c = db.concurrent();
if (c >= db._concurrent_warn) {
return {
status: `hub not healthy, since concurrent ${c} >= ${db._concurrent_warn}`,
abort: true,
};
} else {
return { status: `concurrent ${c} < ${db._concurrent_warn}` };
}
}
function checkUptime(): Check {
const now = Date.now();
const uptime = seconds2hms((now - startup) / 1000);
if (shutdown != null && drain != null) {
if (now >= shutdown) {
const msg = `uptime ${uptime} – expired, terminating now`;
L(msg);
return { status: msg, abort: true };
} else {
const until = seconds2hms((shutdown - now) / 1000);
const drain_str =
drain > now
? `draining in ${seconds2hms((drain - now) / 1000)}`
: "draining now";
const msg = `uptime ${uptime} – ${drain_str} – terminating in ${until}`;
L(msg);
return { status: msg };
}
} else {
const msg = `uptime ${uptime} – no self-termination`;
L(msg);
return { status: msg };
}
}
const DB_ERRORS_THRESHOLD_MIN = parseInt(
process.env.COCALC_DB_ERRORS_THRESHOLD_MIN ?? "5",
);
function checkDBConnectivity(): Check {
if (DB_ERRORS_THRESHOLD_MIN <= 0) {
return { status: "db connectivity check disabled" };
}
const num = howLongDisconnectedMins();
if (num == null) {
return { status: "no DB connection problems", abort: false };
}
const numStr = num.toFixed(2);
const above = num >= DB_ERRORS_THRESHOLD_MIN;
const status = above
? `DB problems for ${numStr} >= ${DB_ERRORS_THRESHOLD_MIN} mins`
: `DB problems for ${numStr} < ${DB_ERRORS_THRESHOLD_MIN} mins`;
return { status, abort: above };
}
async function process_health_check(
db: PostgreSQL,
extra: (() => Promise<Check>)[] = [],
): Promise<HealthcheckData> {
let any_abort = false;
let txt = "healthchecks:\n";
for (const test of [
() => checkConcurrent(db),
checkUptime,
checkDBConnectivity,
...extra,
]) {
try {
const { status, abort = false } = await test();
const statusTxt = abort ? "FAIL" : "OK";
txt += `${status} – ${statusTxt}\n`;
any_abort = any_abort || abort;
L(`process_health_check: ${status} – ${statusTxt}`);
} catch (err) {
L(`process_health_check ERRROR: ${err}`);
HEALTHCHECKS.labels("ERROR").inc();
}
}
const code = any_abort ? 404 : 200;
HEALTHCHECKS.labels(any_abort ? "FAIL" : "OK").inc();
return { code, txt };
}
export async function setup_health_checks(opts: Opts): Promise<void> {
const { db, extra, router } = opts;
setup_agent_check();
router.get("/alive", (_, res: Response) => {
const { code, txt } = process_alive();
res.type("txt");
res.status(code);
res.send(txt);
});
router.get("/healthcheck", async (_, res: Response) => {
const { txt, code } = await process_health_check(db, extra);
res.status(code);
res.type("txt");
res.send(txt);
});
router.get("/concurrent-warn", (_, res) => {
res.type("txt");
if (!database_is_working()) {
L("/concurrent-warn: not healthy, since database connection not working");
res.status(404).end();
return;
}
const c = db.concurrent();
if (c >= db._concurrent_warn) {
L(
`/concurrent-warn: not healthy, since concurrent ${c} >= ${db._concurrent_warn}`,
);
res.status(404).end();
return;
}
res.send(`${c}`);
});
router.get("/concurrent", (_, res) => {
res.type("txt");
res.send(`${db.concurrent()}`);
});
}