Compare commits

...

29 commits

Author SHA1 Message Date
Louis Lam
338c6308ef
Merge 5e55215c9c into d7ffa33950 2024-10-18 00:25:35 +00:00
Louis Lam
5e55215c9c wip 2024-10-16 05:12:06 +08:00
Louis Lam
93cc21271f wip 2024-10-15 00:40:46 +08:00
Louis Lam
8a4e295882 Merge branch 'master' into 2.0-last-part 2024-10-13 14:34:11 +08:00
Louis Lam
fe91ffcc9d wip 2024-10-13 00:51:55 +08:00
Louis Lam
4632030a5e wip 2024-10-11 18:06:59 +08:00
Louis Lam
776f4f2d5f wip 2024-10-11 17:10:29 +08:00
Louis Lam
7562212483 Merge branch 'master' into 2.0-last-part 2024-10-11 16:53:16 +08:00
Louis Lam
c86b12d5d2 Fix merging issue 2024-10-09 13:16:28 +08:00
Louis Lam
19a9735234 Fix merging issue 2024-10-09 13:15:29 +08:00
Louis Lam
0f646e634e wip 2024-10-09 13:12:41 +08:00
Louis Lam
03e507a4e1 wip 2024-10-09 07:46:41 +08:00
Louis Lam
ed5963deb7 Merge branch 'master' into 2.0-last-part
# Conflicts:
#	server/database.js
#	server/jobs/clear-old-data.js
2024-10-09 07:46:12 +08:00
Louis Lam
9ff9a9edcc Merge branch 'master' into 2.0-last-part 2024-10-09 07:19:25 +08:00
Louis Lam
d7c3c40d74 wip 2024-10-09 07:19:05 +08:00
Louis Lam
344fd52501 Avoid Uptime Kuma getting stop if one monitor is gone wrong 2024-10-09 07:18:55 +08:00
Louis Lam
6437b9afab Revert apicache changes as the debug log is too crazy 2024-10-09 07:08:05 +08:00
Louis Lam
da8da0bf59 wip 2024-10-08 18:47:56 +08:00
Louis Lam
6be297fd46 Merge branch 'master' into 2.0-last-part 2024-10-07 19:18:59 +08:00
Louis Lam
31ce34da77 wip 2024-10-07 18:56:07 +08:00
Louis Lam
7f1042976b Merge branch 'master' into 2.0-last-part 2024-10-07 13:20:32 +08:00
Louis Lam
51892c789a Merge branch 'master' into 2.0-last-part 2024-09-29 23:26:27 +08:00
Louis Lam
67ad0f79b3 wip 2024-09-28 01:22:45 +08:00
Louis Lam
7046a2e0f6 Merge branch 'master' into 2.0-last-part
# Conflicts:
#	server/jobs/clear-old-data.js
2024-09-27 21:45:49 +08:00
Louis Lam
59e7607e1a wip 2024-09-27 21:42:20 +08:00
Louis Lam
0f3c727aa4 wip and fix sqlite migration because of foreign_keys 2024-09-22 18:39:46 +08:00
Louis Lam
696d902983 Merge branch 'master' into 2.0-last-part 2024-09-22 16:04:17 +08:00
Louis Lam
124effb552 wip 2024-09-22 16:01:45 +08:00
Louis Lam
2dfa6886b4 Preparing 2024-09-01 17:19:18 +08:00
6 changed files with 256 additions and 44 deletions

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();

View file

