mirror of
https://github.com/louislam/uptime-kuma.git
synced 2025-09-14 07:26:59 +08:00
Compare commits
16 Commits
testcontai
...
escaped-de
Author | SHA1 | Date | |
---|---|---|---|
|
ff197839b3 | ||
|
c90aacc62c | ||
|
eca90a2b00 | ||
|
4829ad8c5d | ||
|
59e70cb763 | ||
|
6476e58907 | ||
|
e773e454e9 | ||
|
d0067a0a12 | ||
|
f791d4a9bf | ||
|
a5faa4b225 | ||
|
da168fc220 | ||
|
1cf88f4fea | ||
|
0f6cb15561 | ||
|
14199dc2cb | ||
|
e8e83808d3 | ||
|
e40ce59e66 |
8
.github/workflows/auto-test.yml
vendored
8
.github/workflows/auto-test.yml
vendored
@@ -15,14 +15,14 @@ on:
|
||||
|
||||
jobs:
|
||||
auto-test:
|
||||
needs: [ check-linters, e2e-test ]
|
||||
needs: [ check-linters ]
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 15
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest, ARM64]
|
||||
node: [ 18, 20.5 ]
|
||||
node: [ 18, 20 ]
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
|
||||
# As a lot of dev dependencies are not supported on ARMv7, we have to test it separately and just test if `npm ci --production` works
|
||||
armv7-simple-test:
|
||||
needs: [ check-linters ]
|
||||
needs: [ ]
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.repository == 'louislam/uptime-kuma' }}
|
||||
@@ -77,7 +77,7 @@ jobs:
|
||||
- run: npm run lint:prod
|
||||
|
||||
e2e-test:
|
||||
needs: [ check-linters ]
|
||||
needs: [ ]
|
||||
runs-on: ARM64
|
||||
steps:
|
||||
- run: git config --global core.autocrlf false # Mainly for Windows
|
||||
|
@@ -16,9 +16,7 @@ export default defineConfig({
|
||||
},
|
||||
define: {
|
||||
"FRONTEND_VERSION": JSON.stringify(process.env.npm_package_version),
|
||||
"DEVCONTAINER": JSON.stringify(process.env.DEVCONTAINER),
|
||||
"GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN": JSON.stringify(process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN),
|
||||
"CODESPACE_NAME": JSON.stringify(process.env.CODESPACE_NAME),
|
||||
"process.env": {},
|
||||
},
|
||||
plugins: [
|
||||
vue(),
|
||||
|
@@ -4,7 +4,6 @@ const tar = require("tar");
|
||||
|
||||
const packageJSON = require("../package.json");
|
||||
const fs = require("fs");
|
||||
const rmSync = require("./fs-rmSync.js");
|
||||
const version = packageJSON.version;
|
||||
|
||||
const filename = "dist.tar.gz";
|
||||
@@ -29,8 +28,9 @@ function download(url) {
|
||||
if (fs.existsSync("./dist")) {
|
||||
|
||||
if (fs.existsSync("./dist-backup")) {
|
||||
rmSync("./dist-backup", {
|
||||
recursive: true
|
||||
fs.rmSync("./dist-backup", {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -43,8 +43,9 @@ function download(url) {
|
||||
|
||||
tarStream.on("close", () => {
|
||||
if (fs.existsSync("./dist-backup")) {
|
||||
rmSync("./dist-backup", {
|
||||
recursive: true
|
||||
fs.rmSync("./dist-backup", {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
console.log("Done");
|
||||
|
@@ -1,23 +0,0 @@
|
||||
const fs = require("fs");
|
||||
/**
|
||||
* Detect if `fs.rmSync` is available
|
||||
* to avoid the runtime deprecation warning triggered for using `fs.rmdirSync` with `{ recursive: true }` in Node.js v16,
|
||||
* or the `recursive` property removing completely in the future Node.js version.
|
||||
* See the link below.
|
||||
* @todo Once we drop the support for Node.js v14 (or at least versions before v14.14.0), we can safely replace this function with `fs.rmSync`, since `fs.rmSync` was add in Node.js v14.14.0 and currently we supports all the Node.js v14 versions that include the versions before the v14.14.0, and this function have almost the same signature with `fs.rmSync`.
|
||||
* @link https://nodejs.org/docs/latest-v16.x/api/deprecations.html#dep0147-fsrmdirpath--recursive-true- the deprecation information of `fs.rmdirSync`
|
||||
* @link https://nodejs.org/docs/latest-v16.x/api/fs.html#fsrmsyncpath-options the document of `fs.rmSync`
|
||||
* @param {fs.PathLike} path Valid types for path values in "fs".
|
||||
* @param {fs.RmDirOptions} options options for `fs.rmdirSync`, if `fs.rmSync` is available and property `recursive` is true, it will automatically have property `force` with value `true`.
|
||||
* @returns {void}
|
||||
*/
|
||||
const rmSync = (path, options) => {
|
||||
if (typeof fs.rmSync === "function") {
|
||||
if (options.recursive) {
|
||||
options.force = true;
|
||||
}
|
||||
return fs.rmSync(path, options);
|
||||
}
|
||||
return fs.rmdirSync(path, options);
|
||||
};
|
||||
module.exports = rmSync;
|
@@ -2,7 +2,6 @@
|
||||
|
||||
import fs from "fs";
|
||||
import util from "util";
|
||||
import rmSync from "../fs-rmSync.js";
|
||||
|
||||
/**
|
||||
* Copy across the required language files
|
||||
@@ -16,7 +15,10 @@ import rmSync from "../fs-rmSync.js";
|
||||
*/
|
||||
function copyFiles(langCode, baseLang) {
|
||||
if (fs.existsSync("./languages")) {
|
||||
rmSync("./languages", { recursive: true });
|
||||
fs.rmSync("./languages", {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
fs.mkdirSync("./languages");
|
||||
|
||||
@@ -93,6 +95,9 @@ console.log("Updating: " + langCode);
|
||||
|
||||
copyFiles(langCode, baseLangCode);
|
||||
await updateLanguage(langCode, baseLangCode);
|
||||
rmSync("./languages", { recursive: true });
|
||||
fs.rmSync("./languages", {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
|
||||
console.log("Done. Fixing formatting by ESLint...");
|
||||
|
988
package-lock.json
generated
988
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -68,8 +68,7 @@
|
||||
"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",
|
||||
"start-server-node14-win": "private\\node14\\node.exe server/server.js"
|
||||
"rebase-pr-to-1.23.X": "node extra/rebase-pr.js 1.23.X"
|
||||
},
|
||||
"dependencies": {
|
||||
"@grpc/grpc-js": "~1.8.22",
|
||||
@@ -155,7 +154,6 @@
|
||||
"@fortawesome/vue-fontawesome": "~3.0.0-5",
|
||||
"@playwright/test": "~1.39.0",
|
||||
"@popperjs/core": "~2.10.2",
|
||||
"@testcontainers/hivemq": "^10.13.1",
|
||||
"@types/bootstrap": "~5.1.9",
|
||||
"@types/node": "^20.8.6",
|
||||
"@typescript-eslint/eslint-plugin": "^6.7.5",
|
||||
@@ -191,7 +189,6 @@
|
||||
"stylelint-config-standard": "~25.0.0",
|
||||
"terser": "~5.15.0",
|
||||
"test": "~3.3.0",
|
||||
"testcontainers": "^10.13.1",
|
||||
"typescript": "~4.4.4",
|
||||
"v-pagination-3": "~0.1.7",
|
||||
"vite": "~5.2.8",
|
||||
|
@@ -1,6 +1,7 @@
|
||||
const basicAuth = require("express-basic-auth");
|
||||
const passwordHash = require("./password-hash");
|
||||
const { R } = require("redbean-node");
|
||||
const { setting } = require("./util-server");
|
||||
const { log } = require("../src/util");
|
||||
const { loginRateLimiter, apiRateLimiter } = require("./rate-limiter");
|
||||
const { Settings } = require("./settings");
|
||||
@@ -138,7 +139,7 @@ exports.basicAuth = async function (req, res, next) {
|
||||
challenge: true,
|
||||
});
|
||||
|
||||
const disabledAuth = await Settings.get("disableAuth");
|
||||
const disabledAuth = await setting("disableAuth");
|
||||
|
||||
if (!disabledAuth) {
|
||||
middleware(req, res, next);
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const { setSetting, setting } = require("./util-server");
|
||||
const axios = require("axios");
|
||||
const compareVersions = require("compare-versions");
|
||||
const { log } = require("../src/util");
|
||||
const { Settings } = require("./settings");
|
||||
|
||||
exports.version = require("../package.json").version;
|
||||
exports.latestVersion = null;
|
||||
@@ -14,7 +14,7 @@ let interval;
|
||||
|
||||
exports.startInterval = () => {
|
||||
let check = async () => {
|
||||
if (await Settings.get("checkUpdate") === false) {
|
||||
if (await setting("checkUpdate") === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ exports.startInterval = () => {
|
||||
res.data.slow = "1000.0.0";
|
||||
}
|
||||
|
||||
let checkBeta = await Settings.get("checkBeta");
|
||||
let checkBeta = await setting("checkBeta");
|
||||
|
||||
if (checkBeta && res.data.beta) {
|
||||
if (compareVersions.compare(res.data.beta, res.data.slow, ">")) {
|
||||
@@ -57,7 +57,7 @@ exports.startInterval = () => {
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
exports.enableCheckUpdate = async (value) => {
|
||||
await Settings.set("checkUpdate", value);
|
||||
await setSetting("checkUpdate", value);
|
||||
|
||||
clearInterval(interval);
|
||||
|
||||
|
@@ -6,8 +6,8 @@ const { R } = require("redbean-node");
|
||||
const { UptimeKumaServer } = require("./uptime-kuma-server");
|
||||
const server = UptimeKumaServer.getInstance();
|
||||
const io = server.io;
|
||||
const { setting } = require("./util-server");
|
||||
const checkVersion = require("./check-version");
|
||||
const { Settings } = require("./settings");
|
||||
const Database = require("./database");
|
||||
|
||||
/**
|
||||
@@ -158,8 +158,8 @@ async function sendInfo(socket, hideVersion = false) {
|
||||
version,
|
||||
latestVersion,
|
||||
isContainer,
|
||||
primaryBaseURL: await Settings.get("primaryBaseURL"),
|
||||
dbType,
|
||||
primaryBaseURL: await setting("primaryBaseURL"),
|
||||
serverTimezone: await server.getTimezone(),
|
||||
serverTimezoneOffset: server.getTimezoneOffset(),
|
||||
});
|
||||
|
@@ -1,11 +1,11 @@
|
||||
const fs = require("fs");
|
||||
const { R } = require("redbean-node");
|
||||
const { setSetting, setting } = require("./util-server");
|
||||
const { log, sleep } = require("../src/util");
|
||||
const knex = require("knex");
|
||||
const path = require("path");
|
||||
const { EmbeddedMariaDB } = require("./embedded-mariadb");
|
||||
const mysql = require("mysql2/promise");
|
||||
const { Settings } = require("./settings");
|
||||
|
||||
/**
|
||||
* Database & App Data Folder
|
||||
@@ -420,7 +420,7 @@ class Database {
|
||||
* @deprecated
|
||||
*/
|
||||
static async patchSqlite() {
|
||||
let version = parseInt(await Settings.get("database_version"));
|
||||
let version = parseInt(await setting("database_version"));
|
||||
|
||||
if (! version) {
|
||||
version = 0;
|
||||
@@ -445,7 +445,7 @@ class Database {
|
||||
log.info("db", `Patching ${sqlFile}`);
|
||||
await Database.importSQLFile(sqlFile);
|
||||
log.info("db", `Patched ${sqlFile}`);
|
||||
await Settings.set("database_version", i);
|
||||
await setSetting("database_version", i);
|
||||
}
|
||||
} catch (ex) {
|
||||
await Database.close();
|
||||
@@ -471,7 +471,7 @@ class Database {
|
||||
*/
|
||||
static async patchSqlite2() {
|
||||
log.debug("db", "Database Patch 2.0 Process");
|
||||
let databasePatchedFiles = await Settings.get("databasePatchedFiles");
|
||||
let databasePatchedFiles = await setting("databasePatchedFiles");
|
||||
|
||||
if (! databasePatchedFiles) {
|
||||
databasePatchedFiles = {};
|
||||
@@ -499,7 +499,7 @@ class Database {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
await Settings.set("databasePatchedFiles", databasePatchedFiles);
|
||||
await setSetting("databasePatchedFiles", databasePatchedFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -512,27 +512,27 @@ class Database {
|
||||
// Fix 1.13.0 empty slug bug
|
||||
await R.exec("UPDATE status_page SET slug = 'empty-slug-recover' WHERE TRIM(slug) = ''");
|
||||
|
||||
let title = await Settings.get("title");
|
||||
let title = await setting("title");
|
||||
|
||||
if (title) {
|
||||
log.info("database", "Migrating Status Page");
|
||||
console.log("Migrating Status Page");
|
||||
|
||||
let statusPageCheck = await R.findOne("status_page", " slug = 'default' ");
|
||||
|
||||
if (statusPageCheck !== null) {
|
||||
log.info("database", "Migrating Status Page - Skip, default slug record is already existing");
|
||||
console.log("Migrating Status Page - Skip, default slug record is already existing");
|
||||
return;
|
||||
}
|
||||
|
||||
let statusPage = R.dispense("status_page");
|
||||
statusPage.slug = "default";
|
||||
statusPage.title = title;
|
||||
statusPage.description = await Settings.get("description");
|
||||
statusPage.icon = await Settings.get("icon");
|
||||
statusPage.theme = await Settings.get("statusPageTheme");
|
||||
statusPage.published = !!await Settings.get("statusPagePublished");
|
||||
statusPage.search_engine_index = !!await Settings.get("searchEngineIndex");
|
||||
statusPage.show_tags = !!await Settings.get("statusPageTags");
|
||||
statusPage.description = await setting("description");
|
||||
statusPage.icon = await setting("icon");
|
||||
statusPage.theme = await setting("statusPageTheme");
|
||||
statusPage.published = !!await setting("statusPagePublished");
|
||||
statusPage.search_engine_index = !!await setting("searchEngineIndex");
|
||||
statusPage.show_tags = !!await setting("statusPageTags");
|
||||
statusPage.password = null;
|
||||
|
||||
if (!statusPage.title) {
|
||||
@@ -560,13 +560,13 @@ class Database {
|
||||
await R.exec("DELETE FROM setting WHERE type = 'statusPage'");
|
||||
|
||||
// Migrate Entry Page if it is status page
|
||||
let entryPage = await Settings.get("entryPage");
|
||||
let entryPage = await setting("entryPage");
|
||||
|
||||
if (entryPage === "statusPage") {
|
||||
await Settings.set("entryPage", "statusPage-default", "general");
|
||||
await setSetting("entryPage", "statusPage-default", "general");
|
||||
}
|
||||
|
||||
log.info("database", "Migrating Status Page - Done");
|
||||
console.log("Migrating Status Page - Done");
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -1,7 +1,7 @@
|
||||
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 DEFAULT_KEEP_PERIOD = 180;
|
||||
|
||||
@@ -11,11 +11,11 @@ const DEFAULT_KEEP_PERIOD = 180;
|
||||
*/
|
||||
|
||||
const clearOldData = async () => {
|
||||
let period = await Settings.get("keepDataPeriodDays");
|
||||
let period = await setting("keepDataPeriodDays");
|
||||
|
||||
// Set Default Period
|
||||
if (period == null) {
|
||||
await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
|
||||
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
|
||||
period = DEFAULT_KEEP_PERIOD;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ const clearOldData = async () => {
|
||||
parsedPeriod = parseInt(period);
|
||||
} catch (_) {
|
||||
log.warn("clearOldData", "Failed to parse setting, resetting to default..");
|
||||
await Settings.set("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
|
||||
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
|
||||
parsedPeriod = DEFAULT_KEEP_PERIOD;
|
||||
}
|
||||
|
||||
|
@@ -4,7 +4,7 @@ const { Prometheus } = require("../prometheus");
|
||||
const { log, UP, DOWN, PENDING, MAINTENANCE, flipStatus, MAX_INTERVAL_SECOND, MIN_INTERVAL_SECOND,
|
||||
SQL_DATETIME_FORMAT, evaluateJsonQuery
|
||||
} = require("../../src/util");
|
||||
const { tcping, ping, checkCertificate, checkStatusCode, getTotalClientInRoom, mssqlQuery, postgresQuery, mysqlQuery, httpNtlm, radius, grpcQuery,
|
||||
const { tcping, ping, checkCertificate, checkStatusCode, getTotalClientInRoom, setting, mssqlQuery, postgresQuery, mysqlQuery, setSetting, httpNtlm, radius, grpcQuery,
|
||||
redisPingAsync, kafkaProducerAsync, getOidcTokenClientCredentials, rootCertificatesFingerprints, axiosAbortSignal
|
||||
} = require("../util-server");
|
||||
const { R } = require("redbean-node");
|
||||
@@ -24,7 +24,6 @@ const { CookieJar } = require("tough-cookie");
|
||||
const { HttpsCookieAgent } = require("http-cookie-agent/http");
|
||||
const https = require("https");
|
||||
const http = require("http");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
const rootCertificates = rootCertificatesFingerprints();
|
||||
|
||||
@@ -72,23 +71,12 @@ class Monitor extends BeanModel {
|
||||
|
||||
/**
|
||||
* Return an object that ready to parse to JSON
|
||||
* @param {object} preloadData to prevent n+1 problems, we query the data in a batch outside of this function
|
||||
* @param {boolean} includeSensitiveData Include sensitive data in
|
||||
* JSON
|
||||
* @returns {Promise<object>} Object ready to parse
|
||||
* @returns {object} Object ready to parse
|
||||
*/
|
||||
async toJSON(includeSensitiveData = true) {
|
||||
|
||||
let notificationIDList = {};
|
||||
|
||||
let list = await R.find("monitor_notification", " monitor_id = ? ", [
|
||||
this.id,
|
||||
]);
|
||||
|
||||
for (let bean of list) {
|
||||
notificationIDList[bean.notification_id] = true;
|
||||
}
|
||||
|
||||
const tags = await this.getTags();
|
||||
toJSON(preloadData = {}, includeSensitiveData = true) {
|
||||
|
||||
let screenshot = null;
|
||||
|
||||
@@ -96,7 +84,7 @@ class Monitor extends BeanModel {
|
||||
screenshot = "/screenshots/" + jwt.sign(this.id, UptimeKumaServer.getInstance().jwtSecret) + ".png";
|
||||
}
|
||||
|
||||
const path = await this.getPath();
|
||||
const path = preloadData.paths.get(this.id) || [];
|
||||
const pathName = path.join(" / ");
|
||||
|
||||
let data = {
|
||||
@@ -106,15 +94,15 @@ class Monitor extends BeanModel {
|
||||
path,
|
||||
pathName,
|
||||
parent: this.parent,
|
||||
childrenIDs: await Monitor.getAllChildrenIDs(this.id),
|
||||
childrenIDs: preloadData.childrenIDs.get(this.id) || [],
|
||||
url: this.url,
|
||||
method: this.method,
|
||||
hostname: this.hostname,
|
||||
port: this.port,
|
||||
maxretries: this.maxretries,
|
||||
weight: this.weight,
|
||||
active: await this.isActive(),
|
||||
forceInactive: !await Monitor.isParentActive(this.id),
|
||||
active: preloadData.activeStatus.get(this.id),
|
||||
forceInactive: preloadData.forceInactive.get(this.id),
|
||||
type: this.type,
|
||||
timeout: this.timeout,
|
||||
interval: this.interval,
|
||||
@@ -134,9 +122,9 @@ class Monitor extends BeanModel {
|
||||
docker_container: this.docker_container,
|
||||
docker_host: this.docker_host,
|
||||
proxyId: this.proxy_id,
|
||||
notificationIDList,
|
||||
tags: tags,
|
||||
maintenance: await Monitor.isUnderMaintenance(this.id),
|
||||
notificationIDList: preloadData.notifications.get(this.id) || {},
|
||||
tags: preloadData.tags.get(this.id) || [],
|
||||
maintenance: preloadData.maintenanceStatus.get(this.id),
|
||||
mqttTopic: this.mqttTopic,
|
||||
mqttSuccessMessage: this.mqttSuccessMessage,
|
||||
mqttCheckType: this.mqttCheckType,
|
||||
@@ -202,16 +190,6 @@ class Monitor extends BeanModel {
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the monitor is active based on itself and its parents
|
||||
* @returns {Promise<boolean>} Is the monitor active?
|
||||
*/
|
||||
async isActive() {
|
||||
const parentActive = await Monitor.isParentActive(this.id);
|
||||
|
||||
return (this.active === 1) && parentActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all tags applied to this monitor
|
||||
* @returns {Promise<LooseObject<any>[]>} List of tags on the
|
||||
@@ -347,7 +325,7 @@ class Monitor extends BeanModel {
|
||||
let previousBeat = null;
|
||||
let retries = 0;
|
||||
|
||||
this.prometheus = await Prometheus.createAndInitMetrics(this);
|
||||
this.prometheus = new Prometheus(this);
|
||||
|
||||
const beat = async () => {
|
||||
|
||||
@@ -673,7 +651,7 @@ class Monitor extends BeanModel {
|
||||
|
||||
} else if (this.type === "steam") {
|
||||
const steamApiUrl = "https://api.steampowered.com/IGameServersService/GetServerList/v1/";
|
||||
const steamAPIKey = await Settings.get("steamAPIKey");
|
||||
const steamAPIKey = await setting("steamAPIKey");
|
||||
const filter = `addr\\${this.hostname}:${this.port}`;
|
||||
|
||||
if (!steamAPIKey) {
|
||||
@@ -999,7 +977,7 @@ class Monitor extends BeanModel {
|
||||
await R.store(bean);
|
||||
|
||||
log.debug("monitor", `[${this.name}] prometheus.update`);
|
||||
await this.prometheus?.update(bean, tlsInfo);
|
||||
this.prometheus?.update(bean, tlsInfo);
|
||||
|
||||
previousBeat = bean;
|
||||
|
||||
@@ -1197,6 +1175,18 @@ class Monitor extends BeanModel {
|
||||
return checkCertificateResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the monitor is active based on itself and its parents
|
||||
* @param {number} monitorID ID of monitor to send
|
||||
* @param {boolean} active is active
|
||||
* @returns {Promise<boolean>} Is the monitor active?
|
||||
*/
|
||||
static async isActive(monitorID, active) {
|
||||
const parentActive = await Monitor.isParentActive(monitorID);
|
||||
|
||||
return (active === 1) && parentActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send statistics to clients
|
||||
* @param {Server} io Socket server instance
|
||||
@@ -1333,7 +1323,10 @@ class Monitor extends BeanModel {
|
||||
for (let notification of notificationList) {
|
||||
try {
|
||||
const heartbeatJSON = bean.toJSON();
|
||||
|
||||
const monitorData = [{ id: monitor.id,
|
||||
active: monitor.active
|
||||
}];
|
||||
const preloadData = await Monitor.preparePreloadData(monitorData);
|
||||
// Prevent if the msg is undefined, notifications such as Discord cannot send out.
|
||||
if (!heartbeatJSON["msg"]) {
|
||||
heartbeatJSON["msg"] = "N/A";
|
||||
@@ -1344,7 +1337,7 @@ class Monitor extends BeanModel {
|
||||
heartbeatJSON["timezoneOffset"] = UptimeKumaServer.getInstance().getTimezoneOffset();
|
||||
heartbeatJSON["localDateTime"] = dayjs.utc(heartbeatJSON["time"]).tz(heartbeatJSON["timezone"]).format(SQL_DATETIME_FORMAT);
|
||||
|
||||
await Notification.send(JSON.parse(notification.config), msg, await monitor.toJSON(false), heartbeatJSON);
|
||||
await Notification.send(JSON.parse(notification.config), msg, monitor.toJSON(preloadData, false), heartbeatJSON);
|
||||
} catch (e) {
|
||||
log.error("monitor", "Cannot send notification to " + notification.name);
|
||||
log.error("monitor", e);
|
||||
@@ -1380,12 +1373,11 @@ class Monitor extends BeanModel {
|
||||
return;
|
||||
}
|
||||
|
||||
let notifyDays = await Settings.get("tlsExpiryNotifyDays");
|
||||
let notifyDays = await setting("tlsExpiryNotifyDays");
|
||||
if (notifyDays == null || !Array.isArray(notifyDays)) {
|
||||
// Reset Default
|
||||
await Settings.set("tlsExpiryNotifyDays", [ 7, 14, 21 ], "general");
|
||||
await setSetting("tlsExpiryNotifyDays", [ 7, 14, 21 ], "general");
|
||||
notifyDays = [ 7, 14, 21 ];
|
||||
await Settings.set("tlsExpiryNotifyDays", notifyDays, "general");
|
||||
}
|
||||
|
||||
if (Array.isArray(notifyDays)) {
|
||||
@@ -1507,6 +1499,111 @@ class Monitor extends BeanModel {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets monitor notification of multiple monitor
|
||||
* @param {Array} monitorIDs IDs of monitor to get
|
||||
* @returns {Promise<LooseObject<any>>} object
|
||||
*/
|
||||
static async getMonitorNotification(monitorIDs) {
|
||||
return await R.getAll(`
|
||||
SELECT monitor_notification.monitor_id, monitor_notification.notification_id
|
||||
FROM monitor_notification
|
||||
WHERE monitor_notification.monitor_id IN (?)
|
||||
`, [
|
||||
monitorIDs,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets monitor tags of multiple monitor
|
||||
* @param {Array} monitorIDs IDs of monitor to get
|
||||
* @returns {Promise<LooseObject<any>>} object
|
||||
*/
|
||||
static async getMonitorTag(monitorIDs) {
|
||||
return await R.getAll(`
|
||||
SELECT monitor_tag.monitor_id, tag.name, tag.color
|
||||
FROM monitor_tag
|
||||
JOIN tag ON monitor_tag.tag_id = tag.id
|
||||
WHERE monitor_tag.monitor_id IN (?)
|
||||
`, [
|
||||
monitorIDs,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare preloaded data for efficient access
|
||||
* @param {Array} monitorData IDs & active field of monitor to get
|
||||
* @returns {Promise<LooseObject<any>>} object
|
||||
*/
|
||||
static async preparePreloadData(monitorData) {
|
||||
|
||||
const notificationsMap = new Map();
|
||||
const tagsMap = new Map();
|
||||
const maintenanceStatusMap = new Map();
|
||||
const childrenIDsMap = new Map();
|
||||
const activeStatusMap = new Map();
|
||||
const forceInactiveMap = new Map();
|
||||
const pathsMap = new Map();
|
||||
|
||||
if (monitorData.length > 0) {
|
||||
const monitorIDs = monitorData.map(monitor => monitor.id);
|
||||
const notifications = await Monitor.getMonitorNotification(monitorIDs);
|
||||
const tags = await Monitor.getMonitorTag(monitorIDs);
|
||||
const maintenanceStatuses = await Promise.all(monitorData.map(monitor => Monitor.isUnderMaintenance(monitor.id)));
|
||||
const childrenIDs = await Promise.all(monitorData.map(monitor => Monitor.getAllChildrenIDs(monitor.id)));
|
||||
const activeStatuses = await Promise.all(monitorData.map(monitor => Monitor.isActive(monitor.id, monitor.active)));
|
||||
const forceInactiveStatuses = await Promise.all(monitorData.map(monitor => Monitor.isParentActive(monitor.id)));
|
||||
const paths = await Promise.all(monitorData.map(monitor => Monitor.getAllPath(monitor.id, monitor.name)));
|
||||
|
||||
notifications.forEach(row => {
|
||||
if (!notificationsMap.has(row.monitor_id)) {
|
||||
notificationsMap.set(row.monitor_id, {});
|
||||
}
|
||||
notificationsMap.get(row.monitor_id)[row.notification_id] = true;
|
||||
});
|
||||
|
||||
tags.forEach(row => {
|
||||
if (!tagsMap.has(row.monitor_id)) {
|
||||
tagsMap.set(row.monitor_id, []);
|
||||
}
|
||||
tagsMap.get(row.monitor_id).push({
|
||||
name: row.name,
|
||||
color: row.color
|
||||
});
|
||||
});
|
||||
|
||||
monitorData.forEach((monitor, index) => {
|
||||
maintenanceStatusMap.set(monitor.id, maintenanceStatuses[index]);
|
||||
});
|
||||
|
||||
monitorData.forEach((monitor, index) => {
|
||||
childrenIDsMap.set(monitor.id, childrenIDs[index]);
|
||||
});
|
||||
|
||||
monitorData.forEach((monitor, index) => {
|
||||
activeStatusMap.set(monitor.id, activeStatuses[index]);
|
||||
});
|
||||
|
||||
monitorData.forEach((monitor, index) => {
|
||||
forceInactiveMap.set(monitor.id, !forceInactiveStatuses[index]);
|
||||
});
|
||||
|
||||
monitorData.forEach((monitor, index) => {
|
||||
pathsMap.set(monitor.id, paths[index]);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
notifications: notificationsMap,
|
||||
tags: tagsMap,
|
||||
maintenanceStatus: maintenanceStatusMap,
|
||||
childrenIDs: childrenIDsMap,
|
||||
activeStatus: activeStatusMap,
|
||||
forceInactive: forceInactiveMap,
|
||||
paths: pathsMap,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets Parent of the monitor
|
||||
* @param {number} monitorID ID of monitor to get
|
||||
@@ -1539,16 +1636,18 @@ class Monitor extends BeanModel {
|
||||
|
||||
/**
|
||||
* Gets the full path
|
||||
* @param {number} monitorID ID of the monitor to get
|
||||
* @param {string} name of the monitor to get
|
||||
* @returns {Promise<string[]>} Full path (includes groups and the name) of the monitor
|
||||
*/
|
||||
async getPath() {
|
||||
const path = [ this.name ];
|
||||
static async getAllPath(monitorID, name) {
|
||||
const path = [ name ];
|
||||
|
||||
if (this.parent === null) {
|
||||
return path;
|
||||
}
|
||||
|
||||
let parent = await Monitor.getParent(this.id);
|
||||
let parent = await Monitor.getParent(monitorID);
|
||||
while (parent !== null) {
|
||||
path.unshift(parent.name);
|
||||
parent = await Monitor.getParent(parent.id);
|
||||
|
@@ -1,6 +1,5 @@
|
||||
let url = require("url");
|
||||
let MemoryCache = require("./memory-cache");
|
||||
const { log } = require("../../../src/util");
|
||||
|
||||
let t = {
|
||||
ms: 1,
|
||||
@@ -91,6 +90,24 @@ function ApiCache() {
|
||||
instances.push(this);
|
||||
this.id = instances.length;
|
||||
|
||||
/**
|
||||
* Logs a message to the console if the `DEBUG` environment variable is set.
|
||||
* @param {string} a The first argument to log.
|
||||
* @param {string} b The second argument to log.
|
||||
* @param {string} c The third argument to log.
|
||||
* @param {string} d The fourth argument to log, and so on... (optional)
|
||||
*
|
||||
* Generated by Trelent
|
||||
*/
|
||||
function debug(a, b, c, d) {
|
||||
let arr = ["\x1b[36m[apicache]\x1b[0m", a, b, c, d].filter(function (arg) {
|
||||
return arg !== undefined;
|
||||
});
|
||||
let debugEnv = process.env.DEBUG && process.env.DEBUG.split(",").indexOf("apicache") !== -1;
|
||||
|
||||
return (globalOptions.debug || debugEnv) && console.log.apply(null, arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given request and response should be logged.
|
||||
* @param {Object} request The HTTP request object.
|
||||
@@ -129,7 +146,7 @@ function ApiCache() {
|
||||
let groupName = req.apicacheGroup;
|
||||
|
||||
if (groupName) {
|
||||
log.debug("apicache", `group detected "${groupName}"`);
|
||||
debug("group detected \"" + groupName + "\"");
|
||||
let group = (index.groups[groupName] = index.groups[groupName] || []);
|
||||
group.unshift(key);
|
||||
}
|
||||
@@ -195,7 +212,7 @@ function ApiCache() {
|
||||
redis.hset(key, "duration", duration);
|
||||
redis.expire(key, duration / 1000, expireCallback || function () {});
|
||||
} catch (err) {
|
||||
log.debug("apicache", `error in redis.hset(): ${err}`);
|
||||
debug("[apicache] error in redis.hset()");
|
||||
}
|
||||
} else {
|
||||
memCache.add(key, value, duration, expireCallback);
|
||||
@@ -303,10 +320,10 @@ function ApiCache() {
|
||||
|
||||
// display log entry
|
||||
let elapsed = new Date() - req.apicacheTimer;
|
||||
log.debug("apicache", `adding cache entry for "${key}" @ ${strDuration} ${logDuration(elapsed)}`);
|
||||
log.debug("apicache", `_apicache.headers: ${JSON.stringify(res._apicache.headers)}`);
|
||||
log.debug("apicache", `res.getHeaders(): ${JSON.stringify(getSafeHeaders(res))}`);
|
||||
log.debug("apicache", `cacheObject: ${JSON.stringify(cacheObject)}`);
|
||||
debug("adding cache entry for \"" + key + "\" @ " + strDuration, logDuration(elapsed));
|
||||
debug("_apicache.headers: ", res._apicache.headers);
|
||||
debug("res.getHeaders(): ", getSafeHeaders(res));
|
||||
debug("cacheObject: ", cacheObject);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,10 +402,10 @@ function ApiCache() {
|
||||
let redis = globalOptions.redisClient;
|
||||
|
||||
if (group) {
|
||||
log.debug("apicache", `clearing group "${target}"`);
|
||||
debug("clearing group \"" + target + "\"");
|
||||
|
||||
group.forEach(function (key) {
|
||||
log.debug("apicache", `clearing cached entry for "${key}"`);
|
||||
debug("clearing cached entry for \"" + key + "\"");
|
||||
clearTimeout(timers[key]);
|
||||
delete timers[key];
|
||||
if (!globalOptions.redisClient) {
|
||||
@@ -397,7 +414,7 @@ function ApiCache() {
|
||||
try {
|
||||
redis.del(key);
|
||||
} catch (err) {
|
||||
log.info("apicache", "error in redis.del(\"" + key + "\")");
|
||||
console.log("[apicache] error in redis.del(\"" + key + "\")");
|
||||
}
|
||||
}
|
||||
index.all = index.all.filter(doesntMatch(key));
|
||||
@@ -405,7 +422,7 @@ function ApiCache() {
|
||||
|
||||
delete index.groups[target];
|
||||
} else if (target) {
|
||||
log.debug("apicache", `clearing ${isAutomatic ? "expired" : "cached"} entry for "${target}"`);
|
||||
debug("clearing " + (isAutomatic ? "expired" : "cached") + " entry for \"" + target + "\"");
|
||||
clearTimeout(timers[target]);
|
||||
delete timers[target];
|
||||
// clear actual cached entry
|
||||
@@ -415,7 +432,7 @@ function ApiCache() {
|
||||
try {
|
||||
redis.del(target);
|
||||
} catch (err) {
|
||||
log.error("apicache", "error in redis.del(\"" + target + "\")");
|
||||
console.log("[apicache] error in redis.del(\"" + target + "\")");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,7 +449,7 @@ function ApiCache() {
|
||||
}
|
||||
});
|
||||
} else {
|
||||
log.debug("apicache", "clearing entire index");
|
||||
debug("clearing entire index");
|
||||
|
||||
if (!redis) {
|
||||
memCache.clear();
|
||||
@@ -444,7 +461,7 @@ function ApiCache() {
|
||||
try {
|
||||
redis.del(key);
|
||||
} catch (err) {
|
||||
log.error("apicache", `error in redis.del("${key}"): ${err}`);
|
||||
console.log("[apicache] error in redis.del(\"" + key + "\")");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -511,7 +528,7 @@ function ApiCache() {
|
||||
|
||||
/**
|
||||
* Get index of a group
|
||||
* @param {string} group
|
||||
* @param {string} group
|
||||
* @returns {number}
|
||||
*/
|
||||
this.getIndex = function (group) {
|
||||
@@ -526,9 +543,9 @@ function ApiCache() {
|
||||
* Express middleware
|
||||
* @param {(string|number)} strDuration Duration to cache responses
|
||||
* for.
|
||||
* @param {function(Object, Object):boolean} middlewareToggle
|
||||
* @param {function(Object, Object):boolean} middlewareToggle
|
||||
* @param {Object} localOptions Options for APICache
|
||||
* @returns
|
||||
* @returns
|
||||
*/
|
||||
this.middleware = function cache(strDuration, middlewareToggle, localOptions) {
|
||||
let duration = instance.getDuration(strDuration);
|
||||
@@ -735,7 +752,7 @@ function ApiCache() {
|
||||
*/
|
||||
let cache = function (req, res, next) {
|
||||
function bypass() {
|
||||
log.debug("apicache", "bypass detected, skipping cache.");
|
||||
debug("bypass detected, skipping cache.");
|
||||
return next();
|
||||
}
|
||||
|
||||
@@ -788,7 +805,7 @@ function ApiCache() {
|
||||
// send if cache hit from memory-cache
|
||||
if (cached) {
|
||||
let elapsed = new Date() - req.apicacheTimer;
|
||||
log.debug("apicache", `sending cached (memory-cache) version of ${key} ${logDuration(elapsed)}`);
|
||||
debug("sending cached (memory-cache) version of", key, logDuration(elapsed));
|
||||
|
||||
perf.hit(key);
|
||||
return sendCachedResponse(req, res, cached, middlewareToggle, next, duration);
|
||||
@@ -800,7 +817,7 @@ function ApiCache() {
|
||||
redis.hgetall(key, function (err, obj) {
|
||||
if (!err && obj && obj.response) {
|
||||
let elapsed = new Date() - req.apicacheTimer;
|
||||
log.debug("apicache", "sending cached (redis) version of "+ key+" "+ logDuration(elapsed));
|
||||
debug("sending cached (redis) version of", key, logDuration(elapsed));
|
||||
|
||||
perf.hit(key);
|
||||
return sendCachedResponse(
|
||||
@@ -842,7 +859,7 @@ function ApiCache() {
|
||||
|
||||
/**
|
||||
* Process options
|
||||
* @param {Object} options
|
||||
* @param {Object} options
|
||||
* @returns {Object}
|
||||
*/
|
||||
this.options = function (options) {
|
||||
@@ -856,7 +873,7 @@ function ApiCache() {
|
||||
}
|
||||
|
||||
if (globalOptions.trackPerformance) {
|
||||
log.debug("apicache", "WARNING: using trackPerformance flag can cause high memory usage!");
|
||||
debug("WARNING: using trackPerformance flag can cause high memory usage!");
|
||||
}
|
||||
|
||||
return this;
|
||||
|
@@ -63,7 +63,7 @@ if (process.platform === "win32") {
|
||||
* @returns {Promise<boolean>} The executable is allowed?
|
||||
*/
|
||||
async function isAllowedChromeExecutable(executablePath) {
|
||||
log.info("Chromium", config.args);
|
||||
console.log(config.args);
|
||||
if (config.args["allow-all-chrome-exec"] || process.env.UPTIME_KUMA_ALLOW_ALL_CHROME_EXEC === "1") {
|
||||
return true;
|
||||
}
|
||||
@@ -102,8 +102,7 @@ async function getBrowser() {
|
||||
*/
|
||||
async function getRemoteBrowser(remoteBrowserID, userId) {
|
||||
let remoteBrowser = await RemoteBrowser.get(remoteBrowserID, userId);
|
||||
log.debug("Chromium", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`);
|
||||
browser = chromium.connect(remoteBrowser.url);
|
||||
log.debug("MONITOR", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`);
|
||||
browser = await chromium.connect(remoteBrowser.url);
|
||||
return browser;
|
||||
}
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { setting } = require("../util-server");
|
||||
const { getMonitorRelativeURL, UP, DOWN } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
class AlertNow extends NotificationProvider {
|
||||
name = "AlertNow";
|
||||
@@ -29,7 +29,7 @@ class AlertNow extends NotificationProvider {
|
||||
|
||||
textMsg += ` - ${msg}`;
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL && monitorJSON) {
|
||||
textMsg += ` >> ${baseURL + getMonitorRelativeURL(monitorJSON.id)}`;
|
||||
}
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
const { setting } = require("../util-server");
|
||||
const successMessage = "Sent Successfully.";
|
||||
|
||||
class FlashDuty extends NotificationProvider {
|
||||
@@ -84,7 +84,7 @@ class FlashDuty extends NotificationProvider {
|
||||
}
|
||||
};
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL && monitorInfo) {
|
||||
options.client = "Uptime Kuma";
|
||||
options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id);
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { setting } = require("../util-server");
|
||||
const { getMonitorRelativeURL, UP } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
class GoogleChat extends NotificationProvider {
|
||||
name = "GoogleChat";
|
||||
@@ -45,7 +45,7 @@ class GoogleChat extends NotificationProvider {
|
||||
}
|
||||
|
||||
// add button for monitor link if available
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL) {
|
||||
const urlPath = monitorJSON ? getMonitorRelativeURL(monitorJSON.id) : "/";
|
||||
sectionWidgets.push({
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
const { setting } = require("../util-server");
|
||||
let successMessage = "Sent Successfully.";
|
||||
|
||||
class PagerDuty extends NotificationProvider {
|
||||
@@ -95,7 +95,7 @@ class PagerDuty extends NotificationProvider {
|
||||
}
|
||||
};
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL && monitorInfo) {
|
||||
options.client = "Uptime Kuma";
|
||||
options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id);
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
const { setting } = require("../util-server");
|
||||
let successMessage = "Sent Successfully.";
|
||||
|
||||
class PagerTree extends NotificationProvider {
|
||||
@@ -74,7 +74,7 @@ class PagerTree extends NotificationProvider {
|
||||
}
|
||||
};
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL && monitorJSON) {
|
||||
options.client = "Uptime Kuma";
|
||||
options.client_url = baseURL + getMonitorRelativeURL(monitorJSON.id);
|
||||
|
@@ -1,8 +1,8 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const Slack = require("./slack");
|
||||
const { setting } = require("../util-server");
|
||||
const { getMonitorRelativeURL, DOWN } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
class RocketChat extends NotificationProvider {
|
||||
name = "rocket.chat";
|
||||
@@ -49,7 +49,7 @@ class RocketChat extends NotificationProvider {
|
||||
await Slack.deprecateURL(notification.rocketbutton);
|
||||
}
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
|
||||
if (baseURL) {
|
||||
data.attachments[0].title_link = baseURL + getMonitorRelativeURL(monitorJSON.id);
|
||||
|
@@ -1,8 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { setSettings, setting } = require("../util-server");
|
||||
const { getMonitorRelativeURL, UP } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
const { log } = require("../../src/util");
|
||||
|
||||
class Slack extends NotificationProvider {
|
||||
name = "slack";
|
||||
@@ -15,13 +14,15 @@ class Slack extends NotificationProvider {
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
static async deprecateURL(url) {
|
||||
let currentPrimaryBaseURL = await Settings.get("primaryBaseURL");
|
||||
let currentPrimaryBaseURL = await setting("primaryBaseURL");
|
||||
|
||||
if (!currentPrimaryBaseURL) {
|
||||
log.error("notification", "Move the url to be the primary base URL");
|
||||
await Settings.set("primaryBaseURL", url, "general");
|
||||
console.log("Move the url to be the primary base URL");
|
||||
await setSettings("general", {
|
||||
primaryBaseURL: url,
|
||||
});
|
||||
} else {
|
||||
log.debug("notification", "Already there, no need to move the primary base URL");
|
||||
console.log("Already there, no need to move the primary base URL");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,21 +136,26 @@ class Slack extends NotificationProvider {
|
||||
return okMsg;
|
||||
}
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
|
||||
const title = "Uptime Kuma Alert";
|
||||
let data = {
|
||||
"text": `${title}\n${msg}`,
|
||||
"channel": notification.slackchannel,
|
||||
"username": notification.slackusername,
|
||||
"icon_emoji": notification.slackiconemo,
|
||||
"attachments": [
|
||||
"attachments": [],
|
||||
};
|
||||
|
||||
if (notification.slackrichmessage) {
|
||||
data.attachments.push(
|
||||
{
|
||||
"color": (heartbeatJSON["status"] === UP) ? "#2eb886" : "#e01e5a",
|
||||
"blocks": Slack.buildBlocks(baseURL, monitorJSON, heartbeatJSON, title, msg),
|
||||
}
|
||||
]
|
||||
};
|
||||
);
|
||||
} else {
|
||||
data.text = `${title}\n${msg}`;
|
||||
}
|
||||
|
||||
if (notification.slackbutton) {
|
||||
await Slack.deprecateURL(notification.slackbutton);
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
const { setting } = require("../util-server");
|
||||
let successMessage = "Sent Successfully.";
|
||||
|
||||
class Splunk extends NotificationProvider {
|
||||
@@ -95,7 +95,7 @@ class Splunk extends NotificationProvider {
|
||||
}
|
||||
};
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL && monitorInfo) {
|
||||
options.client = "Uptime Kuma";
|
||||
options.client_url = baseURL + getMonitorRelativeURL(monitorInfo.id);
|
||||
|
@@ -1,7 +1,7 @@
|
||||
const NotificationProvider = require("./notification-provider");
|
||||
const axios = require("axios");
|
||||
const { setting } = require("../util-server");
|
||||
const { getMonitorRelativeURL } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
class Stackfield extends NotificationProvider {
|
||||
name = "stackfield";
|
||||
@@ -23,7 +23,7 @@ class Stackfield extends NotificationProvider {
|
||||
|
||||
textMsg += `\n${msg}`;
|
||||
|
||||
const baseURL = await Settings.get("primaryBaseURL");
|
||||
const baseURL = await setting("primaryBaseURL");
|
||||
if (baseURL) {
|
||||
textMsg += `\n${baseURL + getMonitorRelativeURL(monitorJSON.id)}`;
|
||||
}
|
||||
|
@@ -32,20 +32,17 @@ class WeCom extends NotificationProvider {
|
||||
* @returns {object} Message
|
||||
*/
|
||||
composeMessage(heartbeatJSON, msg) {
|
||||
let title;
|
||||
let title = "UptimeKuma Message";
|
||||
if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] === UP) {
|
||||
title = "UptimeKuma Monitor Up";
|
||||
}
|
||||
if (msg != null && heartbeatJSON != null && heartbeatJSON["status"] === DOWN) {
|
||||
title = "UptimeKuma Monitor Down";
|
||||
}
|
||||
if (msg != null) {
|
||||
title = "UptimeKuma Message";
|
||||
}
|
||||
return {
|
||||
msgtype: "text",
|
||||
text: {
|
||||
content: title + msg
|
||||
content: title + "\n" + msg
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@@ -1,4 +1,3 @@
|
||||
const { R } = require("redbean-node");
|
||||
const PrometheusClient = require("prom-client");
|
||||
const { log } = require("../src/util");
|
||||
|
||||
@@ -10,102 +9,36 @@ const commonLabels = [
|
||||
"monitor_port",
|
||||
];
|
||||
|
||||
const monitorCertDaysRemaining = new PrometheusClient.Gauge({
|
||||
name: "monitor_cert_days_remaining",
|
||||
help: "The number of days remaining until the certificate expires",
|
||||
labelNames: commonLabels
|
||||
});
|
||||
|
||||
const monitorCertIsValid = new PrometheusClient.Gauge({
|
||||
name: "monitor_cert_is_valid",
|
||||
help: "Is the certificate still valid? (1 = Yes, 0= No)",
|
||||
labelNames: commonLabels
|
||||
});
|
||||
const monitorResponseTime = new PrometheusClient.Gauge({
|
||||
name: "monitor_response_time",
|
||||
help: "Monitor Response Time (ms)",
|
||||
labelNames: commonLabels
|
||||
});
|
||||
|
||||
const monitorStatus = new PrometheusClient.Gauge({
|
||||
name: "monitor_status",
|
||||
help: "Monitor Status (1 = UP, 0= DOWN, 2= PENDING, 3= MAINTENANCE)",
|
||||
labelNames: commonLabels
|
||||
});
|
||||
|
||||
class Prometheus {
|
||||
monitorLabelValues = {};
|
||||
|
||||
/**
|
||||
* Metric: monitor_cert_days_remaining
|
||||
* @type {PrometheusClient.Gauge<string> | null}
|
||||
* @param {object} monitor Monitor object to monitor
|
||||
*/
|
||||
static monitorCertDaysRemaining = null;
|
||||
|
||||
/**
|
||||
* Metric: monitor_cert_is_valid
|
||||
* @type {PrometheusClient.Gauge<string> | null}
|
||||
*/
|
||||
static monitorCertIsValid = null;
|
||||
|
||||
/**
|
||||
* Metric: monitor_response_time
|
||||
* @type {PrometheusClient.Gauge<string> | null}
|
||||
*/
|
||||
static monitorResponseTime = null;
|
||||
|
||||
/**
|
||||
* Metric: monitor_status
|
||||
* @type {PrometheusClient.Gauge<string> | null}
|
||||
*/
|
||||
static monitorStatus = null;
|
||||
|
||||
/**
|
||||
* All registered metric labels.
|
||||
* @type {string[] | null}
|
||||
*/
|
||||
static monitorLabelNames = null;
|
||||
|
||||
/**
|
||||
* Monitor labels/values combination.
|
||||
* @type {{}}
|
||||
*/
|
||||
monitorLabelValues;
|
||||
|
||||
/**
|
||||
* Initialize metrics and get all label names the first time called.
|
||||
* @returns {void}
|
||||
*/
|
||||
static async initMetrics() {
|
||||
if (!this.monitorLabelNames) {
|
||||
let labelNames = await R.getCol("SELECT name FROM tag");
|
||||
this.monitorLabelNames = [ ...commonLabels, ...labelNames ];
|
||||
}
|
||||
if (!this.monitorCertDaysRemaining) {
|
||||
this.monitorCertDaysRemaining = new PrometheusClient.Gauge({
|
||||
name: "monitor_cert_days_remaining",
|
||||
help: "The number of days remaining until the certificate expires",
|
||||
labelNames: this.monitorLabelNames
|
||||
});
|
||||
}
|
||||
if (!this.monitorCertIsValid) {
|
||||
this.monitorCertIsValid = new PrometheusClient.Gauge({
|
||||
name: "monitor_cert_is_valid",
|
||||
help: "Is the certificate still valid? (1 = Yes, 0 = No)",
|
||||
labelNames: this.monitorLabelNames
|
||||
});
|
||||
}
|
||||
if (!this.monitorResponseTime) {
|
||||
this.monitorResponseTime = new PrometheusClient.Gauge({
|
||||
name: "monitor_response_time",
|
||||
help: "Monitor Response Time (ms)",
|
||||
labelNames: this.monitorLabelNames
|
||||
});
|
||||
}
|
||||
if (!this.monitorStatus) {
|
||||
this.monitorStatus = new PrometheusClient.Gauge({
|
||||
name: "monitor_status",
|
||||
help: "Monitor Status (1 = UP, 0 = DOWN, 2 = PENDING, 3 = MAINTENANCE)",
|
||||
labelNames: this.monitorLabelNames
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper to create a `Prometheus` instance and ensure metrics are initialized.
|
||||
* @param {Monitor} monitor Monitor object to monitor
|
||||
* @returns {Promise<Prometheus>} `Prometheus` instance
|
||||
*/
|
||||
static async createAndInitMetrics(monitor) {
|
||||
await Prometheus.initMetrics();
|
||||
let tags = await monitor.getTags();
|
||||
return new Prometheus(monitor, tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a prometheus metric instance.
|
||||
*
|
||||
* Note: Make sure to call `Prometheus.initMetrics()` once prior creating Prometheus instances.
|
||||
* @param {Monitor} monitor Monitor object to monitor
|
||||
* @param {Promise<LooseObject<any>[]>} tags Tags of the monitor
|
||||
*/
|
||||
constructor(monitor, tags) {
|
||||
constructor(monitor) {
|
||||
this.monitorLabelValues = {
|
||||
monitor_name: monitor.name,
|
||||
monitor_type: monitor.type,
|
||||
@@ -113,12 +46,6 @@ class Prometheus {
|
||||
monitor_hostname: monitor.hostname,
|
||||
monitor_port: monitor.port
|
||||
};
|
||||
Object.values(tags)
|
||||
// only label names that were known at first metric creation.
|
||||
.filter(tag => Prometheus.monitorLabelNames.includes(tag.name))
|
||||
.forEach(tag => {
|
||||
this.monitorLabelValues[tag.name] = tag.value;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,6 +55,7 @@ class Prometheus {
|
||||
* @returns {void}
|
||||
*/
|
||||
update(heartbeat, tlsInfo) {
|
||||
|
||||
if (typeof tlsInfo !== "undefined") {
|
||||
try {
|
||||
let isValid;
|
||||
@@ -136,7 +64,7 @@ class Prometheus {
|
||||
} else {
|
||||
isValid = 0;
|
||||
}
|
||||
Prometheus.monitorCertIsValid.set(this.monitorLabelValues, isValid);
|
||||
monitorCertIsValid.set(this.monitorLabelValues, isValid);
|
||||
} catch (e) {
|
||||
log.error("prometheus", "Caught error");
|
||||
log.error("prometheus", e);
|
||||
@@ -144,7 +72,7 @@ class Prometheus {
|
||||
|
||||
try {
|
||||
if (tlsInfo.certInfo != null) {
|
||||
Prometheus.monitorCertDaysRemaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining);
|
||||
monitorCertDaysRemaining.set(this.monitorLabelValues, tlsInfo.certInfo.daysRemaining);
|
||||
}
|
||||
} catch (e) {
|
||||
log.error("prometheus", "Caught error");
|
||||
@@ -154,7 +82,7 @@ class Prometheus {
|
||||
|
||||
if (heartbeat) {
|
||||
try {
|
||||
Prometheus.monitorStatus.set(this.monitorLabelValues, heartbeat.status);
|
||||
monitorStatus.set(this.monitorLabelValues, heartbeat.status);
|
||||
} catch (e) {
|
||||
log.error("prometheus", "Caught error");
|
||||
log.error("prometheus", e);
|
||||
@@ -162,10 +90,10 @@ class Prometheus {
|
||||
|
||||
try {
|
||||
if (typeof heartbeat.ping === "number") {
|
||||
Prometheus.monitorResponseTime.set(this.monitorLabelValues, heartbeat.ping);
|
||||
monitorResponseTime.set(this.monitorLabelValues, heartbeat.ping);
|
||||
} else {
|
||||
// Is it good?
|
||||
Prometheus.monitorResponseTime.set(this.monitorLabelValues, -1);
|
||||
monitorResponseTime.set(this.monitorLabelValues, -1);
|
||||
}
|
||||
} catch (e) {
|
||||
log.error("prometheus", "Caught error");
|
||||
@@ -180,10 +108,10 @@ class Prometheus {
|
||||
*/
|
||||
remove() {
|
||||
try {
|
||||
Prometheus.monitorCertDaysRemaining?.remove(this.monitorLabelValues);
|
||||
Prometheus.monitorCertIsValid?.remove(this.monitorLabelValues);
|
||||
Prometheus.monitorResponseTime?.remove(this.monitorLabelValues);
|
||||
Prometheus.monitorStatus?.remove(this.monitorLabelValues);
|
||||
monitorCertDaysRemaining.remove(this.monitorLabelValues);
|
||||
monitorCertIsValid.remove(this.monitorLabelValues);
|
||||
monitorResponseTime.remove(this.monitorLabelValues);
|
||||
monitorStatus.remove(this.monitorLabelValues);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
@@ -2,7 +2,7 @@ const { R } = require("redbean-node");
|
||||
const HttpProxyAgent = require("http-proxy-agent");
|
||||
const HttpsProxyAgent = require("https-proxy-agent");
|
||||
const SocksProxyAgent = require("socks-proxy-agent");
|
||||
const { log } = require("../src/util");
|
||||
const { debug } = require("../src/util");
|
||||
const { UptimeKumaServer } = require("./uptime-kuma-server");
|
||||
const { CookieJar } = require("tough-cookie");
|
||||
const { createCookieAgent } = require("http-cookie-agent/http");
|
||||
@@ -110,9 +110,9 @@ class Proxy {
|
||||
proxyOptions.auth = `${proxy.username}:${proxy.password}`;
|
||||
}
|
||||
|
||||
log.debug("update-proxy", `Proxy Options: ${JSON.stringify(proxyOptions)}`);
|
||||
log.debug("update-proxy", `HTTP Agent Options: ${JSON.stringify(httpAgentOptions)}`);
|
||||
log.debug("update-proxy", `HTTPS Agent Options: ${JSON.stringify(httpsAgentOptions)}`);
|
||||
debug(`Proxy Options: ${JSON.stringify(proxyOptions)}`);
|
||||
debug(`HTTP Agent Options: ${JSON.stringify(httpAgentOptions)}`);
|
||||
debug(`HTTPS Agent Options: ${JSON.stringify(httpsAgentOptions)}`);
|
||||
|
||||
switch (proxy.protocol) {
|
||||
case "http":
|
||||
|
@@ -1,5 +1,6 @@
|
||||
let express = require("express");
|
||||
const {
|
||||
setting,
|
||||
allowDevAllOrigin,
|
||||
allowAllOrigin,
|
||||
percentageToColor,
|
||||
@@ -17,7 +18,6 @@ const { makeBadge } = require("badge-maker");
|
||||
const { Prometheus } = require("../prometheus");
|
||||
const Database = require("../database");
|
||||
const { UptimeCalculator } = require("../uptime-calculator");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
let router = express.Router();
|
||||
|
||||
@@ -30,7 +30,7 @@ router.get("/api/entry-page", async (request, response) => {
|
||||
|
||||
let result = { };
|
||||
let hostname = request.hostname;
|
||||
if ((await Settings.get("trustProxy")) && request.headers["x-forwarded-host"]) {
|
||||
if ((await setting("trustProxy")) && request.headers["x-forwarded-host"]) {
|
||||
hostname = request.headers["x-forwarded-host"];
|
||||
}
|
||||
|
||||
|
@@ -90,7 +90,8 @@ const Monitor = require("./model/monitor");
|
||||
const User = require("./model/user");
|
||||
|
||||
log.debug("server", "Importing Settings");
|
||||
const { initJWTSecret, checkLogin, doubleCheckPassword, shake256, SHAKE256_LENGTH, allowDevAllOrigin } = require("./util-server");
|
||||
const { getSettings, setSettings, setting, initJWTSecret, checkLogin, doubleCheckPassword, shake256, SHAKE256_LENGTH, allowDevAllOrigin,
|
||||
} = require("./util-server");
|
||||
|
||||
log.debug("server", "Importing Notification");
|
||||
const { Notification } = require("./notification");
|
||||
@@ -200,7 +201,7 @@ let needSetup = false;
|
||||
// Entry Page
|
||||
app.get("/", async (request, response) => {
|
||||
let hostname = request.hostname;
|
||||
if (await Settings.get("trustProxy")) {
|
||||
if (await setting("trustProxy")) {
|
||||
const proxy = request.headers["x-forwarded-host"];
|
||||
if (proxy) {
|
||||
hostname = proxy;
|
||||
@@ -280,7 +281,7 @@ let needSetup = false;
|
||||
// Robots.txt
|
||||
app.get("/robots.txt", async (_request, response) => {
|
||||
let txt = "User-agent: *\nDisallow:";
|
||||
if (!await Settings.get("searchEngineIndex")) {
|
||||
if (!await setting("searchEngineIndex")) {
|
||||
txt += " /";
|
||||
}
|
||||
response.setHeader("Content-Type", "text/plain");
|
||||
@@ -726,7 +727,7 @@ let needSetup = false;
|
||||
|
||||
await updateMonitorNotification(bean.id, notificationIDList);
|
||||
|
||||
await server.sendMonitorList(socket);
|
||||
await server.sendUpdateMonitorIntoList(socket, bean.id);
|
||||
|
||||
if (monitor.active !== false) {
|
||||
await startMonitor(socket.userID, bean.id);
|
||||
@@ -879,11 +880,11 @@ let needSetup = false;
|
||||
|
||||
await updateMonitorNotification(bean.id, monitor.notificationIDList);
|
||||
|
||||
if (await bean.isActive()) {
|
||||
if (await Monitor.isActive(bean.id, bean.active)) {
|
||||
await restartMonitor(socket.userID, bean.id);
|
||||
}
|
||||
|
||||
await server.sendMonitorList(socket);
|
||||
await server.sendUpdateMonitorIntoList(socket, bean.id);
|
||||
|
||||
callback({
|
||||
ok: true,
|
||||
@@ -923,14 +924,17 @@ let needSetup = false;
|
||||
|
||||
log.info("monitor", `Get Monitor: ${monitorID} User ID: ${socket.userID}`);
|
||||
|
||||
let bean = await R.findOne("monitor", " id = ? AND user_id = ? ", [
|
||||
let monitor = await R.findOne("monitor", " id = ? AND user_id = ? ", [
|
||||
monitorID,
|
||||
socket.userID,
|
||||
]);
|
||||
|
||||
const monitorData = [{ id: monitor.id,
|
||||
active: monitor.active
|
||||
}];
|
||||
const preloadData = await Monitor.preparePreloadData(monitorData);
|
||||
callback({
|
||||
ok: true,
|
||||
monitor: await bean.toJSON(),
|
||||
monitor: monitor.toJSON(preloadData),
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
@@ -981,7 +985,7 @@ let needSetup = false;
|
||||
try {
|
||||
checkLogin(socket);
|
||||
await startMonitor(socket.userID, monitorID);
|
||||
await server.sendMonitorList(socket);
|
||||
await server.sendUpdateMonitorIntoList(socket, monitorID);
|
||||
|
||||
callback({
|
||||
ok: true,
|
||||
@@ -1001,7 +1005,7 @@ let needSetup = false;
|
||||
try {
|
||||
checkLogin(socket);
|
||||
await pauseMonitor(socket.userID, monitorID);
|
||||
await server.sendMonitorList(socket);
|
||||
await server.sendUpdateMonitorIntoList(socket, monitorID);
|
||||
|
||||
callback({
|
||||
ok: true,
|
||||
@@ -1047,8 +1051,7 @@ let needSetup = false;
|
||||
msg: "successDeleted",
|
||||
msgi18n: true,
|
||||
});
|
||||
|
||||
await server.sendMonitorList(socket);
|
||||
await server.sendDeleteMonitorFromList(socket, monitorID);
|
||||
|
||||
} catch (e) {
|
||||
callback({
|
||||
@@ -1324,7 +1327,7 @@ let needSetup = false;
|
||||
socket.on("getSettings", async (callback) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
const data = await Settings.getSettings("general");
|
||||
const data = await getSettings("general");
|
||||
|
||||
if (!data.serverTimezone) {
|
||||
data.serverTimezone = await server.getTimezone();
|
||||
@@ -1352,7 +1355,7 @@ let needSetup = false;
|
||||
// Disabled Auth + Want to Enable Auth => No Check
|
||||
// Enabled Auth + Want to Disable Auth => Check!!
|
||||
// Enabled Auth + Want to Enable Auth => No Check
|
||||
const currentDisabledAuth = await Settings.get("disableAuth");
|
||||
const currentDisabledAuth = await setting("disableAuth");
|
||||
if (!currentDisabledAuth && data.disableAuth) {
|
||||
await doubleCheckPassword(socket, currentPassword);
|
||||
}
|
||||
@@ -1366,7 +1369,7 @@ let needSetup = false;
|
||||
const previousChromeExecutable = await Settings.get("chromeExecutable");
|
||||
const previousNSCDStatus = await Settings.get("nscd");
|
||||
|
||||
await Settings.setSettings("general", data);
|
||||
await setSettings("general", data);
|
||||
server.entryPage = data.entryPage;
|
||||
|
||||
// Also need to apply timezone globally
|
||||
@@ -1462,7 +1465,7 @@ let needSetup = false;
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
log.error("server", e);
|
||||
console.error(e);
|
||||
|
||||
callback({
|
||||
ok: false,
|
||||
@@ -1575,7 +1578,7 @@ let needSetup = false;
|
||||
// ***************************
|
||||
|
||||
log.debug("auth", "check auto login");
|
||||
if (await Settings.get("disableAuth")) {
|
||||
if (await setting("disableAuth")) {
|
||||
log.info("auth", "Disabled Auth: auto login to admin");
|
||||
await afterLogin(socket, await R.findOne("user"));
|
||||
socket.emit("autoLogin");
|
||||
@@ -1678,13 +1681,13 @@ async function afterLogin(socket, user) {
|
||||
|
||||
await StatusPage.sendStatusPageList(io, socket);
|
||||
|
||||
const monitorPromises = [];
|
||||
for (let monitorID in monitorList) {
|
||||
await sendHeartbeatList(socket, monitorID);
|
||||
monitorPromises.push(sendHeartbeatList(socket, monitorID));
|
||||
monitorPromises.push(Monitor.sendStats(io, monitorID, user.id));
|
||||
}
|
||||
|
||||
for (let monitorID in monitorList) {
|
||||
await Monitor.sendStats(io, monitorID, user.id);
|
||||
}
|
||||
await Promise.all(monitorPromises);
|
||||
|
||||
// Set server timezone from client browser if not set
|
||||
// It should be run once only
|
||||
|
@@ -60,7 +60,7 @@ module.exports.apiKeySocketHandler = (socket) => {
|
||||
ok: true,
|
||||
});
|
||||
} catch (e) {
|
||||
log.error("apikeys", e);
|
||||
console.error(e);
|
||||
callback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
|
@@ -1,8 +1,7 @@
|
||||
const { checkLogin, doubleCheckPassword } = require("../util-server");
|
||||
const { checkLogin, setSetting, setting, doubleCheckPassword } = require("../util-server");
|
||||
const { CloudflaredTunnel } = require("node-cloudflared-tunnel");
|
||||
const { UptimeKumaServer } = require("../uptime-kuma-server");
|
||||
const { log } = require("../../src/util");
|
||||
const { Settings } = require("../settings");
|
||||
const io = UptimeKumaServer.getInstance().io;
|
||||
|
||||
const prefix = "cloudflared_";
|
||||
@@ -41,7 +40,7 @@ module.exports.cloudflaredSocketHandler = (socket) => {
|
||||
socket.join("cloudflared");
|
||||
io.to(socket.userID).emit(prefix + "installed", cloudflared.checkInstalled());
|
||||
io.to(socket.userID).emit(prefix + "running", cloudflared.running);
|
||||
io.to(socket.userID).emit(prefix + "token", await Settings.get("cloudflaredTunnelToken"));
|
||||
io.to(socket.userID).emit(prefix + "token", await setting("cloudflaredTunnelToken"));
|
||||
} catch (error) { }
|
||||
});
|
||||
|
||||
@@ -56,7 +55,7 @@ module.exports.cloudflaredSocketHandler = (socket) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
if (token && typeof token === "string") {
|
||||
await Settings.set("cloudflaredTunnelToken", token);
|
||||
await setSetting("cloudflaredTunnelToken", token);
|
||||
cloudflared.token = token;
|
||||
} else {
|
||||
cloudflared.token = null;
|
||||
@@ -68,7 +67,7 @@ module.exports.cloudflaredSocketHandler = (socket) => {
|
||||
socket.on(prefix + "stop", async (currentPassword, callback) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
const disabledAuth = await Settings.get("disableAuth");
|
||||
const disabledAuth = await setting("disableAuth");
|
||||
if (!disabledAuth) {
|
||||
await doubleCheckPassword(socket, currentPassword);
|
||||
}
|
||||
@@ -84,7 +83,7 @@ module.exports.cloudflaredSocketHandler = (socket) => {
|
||||
socket.on(prefix + "removeToken", async () => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
await Settings.set("cloudflaredTunnelToken", "");
|
||||
await setSetting("cloudflaredTunnelToken", "");
|
||||
} catch (error) { }
|
||||
});
|
||||
|
||||
@@ -97,15 +96,15 @@ module.exports.cloudflaredSocketHandler = (socket) => {
|
||||
*/
|
||||
module.exports.autoStart = async (token) => {
|
||||
if (!token) {
|
||||
token = await Settings.get("cloudflaredTunnelToken");
|
||||
token = await setting("cloudflaredTunnelToken");
|
||||
} else {
|
||||
// Override the current token via args or env var
|
||||
await Settings.set("cloudflaredTunnelToken", token);
|
||||
log.info("cloudflare", "Use cloudflared token from args or env var");
|
||||
await setSetting("cloudflaredTunnelToken", token);
|
||||
console.log("Use cloudflared token from args or env var");
|
||||
}
|
||||
|
||||
if (token) {
|
||||
log.info("cloudflare", "Start cloudflared");
|
||||
console.log("Start cloudflared");
|
||||
cloudflared.token = token;
|
||||
cloudflared.start();
|
||||
}
|
||||
|
@@ -67,7 +67,7 @@ module.exports.maintenanceSocketHandler = (socket) => {
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
log.error("maintenance", e);
|
||||
console.error(e);
|
||||
callback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
@@ -177,7 +177,7 @@ module.exports.maintenanceSocketHandler = (socket) => {
|
||||
ok: true,
|
||||
});
|
||||
} catch (e) {
|
||||
log.error("maintenance", e);
|
||||
console.error(e);
|
||||
callback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
@@ -201,7 +201,7 @@ module.exports.maintenanceSocketHandler = (socket) => {
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
log.error("maintenance", e);
|
||||
console.error(e);
|
||||
callback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
@@ -225,7 +225,7 @@ module.exports.maintenanceSocketHandler = (socket) => {
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
log.error("maintenance", e);
|
||||
console.error(e);
|
||||
callback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
|
@@ -1,5 +1,5 @@
|
||||
const { R } = require("redbean-node");
|
||||
const { checkLogin } = require("../util-server");
|
||||
const { checkLogin, setSetting } = require("../util-server");
|
||||
const dayjs = require("dayjs");
|
||||
const { log } = require("../../src/util");
|
||||
const ImageDataURI = require("../image-data-uri");
|
||||
@@ -7,7 +7,6 @@ const Database = require("../database");
|
||||
const apicache = require("../modules/apicache");
|
||||
const StatusPage = require("../model/status_page");
|
||||
const { UptimeKumaServer } = require("../uptime-kuma-server");
|
||||
const { Settings } = require("../settings");
|
||||
|
||||
/**
|
||||
* Socket handlers for status page
|
||||
@@ -234,7 +233,7 @@ module.exports.statusPageSocketHandler = (socket) => {
|
||||
// Also change entry page to new slug if it is the default one, and slug is changed.
|
||||
if (server.entryPage === "statusPage-" + slug && statusPage.slug !== slug) {
|
||||
server.entryPage = "statusPage-" + statusPage.slug;
|
||||
await Settings.set("entryPage", server.entryPage, "general");
|
||||
await setSetting("entryPage", server.entryPage, "general");
|
||||
}
|
||||
|
||||
apicache.clear();
|
||||
@@ -292,7 +291,7 @@ module.exports.statusPageSocketHandler = (socket) => {
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
log.error("socket", error);
|
||||
console.error(error);
|
||||
callback({
|
||||
ok: false,
|
||||
msg: error.message,
|
||||
@@ -314,7 +313,7 @@ module.exports.statusPageSocketHandler = (socket) => {
|
||||
// Reset entry page if it is the default one.
|
||||
if (server.entryPage === "statusPage-" + slug) {
|
||||
server.entryPage = "dashboard";
|
||||
await Settings.set("entryPage", server.entryPage, "general");
|
||||
await setSetting("entryPage", server.entryPage, "general");
|
||||
}
|
||||
|
||||
// No need to delete records from `status_page_cname`, because it has cascade foreign key.
|
||||
|
@@ -205,24 +205,56 @@ class UptimeKumaServer {
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Monitor into list
|
||||
* @param {Socket} socket Socket to send list on
|
||||
* @param {number} monitorID update or deleted monitor id
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async sendUpdateMonitorIntoList(socket, monitorID) {
|
||||
let list = await this.getMonitorJSONList(socket.userID, monitorID);
|
||||
this.io.to(socket.userID).emit("updateMonitorIntoList", list);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Monitor from list
|
||||
* @param {Socket} socket Socket to send list on
|
||||
* @param {number} monitorID update or deleted monitor id
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async sendDeleteMonitorFromList(socket, monitorID) {
|
||||
this.io.to(socket.userID).emit("deleteMonitorFromList", monitorID);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @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) {
|
||||
let result = {};
|
||||
async getMonitorJSONList(userID, monitorID = null) {
|
||||
|
||||
let monitorList = await R.find("monitor", " user_id = ? ORDER BY weight DESC, name", [
|
||||
userID,
|
||||
]);
|
||||
let query = " user_id = ? ";
|
||||
let queryParams = [ userID ];
|
||||
|
||||
for (let monitor of monitorList) {
|
||||
result[monitor.id] = await monitor.toJSON();
|
||||
if (monitorID) {
|
||||
query += "AND id = ? ";
|
||||
queryParams.push(monitorID);
|
||||
}
|
||||
|
||||
let monitorList = await R.find("monitor", query + "ORDER BY weight DESC, name", queryParams);
|
||||
|
||||
const monitorData = monitorList.map(monitor => ({
|
||||
id: monitor.id,
|
||||
active: monitor.active,
|
||||
name: monitor.name,
|
||||
}));
|
||||
const preloadData = await Monitor.preparePreloadData(monitorData);
|
||||
|
||||
const result = {};
|
||||
monitorList.forEach(monitor => result[monitor.id] = monitor.toJSON(preloadData));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -520,3 +552,4 @@ const { DnsMonitorType } = require("./monitor-types/dns");
|
||||
const { MqttMonitorType } = require("./monitor-types/mqtt");
|
||||
const { SNMPMonitorType } = require("./monitor-types/snmp");
|
||||
const { MongodbMonitorType } = require("./monitor-types/mongodb");
|
||||
const Monitor = require("./model/monitor");
|
||||
|
@@ -12,6 +12,7 @@ const { Client } = require("pg");
|
||||
const postgresConParse = require("pg-connection-string").parse;
|
||||
const mysql = require("mysql2");
|
||||
const { NtlmClient } = require("./modules/axios-ntlm/lib/ntlmClient.js");
|
||||
const { Settings } = require("./settings");
|
||||
const grpc = require("@grpc/grpc-js");
|
||||
const protojs = require("protobufjs");
|
||||
const radiusClient = require("node-radius-client");
|
||||
@@ -520,6 +521,46 @@ exports.redisPingAsync = function (dsn, rejectUnauthorized) {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve value of setting based on key
|
||||
* @param {string} key Key of setting to retrieve
|
||||
* @returns {Promise<any>} Value
|
||||
* @deprecated Use await Settings.get(key)
|
||||
*/
|
||||
exports.setting = async function (key) {
|
||||
return await Settings.get(key);
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the specified setting to specified value
|
||||
* @param {string} key Key of setting to set
|
||||
* @param {any} value Value to set to
|
||||
* @param {?string} type Type of setting
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
exports.setSetting = async function (key, value, type = null) {
|
||||
await Settings.set(key, value, type);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get settings based on type
|
||||
* @param {string} type The type of setting
|
||||
* @returns {Promise<Bean>} Settings of requested type
|
||||
*/
|
||||
exports.getSettings = async function (type) {
|
||||
return await Settings.getSettings(type);
|
||||
};
|
||||
|
||||
/**
|
||||
* Set settings based on type
|
||||
* @param {string} type Type of settings to set
|
||||
* @param {object} data Values of settings
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
exports.setSettings = async function (type, data) {
|
||||
await Settings.setSettings(type, data);
|
||||
};
|
||||
|
||||
// ssl-checker by @dyaa
|
||||
//https://github.com/dyaa/ssl-checker/blob/master/src/index.ts
|
||||
|
||||
|
201
src/components/DebugMonitorDialog.vue
Normal file
201
src/components/DebugMonitorDialog.vue
Normal file
@@ -0,0 +1,201 @@
|
||||
<template>
|
||||
<div ref="modal" class="modal fade" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-body">
|
||||
<div v-if="monitor?.type === 'http'">
|
||||
<textarea id="curl-debug" v-model="curlCommand" class="form-control mb-3" readonly wrap="off"></textarea>
|
||||
<button
|
||||
id="debug-copy-btn" class="btn btn-outline-primary position-absolute top-0 end-0 mt-3 me-3 border-0"
|
||||
type="button" @click.stop="copyToClipboard"
|
||||
>
|
||||
<font-awesome-icon icon="copy" />
|
||||
</button>
|
||||
<i18n-t keypath="CurlDebugInfo" tag="p" class="form-text">
|
||||
<template #newiline>
|
||||
<br>
|
||||
</template>
|
||||
<template #firewalls>
|
||||
<a href="https://xkcd.com/2259/" target="_blank">{{ $t('firewalls') }}</a>
|
||||
</template>
|
||||
<template #dns_resolvers>
|
||||
<a
|
||||
href="https://www.reddit.com/r/sysadmin/comments/rxho93/thank_you_for_the_running_its_always_dns_joke_its/"
|
||||
target="_blank"
|
||||
>{{ $t('dns resolvers') }}</a>
|
||||
</template>
|
||||
<template #docker_networks>
|
||||
<a href="https://youtu.be/bKFMS5C4CG0" target="_blank">{{ $t('docker networks') }}</a>
|
||||
</template>
|
||||
</i18n-t>
|
||||
<div
|
||||
v-if="monitor.authMethod === 'oauth2-cc'" class="alert alert-warning d-flex align-items-center gap-2"
|
||||
role="alert"
|
||||
>
|
||||
<div role="img" aria-label="Warning:">⚠️</div>
|
||||
<i18n-t keypath="CurlDebugInfoOAuth2CCUnsupported" tag="div">
|
||||
<template #curl>
|
||||
<code>curl</code>
|
||||
</template>
|
||||
<template #newline>
|
||||
<br>
|
||||
</template>
|
||||
<template #oauth2_bearer>
|
||||
<code>--oauth2-bearer TOKEN</code>
|
||||
</template>
|
||||
</i18n-t>
|
||||
</div>
|
||||
<div v-if="monitor.proxyId" class="alert alert-warning d-flex align-items-center gap-2" role="alert">
|
||||
<div role="img" aria-label="Warning:">⚠️</div>
|
||||
<i18n-t keypath="CurlDebugInfoProxiesUnsupported" tag="div">
|
||||
<template #curl>
|
||||
<code>curl</code>
|
||||
</template>
|
||||
</i18n-t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script>
|
||||
import { Modal } from "bootstrap";
|
||||
import { version } from "../../package.json";
|
||||
import { useToast } from "vue-toastification";
|
||||
const toast = useToast();
|
||||
export default {
|
||||
name: "DebugMonitor",
|
||||
props: {
|
||||
/** Monitor this represents */
|
||||
monitor: {
|
||||
type: Object,
|
||||
default: null,
|
||||
},
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
modal: null,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
curlCommand() {
|
||||
if (this.monitor === null) {
|
||||
return "";
|
||||
}
|
||||
let method = this.monitor.method;
|
||||
if ([ "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS" ].indexOf(method) === -1) {
|
||||
// set to a custom value => could lead to injections
|
||||
method = this.escapeShell(method);
|
||||
}
|
||||
const command = [ "curl", "--verbose", "--head", "--request", method, "\\\n" ];
|
||||
command.push("--user-agent", `'Uptime-Kuma/${version}'`, "\\\n");
|
||||
if (this.monitor.ignoreTls) {
|
||||
command.push("--insecure", "\\\n");
|
||||
}
|
||||
if (this.monitor.headers) {
|
||||
try {
|
||||
for (const [ key, value ] of Object.entries(JSON.parse(this.monitor.headers))) {
|
||||
command.push("--header", `'${this.escapeShellNoQuotes(key)}: ${this.escapeShellNoQuotes(value)}'`, "\\\n");
|
||||
}
|
||||
} catch (e) {
|
||||
command.push("--header", this.escapeShell(this.monitor.headers), "\\\n");
|
||||
}
|
||||
}
|
||||
if (this.monitor.authMethod === "basic") {
|
||||
command.push("--basic", "--user", `'${this.escapeShellNoQuotes(this.monitor.basic_auth_user)}:${this.escapeShellNoQuotes(this.monitor.basic_auth_pass)}'`, "\\\n");
|
||||
} else if (this.monitor.authMethod === "mtls") {
|
||||
command.push("--cacert", this.escapeShell(this.monitor.tlsCa), "\\\n");
|
||||
command.push("--key", this.escapeShell(this.monitor.tlsKey), "\\\n");
|
||||
command.push( "--cert", this.escapeShell(this.monitor.tlsCert), "\\\n");
|
||||
} else if (this.monitor.authMethod === "ntlm") {
|
||||
let domain = "";
|
||||
if (this.monitor.authDomain) {
|
||||
domain = `${this.monitor.authDomain}/`;
|
||||
}
|
||||
command.push("--ntlm", "--user", `'${this.escapeShellNoQuotes(domain)}${this.escapeShellNoQuotes(this.monitor.basic_auth_user)}:${this.escapeShellNoQuotes(this.monitor.basic_auth_pass)}'`, "\\\n");
|
||||
}
|
||||
if (this.monitor.body && this.monitor.httpBodyEncoding === "json") {
|
||||
let json = "";
|
||||
try {
|
||||
// trying to parse the supplied data as json to trim whitespace
|
||||
json = JSON.stringify(JSON.parse(this.monitor.body));
|
||||
} catch (e) {
|
||||
json = this.monitor.body;
|
||||
}
|
||||
command.push("--header", "'Content-Type: application/json'", "\\\n");
|
||||
command.push("--data", this.escapeShell(json), "\\\n");
|
||||
} else if (this.monitor.body && this.monitor.httpBodyEncoding === "xml") {
|
||||
command.push("--headers", "'Content-Type: application/xml'", "\\\n");
|
||||
command.push("--data", this.escapeShell(this.monitor.body), "\\\n");
|
||||
}
|
||||
if (this.monitor.maxredirects) {
|
||||
command.push("--location", "--max-redirs", this.escapeShell(this.monitor.maxredirects), "\\\n");
|
||||
}
|
||||
if (this.monitor.timeout) {
|
||||
command.push("--max-time", this.escapeShell(this.monitor.timeout), "\\\n");
|
||||
}
|
||||
if (this.monitor.maxretries) {
|
||||
command.push("--retry", this.escapeShell(this.monitor.maxretries), "\\\n");
|
||||
}
|
||||
command.push("--url", this.escapeShell(this.monitor.url));
|
||||
return command.join(" ");
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
this.modal = new Modal(this.$refs.modal);
|
||||
},
|
||||
methods: {
|
||||
/**
|
||||
* Show the dialog
|
||||
* @returns {void}
|
||||
*/
|
||||
show() {
|
||||
this.modal.show();
|
||||
},
|
||||
/**
|
||||
* Escape a string for use in a shell
|
||||
* @param {string|number} s string to escape
|
||||
* @returns {string} escaped, quoted string
|
||||
*/
|
||||
escapeShell(s) {
|
||||
if (typeof s == "number") {
|
||||
return s.toString();
|
||||
}
|
||||
return "'" + this.escapeShellNoQuotes(s) + "'";
|
||||
},
|
||||
/**
|
||||
* Escape a string for use in a shell
|
||||
* @param {string} s string to escape
|
||||
* @returns {string} escaped string
|
||||
*/
|
||||
escapeShellNoQuotes(s) {
|
||||
return s.replace(/(['"$`\\])/g, "\\$1");
|
||||
},
|
||||
/**
|
||||
* Copies a value to the clipboard and shows toasts with the success/error
|
||||
* @returns {void}
|
||||
*/
|
||||
async copyToClipboard() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(this.curlCommand);
|
||||
toast.success(this.$t("CopyToClipboardSuccess"));
|
||||
} catch (err) {
|
||||
toast.error(this.$t("CopyToClipboardError", { error: err.message }));
|
||||
}
|
||||
},
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<style lang="scss" scoped>
|
||||
@import "../assets/vars";
|
||||
|
||||
textarea {
|
||||
min-height: 200px;
|
||||
}
|
||||
|
||||
#curl-debug {
|
||||
font-family: monospace;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
@@ -9,6 +9,12 @@
|
||||
<label for="slack-channel" class="form-label">{{ $t("Channel Name") }}</label>
|
||||
<input id="slack-channel-name" v-model="$parent.notification.slackchannel" type="text" class="form-control">
|
||||
|
||||
<label class="form-label">{{ $t("Message format") }}</label>
|
||||
<div class="form-check form-switch">
|
||||
<input id="slack-text-message" v-model="$parent.notification.slackrichmessage" type="checkbox" class="form-check-input">
|
||||
<label for="slack-text-message" class="form-label">{{ $t("Send rich messages") }}</label>
|
||||
</div>
|
||||
|
||||
<div class="form-text">
|
||||
<span style="color: red;"><sup>*</sup></span>{{ $t("Required") }}
|
||||
<i18n-t tag="p" keypath="aboutWebhooks" style="margin-top: 8px;">
|
||||
|
@@ -82,6 +82,7 @@
|
||||
"resendEveryXTimes": "Resend every {0} times",
|
||||
"resendDisabled": "Resend disabled",
|
||||
"retriesDescription": "Maximum retries before the service is marked as down and a notification is sent",
|
||||
"ignoredTLSError": "TLS/SSL errors have been ignored",
|
||||
"ignoreTLSError": "Ignore TLS/SSL errors for HTTPS websites",
|
||||
"ignoreTLSErrorGeneral": "Ignore TLS/SSL error for connection",
|
||||
"upsideDownModeDescription": "Flip the status upside down. If the service is reachable, it is DOWN.",
|
||||
@@ -96,6 +97,8 @@
|
||||
"pushOthers": "Others",
|
||||
"programmingLanguages": "Programming Languages",
|
||||
"Save": "Save",
|
||||
"Debug": "Debug",
|
||||
"Copy": "Copy",
|
||||
"Notifications": "Notifications",
|
||||
"Not available, please setup.": "Not available, please set up.",
|
||||
"Setup Notification": "Set Up Notification",
|
||||
@@ -248,6 +251,14 @@
|
||||
"PushUrl": "Push URL",
|
||||
"HeadersInvalidFormat": "The request headers are not valid JSON: ",
|
||||
"BodyInvalidFormat": "The request body is not valid JSON: ",
|
||||
"CopyToClipboardError": "Couldn't copy to clipbard: {error}",
|
||||
"CopyToClipboardSuccess": "Copied!",
|
||||
"CurlDebugInfo": "To debug the monitor, you can either paste this into your own machines terminal or into the machines terminal which uptime kuma is running on and see what you are requesting.{newiline}Please be aware of networking differences like {firewalls}, {dns_resolvers} or {docker_networks}.",
|
||||
"firewalls": "firewalls",
|
||||
"dns resolvers": "dns resolvers",
|
||||
"docker networks": "docker networks",
|
||||
"CurlDebugInfoOAuth2CCUnsupported": "Full oauth client credential flow is not supported in {curl}.{newline}Please get a bearer token and pass it via the {oauth2_bearer} option.",
|
||||
"CurlDebugInfoProxiesUnsupported": "Proxy support in the above {curl} command is currently not implemented.",
|
||||
"Monitor History": "Monitor History",
|
||||
"clearDataOlderThan": "Keep monitor history data for {0} days.",
|
||||
"PasswordsDoNotMatch": "Passwords do not match.",
|
||||
@@ -884,6 +895,8 @@
|
||||
"cacheBusterParamDescription": "Randomly generated parameter to skip caches.",
|
||||
"gamedigGuessPort": "Gamedig: Guess Port",
|
||||
"gamedigGuessPortDescription": "The port used by Valve Server Query Protocol may be different from the client port. Try this if the monitor cannot connect to your server.",
|
||||
"Message format": "Message format",
|
||||
"Send rich messages": "Send rich messages",
|
||||
"Bitrix24 Webhook URL": "Bitrix24 Webhook URL",
|
||||
"wayToGetBitrix24Webhook": "You can create a webhook by following the steps at {0}",
|
||||
"bitrix24SupportUserID": "Enter your user ID in Bitrix24. You can find out the ID from the link by going to the user's profile.",
|
||||
|
@@ -141,19 +141,23 @@ export default {
|
||||
});
|
||||
|
||||
socket.on("monitorList", (data) => {
|
||||
// Add Helper function
|
||||
Object.entries(data).forEach(([ monitorID, monitor ]) => {
|
||||
monitor.getUrl = () => {
|
||||
try {
|
||||
return new URL(monitor.url);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
});
|
||||
this.assignMonitorUrlParser(data);
|
||||
this.monitorList = data;
|
||||
});
|
||||
|
||||
socket.on("updateMonitorIntoList", (data) => {
|
||||
this.assignMonitorUrlParser(data);
|
||||
Object.entries(data).forEach(([ monitorID, updatedMonitor ]) => {
|
||||
this.monitorList[monitorID] = updatedMonitor;
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("deleteMonitorFromList", (monitorID) => {
|
||||
if (this.monitorList[monitorID]) {
|
||||
delete this.monitorList[monitorID];
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("monitorTypeList", (data) => {
|
||||
this.monitorTypeList = data;
|
||||
});
|
||||
@@ -289,6 +293,23 @@ export default {
|
||||
location.reload();
|
||||
});
|
||||
},
|
||||
/**
|
||||
* parse all urls from list.
|
||||
* @param {object} data Monitor data to modify
|
||||
* @returns {object} list
|
||||
*/
|
||||
assignMonitorUrlParser(data) {
|
||||
Object.entries(data).forEach(([ monitorID, monitor ]) => {
|
||||
monitor.getUrl = () => {
|
||||
try {
|
||||
return new URL(monitor.url);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* The storage currently in use
|
||||
|
@@ -565,8 +565,8 @@
|
||||
|
||||
<h2 v-if="monitor.type !== 'push'" class="mt-5 mb-2">{{ $t("Advanced") }}</h2>
|
||||
|
||||
<div v-if="monitor.type === 'http' || monitor.type === 'keyword' || monitor.type === 'json-query' " class="my-3 form-check">
|
||||
<input id="expiry-notification" v-model="monitor.expiryNotification" class="form-check-input" type="checkbox">
|
||||
<div v-if="monitor.type === 'http' || monitor.type === 'keyword' || monitor.type === 'json-query' " class="my-3 form-check" :title="monitor.ignoreTls ? $t('ignoredTLSError') : ''">
|
||||
<input id="expiry-notification" v-model="monitor.expiryNotification" class="form-check-input" type="checkbox" :disabled="monitor.ignoreTls">
|
||||
<label class="form-check-label" for="expiry-notification">
|
||||
{{ $t("Certificate Expiry Notification") }}
|
||||
</label>
|
||||
@@ -982,13 +982,23 @@
|
||||
<div class="fixed-bottom-bar p-3">
|
||||
<button
|
||||
id="monitor-submit-btn"
|
||||
class="btn btn-primary"
|
||||
class="btn btn-primary me-2"
|
||||
type="submit"
|
||||
:disabled="processing"
|
||||
data-testid="save-button"
|
||||
>
|
||||
{{ $t("Save") }}
|
||||
</button>
|
||||
<button
|
||||
v-if="monitor.type === 'http'"
|
||||
id="monitor-debug-btn"
|
||||
class="btn btn-outline-primary"
|
||||
type="button"
|
||||
:disabled="processing"
|
||||
@click="$refs.debugMonitorDialog.show()"
|
||||
>
|
||||
{{ $t("Debug") }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -1000,6 +1010,7 @@
|
||||
<RemoteBrowserDialog ref="remoteBrowserDialog" />
|
||||
</div>
|
||||
</transition>
|
||||
<DebugMonitorDialog ref="debugMonitorDialog" :monitor="monitor" />
|
||||
</template>
|
||||
|
||||
<script>
|
||||
@@ -1017,8 +1028,9 @@ import { genSecret, isDev, MAX_INTERVAL_SECOND, MIN_INTERVAL_SECOND, sleep } fro
|
||||
import { hostNameRegexPattern } from "../util-frontend";
|
||||
import HiddenInput from "../components/HiddenInput.vue";
|
||||
import EditMonitorConditions from "../components/EditMonitorConditions.vue";
|
||||
import DebugMonitorDialog from "../components/DebugMonitorDialog.vue";
|
||||
|
||||
const toast = useToast;
|
||||
const toast = useToast();
|
||||
|
||||
const pushTokenLength = 32;
|
||||
|
||||
@@ -1066,6 +1078,7 @@ const monitorDefaults = {
|
||||
|
||||
export default {
|
||||
components: {
|
||||
DebugMonitorDialog,
|
||||
HiddenInput,
|
||||
ActionSelect,
|
||||
ProxyDialog,
|
||||
@@ -1081,6 +1094,7 @@ export default {
|
||||
|
||||
data() {
|
||||
return {
|
||||
modal: null,
|
||||
minInterval: MIN_INTERVAL_SECOND,
|
||||
maxInterval: MAX_INTERVAL_SECOND,
|
||||
processing: false,
|
||||
@@ -1107,11 +1121,9 @@ export default {
|
||||
},
|
||||
|
||||
computed: {
|
||||
|
||||
ipRegex() {
|
||||
|
||||
// Allow to test with simple dns server with port (127.0.0.1:5300)
|
||||
if (! isDev) {
|
||||
if (!isDev) {
|
||||
return this.ipRegexPattern;
|
||||
}
|
||||
return null;
|
||||
@@ -1456,6 +1468,12 @@ message HealthCheckResponse {
|
||||
}
|
||||
this.monitor.game = newGameObject.keys[0];
|
||||
},
|
||||
|
||||
"monitor.ignoreTls"(newVal) {
|
||||
if (newVal) {
|
||||
this.monitor.expiryNotification = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
this.init();
|
||||
@@ -1689,7 +1707,6 @@ message HealthCheckResponse {
|
||||
await this.startParentGroupMonitor();
|
||||
}
|
||||
this.processing = false;
|
||||
this.$root.getMonitorList();
|
||||
this.$router.push("/dashboard/" + res.monitorID);
|
||||
} else {
|
||||
this.processing = false;
|
||||
@@ -1786,4 +1803,5 @@ message HealthCheckResponse {
|
||||
textarea {
|
||||
min-height: 200px;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
@@ -68,15 +68,17 @@ const routes = [
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "/add",
|
||||
component: EditMonitor,
|
||||
children: [
|
||||
{
|
||||
path: "/clone/:id",
|
||||
component: EditMonitor,
|
||||
},
|
||||
{
|
||||
path: "/add",
|
||||
component: EditMonitor,
|
||||
},
|
||||
],
|
||||
]
|
||||
},
|
||||
{
|
||||
path: "/list",
|
||||
|
71
src/util.js
71
src/util.js
@@ -8,34 +8,17 @@
|
||||
// Backend uses the compiled file util.js
|
||||
// Frontend uses util.ts
|
||||
*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
var _a;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.sleep = exports.flipStatus = exports.badgeConstants = exports.CONSOLE_STYLE_BgGray = exports.CONSOLE_STYLE_BgWhite = exports.CONSOLE_STYLE_BgCyan = exports.CONSOLE_STYLE_BgMagenta = exports.CONSOLE_STYLE_BgBlue = exports.CONSOLE_STYLE_BgYellow = exports.CONSOLE_STYLE_BgGreen = exports.CONSOLE_STYLE_BgRed = exports.CONSOLE_STYLE_BgBlack = exports.CONSOLE_STYLE_FgPink = exports.CONSOLE_STYLE_FgBrown = exports.CONSOLE_STYLE_FgViolet = exports.CONSOLE_STYLE_FgLightBlue = exports.CONSOLE_STYLE_FgLightGreen = exports.CONSOLE_STYLE_FgOrange = exports.CONSOLE_STYLE_FgGray = exports.CONSOLE_STYLE_FgWhite = exports.CONSOLE_STYLE_FgCyan = exports.CONSOLE_STYLE_FgMagenta = exports.CONSOLE_STYLE_FgBlue = exports.CONSOLE_STYLE_FgYellow = exports.CONSOLE_STYLE_FgGreen = exports.CONSOLE_STYLE_FgRed = exports.CONSOLE_STYLE_FgBlack = exports.CONSOLE_STYLE_Hidden = exports.CONSOLE_STYLE_Reverse = exports.CONSOLE_STYLE_Blink = exports.CONSOLE_STYLE_Underscore = exports.CONSOLE_STYLE_Dim = exports.CONSOLE_STYLE_Bright = exports.CONSOLE_STYLE_Reset = exports.MIN_INTERVAL_SECOND = exports.MAX_INTERVAL_SECOND = exports.SQL_DATETIME_FORMAT_WITHOUT_SECOND = exports.SQL_DATETIME_FORMAT = exports.SQL_DATE_FORMAT = exports.STATUS_PAGE_MAINTENANCE = exports.STATUS_PAGE_PARTIAL_DOWN = exports.STATUS_PAGE_ALL_UP = exports.STATUS_PAGE_ALL_DOWN = exports.MAINTENANCE = exports.PENDING = exports.UP = exports.DOWN = exports.appName = exports.isNode = exports.isDev = void 0;
|
||||
exports.evaluateJsonQuery = exports.intHash = exports.localToUTC = exports.utcToLocal = exports.utcToISODateTime = exports.isoToUTCDateTime = exports.parseTimeFromTimeObject = exports.parseTimeObject = exports.getMaintenanceRelativeURL = exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log = exports.ucfirst = void 0;
|
||||
exports.evaluateJsonQuery = exports.intHash = exports.localToUTC = exports.utcToLocal = exports.utcToISODateTime = exports.isoToUTCDateTime = exports.parseTimeFromTimeObject = exports.parseTimeObject = exports.getMaintenanceRelativeURL = exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log = exports.debug = exports.ucfirst = void 0;
|
||||
exports.intHash = exports.localToUTC = exports.utcToLocal = exports.utcToISODateTime = exports.isoToUTCDateTime = exports.parseTimeFromTimeObject = exports.parseTimeObject = exports.getMaintenanceRelativeURL = exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log = exports.debug = exports.ucfirst = void 0;
|
||||
const dayjs_1 = __importDefault(require("dayjs"));
|
||||
const jsonata = __importStar(require("jsonata"));
|
||||
const dayjs = require("dayjs");
|
||||
const jsonata = require("jsonata");
|
||||
exports.isDev = process.env.NODE_ENV === "development";
|
||||
exports.isNode = typeof process !== "undefined" && ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node);
|
||||
exports.appName = "Uptime Kuma";
|
||||
@@ -83,6 +66,7 @@ exports.CONSOLE_STYLE_BgMagenta = "\x1b[45m";
|
||||
exports.CONSOLE_STYLE_BgCyan = "\x1b[46m";
|
||||
exports.CONSOLE_STYLE_BgWhite = "\x1b[47m";
|
||||
exports.CONSOLE_STYLE_BgGray = "\x1b[100m";
|
||||
|
||||
const consoleModuleColors = [
|
||||
exports.CONSOLE_STYLE_FgCyan,
|
||||
exports.CONSOLE_STYLE_FgGreen,
|
||||
@@ -141,6 +125,10 @@ function ucfirst(str) {
|
||||
return firstLetter.toUpperCase() + str.substr(1);
|
||||
}
|
||||
exports.ucfirst = ucfirst;
|
||||
function debug(msg) {
|
||||
exports.log.log("", msg, "debug");
|
||||
}
|
||||
exports.debug = debug;
|
||||
class Logger {
|
||||
constructor() {
|
||||
this.hideLog = {
|
||||
@@ -168,6 +156,8 @@ class Logger {
|
||||
if (this.hideLog[level] && this.hideLog[level].includes(module.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
module = module.toUpperCase();
|
||||
level = level.toUpperCase();
|
||||
let now;
|
||||
if (dayjs_1.default.tz) {
|
||||
now = dayjs_1.default.tz(new Date()).format();
|
||||
@@ -177,20 +167,10 @@ class Logger {
|
||||
}
|
||||
const levelColor = consoleLevelColors[level];
|
||||
const moduleColor = consoleModuleColors[intHash(module, consoleModuleColors.length)];
|
||||
let timePart = now;
|
||||
let modulePart = module;
|
||||
let levelPart = level;
|
||||
let msgPart = msg;
|
||||
if (process.env.UPTIME_KUMA_LOG_FORMAT === "json") {
|
||||
console.log(JSON.stringify({
|
||||
time: timePart,
|
||||
module: modulePart,
|
||||
level: levelPart,
|
||||
msg: typeof msg === "string" ? msg : JSON.stringify(msg),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
module = module.toUpperCase();
|
||||
let timePart;
|
||||
let modulePart;
|
||||
let levelPart;
|
||||
let msgPart;
|
||||
if (exports.isNode) {
|
||||
switch (level) {
|
||||
case "DEBUG":
|
||||
@@ -207,17 +187,28 @@ class Logger {
|
||||
if (typeof msg === "string") {
|
||||
msgPart = exports.CONSOLE_STYLE_FgRed + msg + exports.CONSOLE_STYLE_Reset;
|
||||
}
|
||||
else {
|
||||
msgPart = msg;
|
||||
}
|
||||
break;
|
||||
case "DEBUG":
|
||||
if (typeof msg === "string") {
|
||||
msgPart = exports.CONSOLE_STYLE_FgGray + msg + exports.CONSOLE_STYLE_Reset;
|
||||
}
|
||||
else {
|
||||
msgPart = msg;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
msgPart = msg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
timePart = now;
|
||||
modulePart = `[${module}]`;
|
||||
levelPart = `${level}:`;
|
||||
msgPart = msg;
|
||||
}
|
||||
switch (level) {
|
||||
case "ERROR":
|
||||
@@ -240,23 +231,23 @@ class Logger {
|
||||
}
|
||||
}
|
||||
info(module, msg) {
|
||||
this.log(module, msg, "INFO");
|
||||
this.log(module, msg, "info");
|
||||
}
|
||||
warn(module, msg) {
|
||||
this.log(module, msg, "WARN");
|
||||
this.log(module, msg, "warn");
|
||||
}
|
||||
error(module, msg) {
|
||||
this.log(module, msg, "ERROR");
|
||||
this.log(module, msg, "error");
|
||||
}
|
||||
debug(module, msg) {
|
||||
this.log(module, msg, "DEBUG");
|
||||
this.log(module, msg, "debug");
|
||||
}
|
||||
exception(module, exception, msg) {
|
||||
let finalMessage = exception;
|
||||
if (msg) {
|
||||
finalMessage = `${msg}: ${exception}`;
|
||||
}
|
||||
this.log(module, finalMessage, "ERROR");
|
||||
this.log(module, finalMessage, "error");
|
||||
}
|
||||
}
|
||||
exports.log = new Logger();
|
||||
|
67
src/util.ts
67
src/util.ts
@@ -156,6 +156,15 @@ export function ucfirst(str: string) {
|
||||
return firstLetter.toUpperCase() + str.substr(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use log.debug (https://github.com/louislam/uptime-kuma/pull/910)
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
export function debug(msg: unknown) {
|
||||
log.log("", msg, "debug");
|
||||
}
|
||||
|
||||
class Logger {
|
||||
|
||||
/**
|
||||
@@ -197,13 +206,12 @@ class Logger {
|
||||
|
||||
/**
|
||||
* Write a message to the log
|
||||
* @private
|
||||
* @param module The module the log comes from
|
||||
* @param msg Message to write
|
||||
* @param level {"INFO"|"WARN"|"ERROR"|"DEBUG"} Log level
|
||||
* @param level Log level. One of INFO, WARN, ERROR, DEBUG or can be customized.
|
||||
* @returns {void}
|
||||
*/
|
||||
log(module: string, msg: unknown, level: "INFO"|"WARN"|"ERROR"|"DEBUG"): void {
|
||||
log(module: string, msg: any, level: string) {
|
||||
if (level === "DEBUG" && !isDev) {
|
||||
return;
|
||||
}
|
||||
@@ -212,6 +220,9 @@ class Logger {
|
||||
return;
|
||||
}
|
||||
|
||||
module = module.toUpperCase();
|
||||
level = level.toUpperCase();
|
||||
|
||||
let now;
|
||||
if (dayjs.tz) {
|
||||
now = dayjs.tz(new Date()).format();
|
||||
@@ -222,23 +233,10 @@ class Logger {
|
||||
const levelColor = consoleLevelColors[level];
|
||||
const moduleColor = consoleModuleColors[intHash(module, consoleModuleColors.length)];
|
||||
|
||||
let timePart: string = now;
|
||||
let modulePart: string = module;
|
||||
let levelPart: string = level;
|
||||
let msgPart: unknown = msg;
|
||||
|
||||
if (process.env.UPTIME_KUMA_LOG_FORMAT === "json") {
|
||||
console.log(JSON.stringify({
|
||||
time: timePart,
|
||||
module: modulePart,
|
||||
level: levelPart,
|
||||
msg: typeof msg === "string" ? msg : JSON.stringify(msg),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
// Console rendering:
|
||||
module = module.toUpperCase();
|
||||
let timePart: string;
|
||||
let modulePart: string;
|
||||
let levelPart: string;
|
||||
let msgPart: string;
|
||||
|
||||
if (isNode) {
|
||||
// Add console colors
|
||||
@@ -259,18 +257,27 @@ class Logger {
|
||||
case "ERROR":
|
||||
if (typeof msg === "string") {
|
||||
msgPart = CONSOLE_STYLE_FgRed + msg + CONSOLE_STYLE_Reset;
|
||||
} else {
|
||||
msgPart = msg;
|
||||
}
|
||||
break;
|
||||
case "DEBUG":
|
||||
if (typeof msg === "string") {
|
||||
msgPart = CONSOLE_STYLE_FgGray + msg + CONSOLE_STYLE_Reset;
|
||||
} else {
|
||||
msgPart = msg;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
msgPart = msg;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// No console colors
|
||||
timePart = now;
|
||||
modulePart = `[${module}]`;
|
||||
levelPart = `${level}:`;
|
||||
msgPart = msg;
|
||||
}
|
||||
|
||||
// Write to console
|
||||
@@ -301,8 +308,8 @@ class Logger {
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
info(module: string, msg: string): void {
|
||||
this.log(module, msg, "INFO");
|
||||
info(module: string, msg: unknown) {
|
||||
this.log(module, msg, "info");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -311,8 +318,8 @@ class Logger {
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
warn(module: string, msg: string): void {
|
||||
this.log(module, msg, "WARN");
|
||||
warn(module: string, msg: unknown) {
|
||||
this.log(module, msg, "warn");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -321,8 +328,8 @@ class Logger {
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
error(module: string, msg: string): void {
|
||||
this.log(module, msg, "ERROR");
|
||||
error(module: string, msg: unknown) {
|
||||
this.log(module, msg, "error");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -331,8 +338,8 @@ class Logger {
|
||||
* @param msg Message to write
|
||||
* @returns {void}
|
||||
*/
|
||||
debug(module: string, msg: string): void {
|
||||
this.log(module, msg, "DEBUG");
|
||||
debug(module: string, msg: unknown) {
|
||||
this.log(module, msg, "debug");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -349,7 +356,7 @@ class Logger {
|
||||
finalMessage = `${msg}: ${exception}`;
|
||||
}
|
||||
|
||||
this.log(module, finalMessage, "ERROR");
|
||||
this.log(module, finalMessage, "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,7 +400,7 @@ export class TimeLogger {
|
||||
* @param name Name of monitor
|
||||
* @returns {void}
|
||||
*/
|
||||
print(name: string): void {
|
||||
print(name: string) {
|
||||
if (isDev && process.env.TIMELOGGER === "1") {
|
||||
console.log(name + ": " + (dayjs().valueOf() - this.startTime) + "ms");
|
||||
}
|
||||
|
@@ -1,102 +0,0 @@
|
||||
const { describe, test } = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const { HiveMQContainer } = require("@testcontainers/hivemq");
|
||||
const mqtt = require("mqtt");
|
||||
const { MqttMonitorType } = require("../../server/monitor-types/mqtt");
|
||||
const { UP, PENDING } = require("../../src/util");
|
||||
|
||||
/**
|
||||
* Runs an MQTT test with the
|
||||
* @param {string} mqttSuccessMessage the message that the monitor expects
|
||||
* @param {null|"keyword"|"json-query"} mqttCheckType the type of check we perform
|
||||
* @param {string} receivedMessage what message is recieved from the mqtt channel
|
||||
* @returns {Promise<Heartbeat>} the heartbeat produced by the check
|
||||
*/
|
||||
async function testMqtt(mqttSuccessMessage, mqttCheckType, receivedMessage) {
|
||||
const hiveMQContainer = await new HiveMQContainer().start();
|
||||
const connectionString = hiveMQContainer.getConnectionString();
|
||||
const mqttMonitorType = new MqttMonitorType();
|
||||
const monitor = {
|
||||
jsonPath: "firstProp", // always return firstProp for the json-query monitor
|
||||
hostname: connectionString.split(":", 2).join(":"),
|
||||
mqttTopic: "test",
|
||||
port: connectionString.split(":")[2],
|
||||
mqttUsername: null,
|
||||
mqttPassword: null,
|
||||
interval: 20, // controls the timeout
|
||||
mqttSuccessMessage: mqttSuccessMessage, // for keywords
|
||||
expectedValue: mqttSuccessMessage, // for json-query
|
||||
mqttCheckType: mqttCheckType,
|
||||
};
|
||||
const heartbeat = {
|
||||
msg: "",
|
||||
status: PENDING,
|
||||
};
|
||||
|
||||
const testMqttClient = mqtt.connect(hiveMQContainer.getConnectionString());
|
||||
testMqttClient.on("connect", () => {
|
||||
testMqttClient.subscribe("test", (error) => {
|
||||
if (!error) {
|
||||
testMqttClient.publish("test", receivedMessage);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
await mqttMonitorType.check(monitor, heartbeat, {});
|
||||
} finally {
|
||||
testMqttClient.end();
|
||||
hiveMQContainer.stop();
|
||||
}
|
||||
return heartbeat;
|
||||
}
|
||||
|
||||
describe("MqttMonitorType", {
|
||||
concurrency: true,
|
||||
skip: !!process.env.CI && (process.platform !== "linux" || process.arch !== "x64")
|
||||
}, () => {
|
||||
test("valid keywords (type=default)", async () => {
|
||||
const heartbeat = await testMqtt("KEYWORD", null, "-> KEYWORD <-");
|
||||
assert.strictEqual(heartbeat.status, UP);
|
||||
assert.strictEqual(heartbeat.msg, "Topic: test; Message: -> KEYWORD <-");
|
||||
});
|
||||
|
||||
test("valid keywords (type=keyword)", async () => {
|
||||
const heartbeat = await testMqtt("KEYWORD", "keyword", "-> KEYWORD <-");
|
||||
assert.strictEqual(heartbeat.status, UP);
|
||||
assert.strictEqual(heartbeat.msg, "Topic: test; Message: -> KEYWORD <-");
|
||||
});
|
||||
test("invalid keywords (type=default)", async () => {
|
||||
await assert.rejects(
|
||||
testMqtt("NOT_PRESENT", null, "-> KEYWORD <-"),
|
||||
new Error("Message Mismatch - Topic: test; Message: -> KEYWORD <-"),
|
||||
);
|
||||
});
|
||||
|
||||
test("invalid keyword (type=keyword)", async () => {
|
||||
await assert.rejects(
|
||||
testMqtt("NOT_PRESENT", "keyword", "-> KEYWORD <-"),
|
||||
new Error("Message Mismatch - Topic: test; Message: -> KEYWORD <-"),
|
||||
);
|
||||
});
|
||||
test("valid json-query", async () => {
|
||||
// works because the monitors' jsonPath is hard-coded to "firstProp"
|
||||
const heartbeat = await testMqtt("present", "json-query", "{\"firstProp\":\"present\"}");
|
||||
assert.strictEqual(heartbeat.status, UP);
|
||||
assert.strictEqual(heartbeat.msg, "Message received, expected value is found");
|
||||
});
|
||||
test("invalid (because query fails) json-query", async () => {
|
||||
// works because the monitors' jsonPath is hard-coded to "firstProp"
|
||||
await assert.rejects(
|
||||
testMqtt("[not_relevant]", "json-query", "{}"),
|
||||
new Error("Message received but value is not equal to expected value, value was: [undefined]"),
|
||||
);
|
||||
});
|
||||
test("invalid (because successMessage fails) json-query", async () => {
|
||||
// works because the monitors' jsonPath is hard-coded to "firstProp"
|
||||
await assert.rejects(
|
||||
testMqtt("[wrong_success_messsage]", "json-query", "{\"firstProp\":\"present\"}"),
|
||||
new Error("Message received but value is not equal to expected value, value was: [present]")
|
||||
);
|
||||
});
|
||||
});
|
@@ -1,10 +1,10 @@
|
||||
const fs = require("fs");
|
||||
const rmSync = require("../extra/fs-rmSync.js");
|
||||
|
||||
const path = "./data/test";
|
||||
|
||||
if (fs.existsSync(path)) {
|
||||
rmSync(path, {
|
||||
fs.rmSync(path, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
|
Reference in New Issue
Block a user