Compare commits

...

22 commits

Author SHA1 Message Date
Peace
9bb565cf3c
Merge ac8d1d6346 into 459fb138f2 2024-10-26 14:13:07 +00:00
Louis Lam
459fb138f2
Add next and next-slim tags (#5253)
Some checks are pending
Auto Test / auto-test (20, ubuntu-latest) (push) Blocked by required conditions
Auto Test / auto-test (20, windows-latest) (push) Blocked by required conditions
Auto Test / armv7-simple-test (18, ARMv7) (push) Waiting to run
Auto Test / armv7-simple-test (20, ARMv7) (push) Waiting to run
Auto Test / check-linters (push) Waiting to run
Auto Test / e2e-test (push) Waiting to run
Auto Test / auto-test (18, ARM64) (push) Blocked by required conditions
Auto Test / auto-test (18, macos-latest) (push) Blocked by required conditions
Auto Test / auto-test (18, ubuntu-latest) (push) Blocked by required conditions
Auto Test / auto-test (18, windows-latest) (push) Blocked by required conditions
Auto Test / auto-test (20, ARM64) (push) Blocked by required conditions
Auto Test / auto-test (20, macos-latest) (push) Blocked by required conditions
CodeQL / Analyze (push) Waiting to run
Merge Conflict Labeler / Labeling (push) Waiting to run
json-yaml-validate / json-yaml-validate (push) Waiting to run
json-yaml-validate / check-lang-json (push) Waiting to run
2024-10-26 22:12:55 +08:00
Louis Lam
8f950a5145
Update dependencies (#5252) 2024-10-26 21:53:53 +08:00
Louis Lam
4d779cfc69
Data migration and history retention for 2.0.0 (#5075) 2024-10-26 20:50:29 +08:00
Louis Lam
2470451f6d
Fix Apprise download issue (#5251) 2024-10-26 20:47:38 +08:00
Peace
ac8d1d6346
docs: add comments for queries 2024-10-17 17:16:29 +02:00
Peace
ec2cebc5df
perf: option to only get ids of active children 2024-10-17 17:16:08 +02:00
Peace
0a479ecb50
Merge branch 'master' into fix/pause-child-monitors 2024-10-17 00:22:51 +02:00
Peace
c9e5dff162
perf: less recursion for isUnderMaintenance using db query 2024-10-17 00:07:07 +02:00
Peace
16c04f6ac2
perf: less recursion for isParentActive using db query 2024-10-17 00:06:40 +02:00
Peace
5dc66e1495
refactor: make getAllChildrenIDs more compact 2024-10-17 00:05:55 +02:00
Peace
c079971a7b
fix: cast getParent and getChildren to Beans 2024-10-17 00:05:29 +02:00
Peace
71c7ee69c7
feat: db statement to get all active monitors 2024-10-17 00:04:45 +02:00
Peace
22dcba17c8
fix: remove test logging 2024-10-16 22:56:14 +02:00
Peace
f622898ff1
perf: less sql statements and concurrent start/stop 2024-10-16 22:54:15 +02:00
Peace
6179f31348
Merge branch 'master' into fix/pause-child-monitors 2024-10-14 23:08:48 +02:00
Peace
d336d09d78
fix: display children as paused when pausing parent 2024-10-14 23:04:07 +02:00
Peace
b02b21299b
feat: set group to pending if all childs are paused. 2024-10-14 00:01:55 +02:00
Peace
9eda25d0b6
revert: fix: pause child monitors if parent is paused 2024-10-13 23:29:11 +02:00
Peace
d1677300a4
style: fix formatting 2024-10-13 01:16:16 +02:00
Peace
b4fabbb00f
fix: update children in ui on pause 2024-10-13 01:14:24 +02:00
Peace
703e3d0fae
fix: pause child monitors if parent is paused 2024-10-13 00:25:45 +02:00
12 changed files with 2358 additions and 2462 deletions

View file

@ -1,3 +1,13 @@
# Download Apprise deb package
FROM node:20-bookworm-slim AS download-apprise
WORKDIR /app
COPY ./extra/download-apprise.mjs ./download-apprise.mjs
RUN apt update && \
apt --yes --no-install-recommends install curl && \
npm install cheerio semver && \
node ./download-apprise.mjs
# Base Image (Slim)
# If the image changed, the second stage image should be changed too
FROM node:20-bookworm-slim AS base2-slim
ARG TARGETPLATFORM
@ -27,8 +37,9 @@ RUN apt update && \
# apprise = for notifications (Install from the deb package, as the stable one is too old) (workaround for #4867)
# Switching to testing repo is no longer working, as the testing repo is not bookworm anymore.
# python3-paho-mqtt (#4859)
RUN curl http://ftp.debian.org/debian/pool/main/a/apprise/apprise_1.8.0-2_all.deb --output apprise.deb && \
apt update && \
# TODO: no idea how to delete the deb file after installation as it becomes a layer already
COPY --from=download-apprise /app/apprise.deb ./apprise.deb
RUN apt update && \
apt --yes --no-install-recommends install ./apprise.deb python3-paho-mqtt && \
rm -rf /var/lib/apt/lists/* && \
rm -f apprise.deb && \

View file

@ -0,0 +1,57 @@
// Go to http://ftp.debian.org/debian/pool/main/a/apprise/ using fetch api, where it is a apache directory listing page
// Use cheerio to parse the html and get the latest version of Apprise
// call curl to download the latest version of Apprise
// Target file: the latest version of Apprise, which the format is apprise_{VERSION}_all.deb
import * as cheerio from "cheerio";
import semver from "semver";
import * as childProcess from "child_process";
const baseURL = "http://ftp.debian.org/debian/pool/main/a/apprise/";
const response = await fetch(baseURL);
if (!response.ok) {
throw new Error("Failed to fetch page of Apprise Debian repository.");
}
const html = await response.text();
const $ = cheerio.load(html);
// Get all the links in the page
const linkElements = $("a");
// Filter the links which match apprise_{VERSION}_all.deb
const links = [];
const pattern = /apprise_(.*?)_all.deb/;
for (let i = 0; i < linkElements.length; i++) {
const link = linkElements[i];
if (link.attribs.href.match(pattern) && !link.attribs.href.includes("~")) {
links.push({
filename: link.attribs.href,
version: link.attribs.href.match(pattern)[1],
});
}
}
console.log(links);
// semver compare and download
let latestLink = {
filename: "",
version: "0.0.0",
};
for (const link of links) {
if (semver.gt(link.version, latestLink.version)) {
latestLink = link;
}
}
const downloadURL = baseURL + latestLink.filename;
console.log(`Downloading ${downloadURL}...`);
let result = childProcess.spawnSync("curl", [ downloadURL, "--output", "apprise.deb" ]);
console.log(result.stdout?.toString());
console.error(result.stderr?.toString());
process.exit(result.status !== null ? result.status : 1);

View file

@ -0,0 +1,24 @@
const { R } = require("redbean-node");
const Database = require("../server/database");
const args = require("args-parser")(process.argv);
const { Settings } = require("../server/settings");
const main = async () => {
console.log("Connecting the database");
Database.initDataDir(args);
await Database.connect(false, false, true);
console.log("Deleting all data from aggregate tables");
await R.exec("DELETE FROM stat_minutely");
await R.exec("DELETE FROM stat_hourly");
await R.exec("DELETE FROM stat_daily");
console.log("Resetting the aggregate table state");
await Settings.set("migrateAggregateTableState", "");
await Database.close();
console.log("Done");
};
main();

4172
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -38,8 +38,8 @@
"build-docker-base": "docker buildx build -f docker/debian-base.dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:base2 --target base2 . --push",
"build-docker-base-slim": "docker buildx build -f docker/debian-base.dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:base2-slim --target base2-slim . --push",
"build-docker-builder-go": "docker buildx build -f docker/builder-go.dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:builder-go . --push",
"build-docker-slim": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:2-slim -t louislam/uptime-kuma:$VERSION-slim --target release --build-arg BASE_IMAGE=louislam/uptime-kuma:base2-slim . --push",
"build-docker-full": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:2 -t louislam/uptime-kuma:$VERSION --target release . --push",
"build-docker-slim": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:next-slim -t louislam/uptime-kuma:2-slim -t louislam/uptime-kuma:$VERSION-slim --target release --build-arg BASE_IMAGE=louislam/uptime-kuma:base2-slim . --push",
"build-docker-full": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:next -t louislam/uptime-kuma:2 -t louislam/uptime-kuma:$VERSION --target release . --push",
"build-docker-nightly": "node ./extra/test-docker.js && npm run build && docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:nightly2 --target nightly . --push",
"build-docker-slim-rootless": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:2-slim-rootless -t louislam/uptime-kuma:$VERSION-slim-rootless --target rootless --build-arg BASE_IMAGE=louislam/uptime-kuma:base2-slim . --push",
"build-docker-full-rootless": "node ./extra/env2arg.js docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64,linux/arm/v7 -t louislam/uptime-kuma:2-rootless -t louislam/uptime-kuma:$VERSION-rootless --target rootless . --push",
@ -68,7 +68,8 @@
"sort-contributors": "node extra/sort-contributors.js",
"quick-run-nightly": "docker run --rm --env NODE_ENV=development -p 3001:3001 louislam/uptime-kuma:nightly2",
"start-dev-container": "cd docker && docker-compose -f docker-compose-dev.yml up --force-recreate",
"rebase-pr-to-1.23.X": "node extra/rebase-pr.js 1.23.X"
"rebase-pr-to-1.23.X": "node extra/rebase-pr.js 1.23.X",
"reset-migrate-aggregate-table-state": "node extra/reset-migrate-aggregate-table-state.js"
},
"dependencies": {
"@grpc/grpc-js": "~1.8.22",

View file

@ -6,6 +6,9 @@ const knex = require("knex");
const path = require("path");
const { EmbeddedMariaDB } = require("./embedded-mariadb");
const mysql = require("mysql2/promise");
const { Settings } = require("./settings");
const { UptimeCalculator } = require("./uptime-calculator");
const dayjs = require("dayjs");
/**
* Database & App Data Folder
@ -391,9 +394,23 @@ class Database {
// https://knexjs.org/guide/migrations.html
// https://gist.github.com/NigelEarle/70db130cc040cc2868555b29a0278261
try {
// Disable foreign key check for SQLite
// Known issue of knex: https://github.com/drizzle-team/drizzle-orm/issues/1813
if (Database.dbConfig.type === "sqlite") {
await R.exec("PRAGMA foreign_keys = OFF");
}
await R.knex.migrate.latest({
directory: Database.knexMigrationsPath,
});
// Enable foreign key check for SQLite
if (Database.dbConfig.type === "sqlite") {
await R.exec("PRAGMA foreign_keys = ON");
}
await this.migrateAggregateTable();
} catch (e) {
// Allow missing patch files for downgrade or testing pr.
if (e.message.includes("the following files are missing:")) {
@ -711,6 +728,152 @@ class Database {
}
}
/**
* Migrate the old data in the heartbeat table to the new format (stat_daily, stat_hourly, stat_minutely)
* It should be run once while upgrading V1 to V2
*
* Normally, it should be in transaction, but UptimeCalculator wasn't designed to be in transaction before that.
* I don't want to heavily modify the UptimeCalculator, so it is not in transaction.
* Run `npm run reset-migrate-aggregate-table-state` to reset, in case the migration is interrupted.
* @returns {Promise<void>}
*/
static async migrateAggregateTable() {
log.debug("db", "Enter Migrate Aggregate Table function");
// Add a setting for 2.0.0-dev users to skip this migration
if (process.env.SET_MIGRATE_AGGREGATE_TABLE_TO_TRUE === "1") {
log.warn("db", "SET_MIGRATE_AGGREGATE_TABLE_TO_TRUE is set to 1, skipping aggregate table migration forever (for 2.0.0-dev users)");
await Settings.set("migrateAggregateTableState", "migrated");
}
let migrateState = await Settings.get("migrateAggregateTableState");
// Skip if already migrated
// If it is migrating, it possibly means the migration was interrupted, or the migration is in progress
if (migrateState === "migrated") {
log.debug("db", "Migrated aggregate table already, skip");
return;
} else if (migrateState === "migrating") {
log.warn("db", "Aggregate table migration is already in progress, or it was interrupted");
throw new Error("Aggregate table migration is already in progress");
}
await Settings.set("migrateAggregateTableState", "migrating");
log.info("db", "Migrating Aggregate Table");
log.info("db", "Getting list of unique monitors");
// Get a list of unique monitors from the heartbeat table, using raw sql
let monitors = await R.getAll(`
SELECT DISTINCT monitor_id
FROM heartbeat
ORDER BY monitor_id ASC
`);
// Stop if stat_* tables are not empty
for (let table of [ "stat_minutely", "stat_hourly", "stat_daily" ]) {
let countResult = await R.getRow(`SELECT COUNT(*) AS count FROM ${table}`);
let count = countResult.count;
if (count > 0) {
log.warn("db", `Aggregate table ${table} is not empty, migration will not be started (Maybe you were using 2.0.0-dev?)`);
return;
}
}
let progressPercent = 0;
let part = 100 / monitors.length;
let i = 1;
for (let monitor of monitors) {
// Get a list of unique dates from the heartbeat table, using raw sql
let dates = await R.getAll(`
SELECT DISTINCT DATE(time) AS date
FROM heartbeat
WHERE monitor_id = ?
ORDER BY date ASC
`, [
monitor.monitor_id
]);
for (let date of dates) {
// New Uptime Calculator
let calculator = new UptimeCalculator();
calculator.monitorID = monitor.monitor_id;
calculator.setMigrationMode(true);
// Get all the heartbeats for this monitor and date
let heartbeats = await R.getAll(`
SELECT status, ping, time
FROM heartbeat
WHERE monitor_id = ?
AND DATE(time) = ?
ORDER BY time ASC
`, [ monitor.monitor_id, date.date ]);
if (heartbeats.length > 0) {
log.info("db", `[DON'T STOP] Migrating monitor data ${monitor.monitor_id} - ${date.date} [${progressPercent.toFixed(2)}%][${i}/${monitors.length}]`);
}
for (let heartbeat of heartbeats) {
await calculator.update(heartbeat.status, parseFloat(heartbeat.ping), dayjs(heartbeat.time));
}
progressPercent += (Math.round(part / dates.length * 100) / 100);
// Lazy to fix the floating point issue, it is acceptable since it is just a progress bar
if (progressPercent > 100) {
progressPercent = 100;
}
}
i++;
}
await Database.clearHeartbeatData(true);
await Settings.set("migrateAggregateTableState", "migrated");
if (monitors.length > 0) {
log.info("db", "Aggregate Table Migration Completed");
} else {
log.info("db", "No data to migrate");
}
}
/**
* Remove all non-important heartbeats from heartbeat table, keep last 24-hour or {KEEP_LAST_ROWS} rows for each monitor
* @param {boolean} detailedLog Log detailed information
* @returns {Promise<void>}
*/
static async clearHeartbeatData(detailedLog = false) {
let monitors = await R.getAll("SELECT id FROM monitor");
const sqlHourOffset = Database.sqlHourOffset();
for (let monitor of monitors) {
if (detailedLog) {
log.info("db", "Deleting non-important heartbeats for monitor " + monitor.id);
}
await R.exec(`
DELETE FROM heartbeat
WHERE monitor_id = ?
AND important = 0
AND time < ${sqlHourOffset}
AND id NOT IN (
SELECT id
FROM heartbeat
WHERE monitor_id = ?
ORDER BY time DESC
LIMIT ?
)
`, [
monitor.id,
-24,
monitor.id,
100,
]);
}
}
}
module.exports = Database;

View file

@ -1,21 +1,22 @@
const { R } = require("redbean-node");
const { log } = require("../../src/util");
const { setSetting, setting } = require("../util-server");
const Database = require("../database");
const { Settings } = require("../settings");
const dayjs = require("dayjs");
const DEFAULT_KEEP_PERIOD = 180;
const DEFAULT_KEEP_PERIOD = 365;
/**
* Clears old data from the heartbeat table of the database.
* Clears old data from the heartbeat table and the stat_daily of the database.
* @returns {Promise<void>} A promise that resolves when the data has been cleared.
*/
const clearOldData = async () => {
let period = await setting("keepDataPeriodDays");
await Database.clearHeartbeatData();
let period = await Settings.get("keepDataPeriodDays");
// Set Default Period
if (period == null) {
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
period = DEFAULT_KEEP_PERIOD;
}
@ -25,23 +26,28 @@ const clearOldData = async () => {
parsedPeriod = parseInt(period);
} catch (_) {
log.warn("clearOldData", "Failed to parse setting, resetting to default..");
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
parsedPeriod = DEFAULT_KEEP_PERIOD;
}
if (parsedPeriod < 1) {
log.info("clearOldData", `Data deletion has been disabled as period is less than 1. Period is ${parsedPeriod} days.`);
} else {
log.debug("clearOldData", `Clearing Data older than ${parsedPeriod} days...`);
const sqlHourOffset = Database.sqlHourOffset();
try {
await R.exec(
"DELETE FROM heartbeat WHERE time < " + sqlHourOffset,
[ parsedPeriod * -24 ]
);
// Heartbeat
await R.exec("DELETE FROM heartbeat WHERE time < " + sqlHourOffset, [
parsedPeriod * -24,
]);
let timestamp = dayjs().subtract(parsedPeriod, "day").utc().startOf("day").unix();
// stat_daily
await R.exec("DELETE FROM stat_daily WHERE timestamp < ? ", [
timestamp,
]);
if (Database.dbConfig.type === "sqlite") {
await R.exec("PRAGMA optimize;");
@ -50,6 +56,8 @@ const clearOldData = async () => {
log.error("clearOldData", `Failed to clear old data: ${e.message}`);
}
}
log.debug("clearOldData", "Data cleared.");
};
module.exports = {

View file

@ -383,7 +383,11 @@ class Monitor extends BeanModel {
} else if (this.type === "group") {
const children = await Monitor.getChildren(this.id);
if (children.length > 0) {
if (children.length > 0 && children.filter(child => child.active).length === 0) {
// Set status pending if all children are paused
bean.status = PENDING;
bean.msg = "All Children are paused.";
} else if (children.length > 0) {
bean.status = UP;
bean.msg = "All children up and running";
for (const child of children) {
@ -1468,10 +1472,12 @@ class Monitor extends BeanModel {
* @returns {Promise<boolean>} Is the monitor under maintenance
*/
static async isUnderMaintenance(monitorID) {
const ancestorIDs = await Monitor.getAllAncestorIDs(monitorID);
const allIDs = [ monitorID, ...ancestorIDs ];
const maintenanceIDList = await R.getCol(`
SELECT maintenance_id FROM monitor_maintenance
WHERE monitor_id = ?
`, [ monitorID ]);
WHERE monitor_id IN (${allIDs.map((_) => "?").join(",")})
`, allIDs);
for (const maintenanceID of maintenanceIDList) {
const maintenance = await UptimeKumaServer.getInstance().getMaintenance(maintenanceID);
@ -1480,11 +1486,6 @@ class Monitor extends BeanModel {
}
}
const parent = await Monitor.getParent(monitorID);
if (parent != null) {
return await Monitor.isUnderMaintenance(parent.id);
}
return false;
}
@ -1604,13 +1605,32 @@ class Monitor extends BeanModel {
};
}
/**
* Gets all active monitors
* @returns {Promise<Bean[]>} Active Monitors
*/
static async getAllActiveMonitors() {
// Gets all monitors but only if they and all their ancestors are active
return R.convertToBeans("monitor", await R.getAll(`
WITH RECURSIVE MonitorHierarchy AS (
SELECT * FROM monitor
WHERE parent IS NULL AND active = 1
UNION ALL
SELECT m.* FROM monitor m
INNER JOIN MonitorHierarchy mh ON m.parent = mh.id
WHERE m.active = 1
)
SELECT * FROM MonitorHierarchy;
`));
}
/**
* Gets Parent of the monitor
* @param {number} monitorID ID of monitor to get
* @returns {Promise<LooseObject<any>>} Parent
* @returns {Promise<Bean | null>} Parent
*/
static async getParent(monitorID) {
return await R.getRow(`
const result = await R.getRow(`
SELECT parent.* FROM monitor parent
LEFT JOIN monitor child
ON child.parent = parent.id
@ -1618,20 +1638,25 @@ class Monitor extends BeanModel {
`, [
monitorID,
]);
if (!result) {
return null;
}
return R.convertToBean("monitor", result);
}
/**
* Gets all Children of the monitor
* @param {number} monitorID ID of monitor to get
* @returns {Promise<LooseObject<any>>} Children
* @returns {Promise<Bean[]>} Children
*/
static async getChildren(monitorID) {
return await R.getAll(`
return R.convertToBeans("monitor", await R.getAll(`
SELECT * FROM monitor
WHERE parent = ?
`, [
monitorID,
]);
]));
}
/**
@ -1657,25 +1682,64 @@ class Monitor extends BeanModel {
}
/**
* Gets recursive all child ids
* Gets recursive all ancestor ids
* @param {number} monitorID ID of the monitor to get
* @returns {Promise<Array>} IDs of all children
* @returns {Promise<number[]>} IDs of all ancestors
*/
static async getAllChildrenIDs(monitorID) {
const childs = await Monitor.getChildren(monitorID);
if (childs === null) {
return [];
static async getAllAncestorIDs(monitorID) {
// Gets all ancestor monitor ids recursive
return await R.getCol(`
WITH RECURSIVE Ancestors AS (
SELECT parent FROM monitor
WHERE id = ?
UNION ALL
SELECT m.parent FROM monitor m
JOIN Ancestors a ON m.id = a.parent
)
SELECT parent AS ancestor_id FROM Ancestors
WHERE parent IS NOT NULL;
`, [
monitorID,
]);
}
let childrenIDs = [];
for (const child of childs) {
childrenIDs.push(child.id);
childrenIDs = childrenIDs.concat(await Monitor.getAllChildrenIDs(child.id));
/**
* Gets recursive all children ids
* @param {number} monitorID ID of the monitor to get
* @param {boolean} onlyActive Return only monitors which are active (including all ancestors)
* @returns {Promise<number[]>} IDs of all children
*/
static async getAllChildrenIDs(monitorID, onlyActive = false) {
if (onlyActive) {
// Gets all children monitor ids recursive but only if they and all their ancestors are active
return await R.getCol(`
WITH RECURSIVE MonitorHierarchy(id, active_chain) AS (
SELECT id, active FROM monitor
WHERE id = ?
UNION ALL
SELECT m.id, m.active * mh.active_chain FROM monitor m
INNER JOIN MonitorHierarchy mh ON m.parent = mh.id
WHERE mh.active_chain = 1
)
SELECT id FROM MonitorHierarchy
WHERE id != ? AND active_chain = 1;
`, [
monitorID,
monitorID
]);
}
return childrenIDs;
// Gets all children monitor ids recursive
return await R.getCol(`
WITH RECURSIVE MonitorHierarchy(id) AS (
SELECT id FROM monitor WHERE id = ?
UNION ALL
SELECT m.id FROM monitor m INNER JOIN MonitorHierarchy mh ON m.parent = mh.id
)
SELECT id FROM MonitorHierarchy WHERE id != ?;
`, [
monitorID,
monitorID
]);
}
/**
@ -1695,14 +1759,32 @@ class Monitor extends BeanModel {
* @returns {Promise<boolean>} Is the parent monitor active?
*/
static async isParentActive(monitorID) {
const parent = await Monitor.getParent(monitorID);
// Checks recursive if the parent and all its ancestors are active
const result = await R.getRow(`
WITH RECURSIVE MonitorHierarchy AS (
SELECT parent FROM monitor
WHERE id = ?
UNION ALL
SELECT m.parent FROM monitor m
JOIN MonitorHierarchy mh ON m.id = mh.parent
)
SELECT
CASE
WHEN (SELECT parent FROM monitor WHERE id = ?) IS NULL THEN 1
ELSE
CASE
WHEN COUNT(m.id) = SUM(m.active) THEN 1
ELSE 0
END
END AS all_active
FROM MonitorHierarchy mh
LEFT JOIN monitor m ON mh.parent = m.id;
`, [
monitorID,
monitorID
]);
if (parent === null) {
return true;
}
const parentActive = await Monitor.isParentActive(parent.id);
return parent.active && parentActive;
return result.all_active === 1;
}
/**

View file

@ -729,7 +729,7 @@ let needSetup = false;
await updateMonitorNotification(bean.id, notificationIDList);
await server.sendUpdateMonitorIntoList(socket, bean.id);
await server.sendUpdateMonitorsIntoList(socket, bean.id);
if (monitor.active !== false) {
await startMonitor(socket.userID, bean.id);
@ -889,7 +889,7 @@ let needSetup = false;
await restartMonitor(socket.userID, bean.id);
}
await server.sendUpdateMonitorIntoList(socket, bean.id);
await server.sendUpdateMonitorsIntoList(socket, bean.id);
callback({
ok: true,
@ -990,7 +990,9 @@ let needSetup = false;
try {
checkLogin(socket);
await startMonitor(socket.userID, monitorID);
await server.sendUpdateMonitorIntoList(socket, monitorID);
const childrenIDs = await Monitor.getAllChildrenIDs(monitorID);
await server.sendUpdateMonitorsIntoList(socket, [ monitorID, ...childrenIDs ]);
callback({
ok: true,
@ -1010,7 +1012,9 @@ let needSetup = false;
try {
checkLogin(socket);
await pauseMonitor(socket.userID, monitorID);
await server.sendUpdateMonitorIntoList(socket, monitorID);
const childrenIDs = await Monitor.getAllChildrenIDs(monitorID);
await server.sendUpdateMonitorsIntoList(socket, [ monitorID, ...childrenIDs ]);
callback({
ok: true,
@ -1604,18 +1608,20 @@ let needSetup = false;
await server.start();
server.httpServer.listen(port, hostname, () => {
server.httpServer.listen(port, hostname, async () => {
if (hostname) {
log.info("server", `Listening on ${hostname}:${port}`);
} else {
log.info("server", `Listening on ${port}`);
}
startMonitors();
await startMonitors();
// Put this here. Start background jobs after the db and server is ready to prevent clear up during db migration.
await initBackgroundJobs();
checkVersion.startInterval();
});
await initBackgroundJobs();
// Start cloudflared at the end if configured
await cloudflaredAutoStart(cloudflaredToken);
@ -1753,16 +1759,19 @@ async function startMonitor(userID, monitorID) {
userID,
]);
let monitor = await R.findOne("monitor", " id = ? ", [
monitorID,
]);
const childrenIDs = await Monitor.getAllChildrenIDs(monitorID, true);
const monitorIDs = [ monitorID, ...childrenIDs ];
let monitors = await R.find("monitor", ` id IN (${monitorIDs.map((_) => "?").join(",")})`, monitorIDs);
await Promise.all(monitors.map(async (monitor) => {
if (monitor.id in server.monitorList) {
await server.monitorList[monitor.id].stop();
}
server.monitorList[monitor.id] = monitor;
await monitor.start(io);
}));
}
/**
@ -1791,10 +1800,16 @@ async function pauseMonitor(userID, monitorID) {
userID,
]);
if (monitorID in server.monitorList) {
await server.monitorList[monitorID].stop();
server.monitorList[monitorID].active = 0;
const childrenIDs = await Monitor.getAllChildrenIDs(monitorID);
const monitorIDs = [ monitorID, ...childrenIDs ];
await Promise.all(monitorIDs.map(async (currentMonitorID) => {
if (currentMonitorID in server.monitorList) {
await server.monitorList[currentMonitorID].stop();
}
}));
server.monitorList[monitorID].active = 0;
}
/**
@ -1802,14 +1817,18 @@ async function pauseMonitor(userID, monitorID) {
* @returns {Promise<void>}
*/
async function startMonitors() {
let list = await R.find("monitor", " active = 1 ");
let list = await Monitor.getAllActiveMonitors();
for (let monitor of list) {
server.monitorList[monitor.id] = monitor;
}
for (let monitor of list) {
try {
await monitor.start(io);
} catch (e) {
log.error("monitor", e);
}
// Give some delays, so all monitors won't make request at the same moment when just start the server.
await sleep(getRandomInt(300, 1000));
}

View file

@ -12,7 +12,6 @@ class UptimeCalculator {
* @private
* @type {{string:UptimeCalculator}}
*/
static list = {};
/**
@ -55,6 +54,15 @@ class UptimeCalculator {
lastHourlyStatBean = null;
lastMinutelyStatBean = null;
/**
* For migration purposes.
* @type {boolean}
*/
migrationMode = false;
statMinutelyKeepHour = 24;
statHourlyKeepDay = 30;
/**
* Get the uptime calculator for a monitor
* Initializes and returns the monitor if it does not exist
@ -189,16 +197,19 @@ class UptimeCalculator {
/**
* @param {number} status status
* @param {number} ping Ping
* @param {dayjs.Dayjs} date Date (Only for migration)
* @returns {dayjs.Dayjs} date
* @throws {Error} Invalid status
*/
async update(status, ping = 0) {
let date = this.getCurrentDate();
async update(status, ping = 0, date) {
if (!date) {
date = this.getCurrentDate();
}
let flatStatus = this.flatStatus(status);
if (flatStatus === DOWN && ping > 0) {
log.warn("uptime-calc", "The ping is not effective when the status is DOWN");
log.debug("uptime-calc", "The ping is not effective when the status is DOWN");
}
let divisionKey = this.getMinutelyKey(date);
@ -297,6 +308,11 @@ class UptimeCalculator {
}
await R.store(dailyStatBean);
let currentDate = this.getCurrentDate();
// For migration mode, we don't need to store old hourly and minutely data, but we need 30-day's hourly data
// Run anyway for non-migration mode
if (!this.migrationMode || date.isAfter(currentDate.subtract(this.statHourlyKeepDay, "day"))) {
let hourlyStatBean = await this.getHourlyStatBean(hourlyKey);
hourlyStatBean.up = hourlyData.up;
hourlyStatBean.down = hourlyData.down;
@ -311,7 +327,11 @@ class UptimeCalculator {
}
}
await R.store(hourlyStatBean);
}
// For migration mode, we don't need to store old hourly and minutely data, but we need 24-hour's minutely data
// Run anyway for non-migration mode
if (!this.migrationMode || date.isAfter(currentDate.subtract(this.statMinutelyKeepHour, "hour"))) {
let minutelyStatBean = await this.getMinutelyStatBean(divisionKey);
minutelyStatBean.up = minutelyData.up;
minutelyStatBean.down = minutelyData.down;
@ -326,18 +346,23 @@ class UptimeCalculator {
}
}
await R.store(minutelyStatBean);
}
// No need to remove old data in migration mode
if (!this.migrationMode) {
// Remove the old data
// TODO: Improvement: Convert it to a job?
log.debug("uptime-calc", "Remove old data");
await R.exec("DELETE FROM stat_minutely WHERE monitor_id = ? AND timestamp < ?", [
this.monitorID,
this.getMinutelyKey(date.subtract(24, "hour")),
this.getMinutelyKey(currentDate.subtract(this.statMinutelyKeepHour, "hour")),
]);
await R.exec("DELETE FROM stat_hourly WHERE monitor_id = ? AND timestamp < ?", [
this.monitorID,
this.getHourlyKey(date.subtract(30, "day")),
this.getHourlyKey(currentDate.subtract(this.statHourlyKeepDay, "day")),
]);
}
return date;
}
@ -812,6 +837,14 @@ class UptimeCalculator {
return dayjs.utc();
}
/**
* For migration purposes.
* @param {boolean} value Migration mode on/off
* @returns {void}
*/
setMigrationMode(value) {
this.migrationMode = value;
}
}
class UptimeDataResult {

View file

@ -209,12 +209,16 @@ class UptimeKumaServer {
/**
* Update Monitor into list
* @param {Socket} socket Socket to send list on
* @param {number} monitorID update or deleted monitor id
* @param {number | number[]} monitorIDs update or deleted monitor ids
* @returns {Promise<void>}
*/
async sendUpdateMonitorIntoList(socket, monitorID) {
let list = await this.getMonitorJSONList(socket.userID, monitorID);
this.io.to(socket.userID).emit("updateMonitorIntoList", list);
async sendUpdateMonitorsIntoList(socket, monitorIDs) {
if (!Array.isArray(monitorIDs)) {
monitorIDs = [ monitorIDs ];
}
let list = await this.getMonitorJSONList(socket.userID, monitorIDs);
this.io.to(socket.userID).emit("updateMonitorsIntoList", list);
}
/**
@ -230,19 +234,19 @@ class UptimeKumaServer {
/**
* Get a list of monitors for the given user.
* @param {string} userID - The ID of the user to get monitors for.
* @param {number} monitorID - The ID of monitor for.
* @param {number[]} monitorIDs - The IDs of monitors for.
* @returns {Promise<object>} A promise that resolves to an object with monitor IDs as keys and monitor objects as values.
*
* Generated by Trelent
*/
async getMonitorJSONList(userID, monitorID = null) {
async getMonitorJSONList(userID, monitorIDs = null) {
let query = " user_id = ? ";
let queryParams = [ userID ];
if (monitorID) {
query += "AND id = ? ";
queryParams.push(monitorID);
if (monitorIDs) {
query += `AND id IN (${monitorIDs.map((_) => "?").join(",")}) `;
queryParams.push(...monitorIDs);
}
let monitorList = await R.find("monitor", query + "ORDER BY weight DESC, name", queryParams);

View file

@ -145,7 +145,7 @@ export default {
this.monitorList = data;
});
socket.on("updateMonitorIntoList", (data) => {
socket.on("updateMonitorsIntoList", (data) => {
this.assignMonitorUrlParser(data);
Object.entries(data).forEach(([ monitorID, updatedMonitor ]) => {
this.monitorList[monitorID] = updatedMonitor;