@ -68,7 +68,8 @@
"sort-contributors": "node extra/sort-contributors.js", "sort-contributors": "node extra/sort-contributors.js",
"quick-run-nightly": "docker run --rm --env NODE_ENV=development -p 3001:3001 louislam/uptime-kuma:nightly2", "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", "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": { "dependencies": {
"@grpc/grpc-js": "~1.8.22", "@grpc/grpc-js": "~1.8.22",

View file

@ -6,6 +6,9 @@ const knex = require("knex");
const path = require("path"); const path = require("path");
const { EmbeddedMariaDB } = require("./embedded-mariadb"); const { EmbeddedMariaDB } = require("./embedded-mariadb");
const mysql = require("mysql2/promise"); const mysql = require("mysql2/promise");
const { Settings } = require("./settings");
const { UptimeCalculator } = require("./uptime-calculator");
const dayjs = require("dayjs");
/** /**
* Database & App Data Folder * Database & App Data Folder
@ -391,9 +394,23 @@ class Database {
// https://knexjs.org/guide/migrations.html // https://knexjs.org/guide/migrations.html
// https://gist.github.com/NigelEarle/70db130cc040cc2868555b29a0278261 // https://gist.github.com/NigelEarle/70db130cc040cc2868555b29a0278261
try { 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({ await R.knex.migrate.latest({
directory: Database.knexMigrationsPath, 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) { } catch (e) {
// Allow missing patch files for downgrade or testing pr. // Allow missing patch files for downgrade or testing pr.
if (e.message.includes("the following files are missing:")) { if (e.message.includes("the following files are missing:")) {
@ -711,6 +728,119 @@ 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++;
}
// TODO: Remove all non-important heartbeats from heartbeat table
log.info("db", "[DON'T STOP] Deleting all data from heartbeat table");
await Settings.set("migrateAggregateTableState", "migrated");
if (monitors.length > 0) {
log.info("db", "Aggregate Table Migration Completed");
} else {
log.info("db", "No data to migrate");
}
}
} }
module.exports = Database; module.exports = Database;

View file

@ -2,6 +2,7 @@ const { R } = require("redbean-node");
const { log } = require("../../src/util"); const { log } = require("../../src/util");
const { setSetting, setting } = require("../util-server"); const { setSetting, setting } = require("../util-server");
const Database = require("../database"); const Database = require("../database");
const { Settings } = require("../settings");
const DEFAULT_KEEP_PERIOD = 180; const DEFAULT_KEEP_PERIOD = 180;
@ -11,11 +12,28 @@ const DEFAULT_KEEP_PERIOD = 180;
*/ */
const clearOldData = async () => { const clearOldData = async () => {
// TODO: Temporary disable for testing
return;
/*
* TODO:
* Since we have aggregated table now, we don't need so much data in heartbeat table.
* But we still need to keep the important rows, because they contain the message.
*
* In the heartbeat table:
* - important rows: keep according to the setting (keepDataPeriodDays) (default 180 days)
* - not important rows: keep 2 days
*
* stat_* tables:
* - keep according to the setting (keepDataPeriodDays) (default 180 days)
*/
let period = await setting("keepDataPeriodDays"); let period = await setting("keepDataPeriodDays");
// Set Default Period // Set Default Period
if (period == null) { if (period == null) {
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general"); await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
period = DEFAULT_KEEP_PERIOD; period = DEFAULT_KEEP_PERIOD;
} }

View file

@ -1599,18 +1599,20 @@ let needSetup = false;
await server.start(); await server.start();
server.httpServer.listen(port, hostname, () => { server.httpServer.listen(port, hostname, async () => {
if (hostname) { if (hostname) {
log.info("server", `Listening on ${hostname}:${port}`); log.info("server", `Listening on ${hostname}:${port}`);
} else { } else {
log.info("server", `Listening on ${port}`); 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(); checkVersion.startInterval();
}); });
await initBackgroundJobs();
// Start cloudflared at the end if configured // Start cloudflared at the end if configured
await cloudflaredAutoStart(cloudflaredToken); await cloudflaredAutoStart(cloudflaredToken);
@ -1804,7 +1806,11 @@ async function startMonitors() {
} }
for (let monitor of list) { for (let monitor of list) {
await monitor.start(io); 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. // Give some delays, so all monitors won't make request at the same moment when just start the server.
await sleep(getRandomInt(300, 1000)); await sleep(getRandomInt(300, 1000));
} }

View file

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