This commit is contained in:
Alvaro Torres committed 2024-08-14 10:28:14 -05:00
commit 0dfe44ac61
41 files changed
+732 -498

No files matched your search

+37
View File
@@ -7,6 +7,7 @@ const {
getMonitorsByUserIdQueryValidation,
} = require("../validation/joi");
const sslChecker = require("ssl-checker");
const SERVICE_NAME = "monitorController";
const { errorMessages, successMessages } = require("../utils/messages");
const { runInNewContext } = require("vm");
@@ -65,6 +66,41 @@ const getMonitorStatsById = async (req, res, next) => {
}
};
const getMonitorCertificate = async (req, res, next) => {
try {
//validation
} catch (error) {
error.status = 422;
error.message =
error.details?.[0]?.message || error.message || "Validation Error";
next(error);
}
try {
const monitor = await req.db.getMonitorById(req, res);
const monitorUrl = new URL(monitor.url);
const certificate = await sslChecker(monitorUrl.hostname);
if (certificate && certificate.validTo) {
return res.json({
success: true,
msg: successMessages.MONITOR_CERTIFICATE,
data: {
certificateDate: new Date(certificate.validTo).toLocaleDateString(),
},
});
} else {
return res.json({
success: true,
msg: successMessages.MONITOR_CERTIFICATE,
data: { certificateDate: "N/A" },
});
}
} catch (error) {
error.service = SERVICE_NAME;
next(error);
}
};
/**
* Returns monitor with matching ID
* @async
@@ -302,6 +338,7 @@ const editMonitor = async (req, res, next) => {
module.exports = {
getAllMonitors,
getMonitorStatsById,
getMonitorCertificate,
getMonitorById,
getMonitorsByUserId,
createMonitor,
+31 -24
View File
@@ -149,7 +149,7 @@ const getMonitorStatsById = async (req) => {
try {
const { monitorId } = req.params;
let { status, limit, sortOrder, filter, numToDisplay, normalize } =
let { status, limit, sortOrder, dateRange, numToDisplay, normalize } =
req.query;
// This effectively removes limit, returning all checks
@@ -161,37 +161,44 @@ const getMonitorStatsById = async (req) => {
// Get monitor
const monitor = await Monitor.findById(monitorId);
// Determine if this is a pagespeed monitor or an http/ping monitor
let model =
monitor.type === "http" || monitor.type === "ping"
? Check
: PageSpeedCheck;
// Build monitor stats object
const monitorStats = {
...monitor.toObject(),
};
// Get all checks to calculate stats
// Start building query
const checksQuery = { monitorId: monitor._id };
// Get all checks
const checksAll = await model.find(checksQuery).sort({
createdAt: sortOrder,
});
if (monitor.type === "http" || monitor.type === "ping") {
// Get checks in 24 hours
checksQuery.createdAt = { $gte: filterLookup.day };
const checks24Hours = await model.find(checksQuery).sort({
createdAt: sortOrder,
});
// Get checks in 30 days
checksQuery.createdAt = { $gte: filterLookup.month };
const checks30Days = await model.find(checksQuery).sort({
createdAt: sortOrder,
});
// Get checks in 60 mins
checksQuery.createdAt = { $gte: filterLookup.hour };
const checks60Mins = await model
.find(checksQuery)
.sort({ createdAt: sortOrder });
const checksQuery24Hours = {
...checksQuery,
createdAt: { $gte: filterLookup.day },
};
const checksQuery30Days = {
...checksQuery,
createdAt: { $gte: filterLookup.month },
};
const checksQuery60Mins = {
...checksQuery,
createdAt: { $gte: filterLookup.hour },
};
const [checks24Hours, checks30Days, checks60Mins] = await Promise.all([
model.find(checksQuery24Hours).sort({ createdAt: sortOrder }),
model.find(checksQuery30Days).sort({ createdAt: sortOrder }),
model.find(checksQuery60Mins).sort({ createdAt: sortOrder }),
]);
// HTTP/PING Specific stats
monitorStats.avgResponseTime24hours =
@@ -202,14 +209,13 @@ const getMonitorStatsById = async (req) => {
}
//Get checks for dateRange
if (status !== undefined) {
checksQuery.status = status;
}
// Filter checks by "day", "week", or "month"
if (filter !== undefined) {
checksQuery.createdAt = { $gte: filterLookup[filter] };
if (dateRange !== undefined) {
checksQuery.createdAt = { $gte: filterLookup[dateRange] };
}
let dateRangeChecks = await model
@@ -219,6 +225,8 @@ const getMonitorStatsById = async (req) => {
})
.limit(limit);
const incidents = getIncidents(dateRangeChecks);
// If more than numToDisplay checks, pick every nth check
if (
numToDisplay !== undefined &&
@@ -233,10 +241,9 @@ const getMonitorStatsById = async (req) => {
if (normalize !== undefined) {
dateRangeChecks = NormalizeData(dateRangeChecks, 1, 100);
}
// Add common stats
const incidents = getIncidents(dateRangeChecks);
monitorStats.uptimeDuration = caluclteUptimeDuration(checksAll);
// Add common stats and stats that depend on the dateRange
monitorStats.uptimeDuration = calculateUptimeDuration(checksAll);
monitorStats.lastChecked = getLastChecked(checksAll);
monitorStats.latestResponseTime = getLatestResponseTime(checksAll);
monitorStats.incidents = incidents;
+30 -34
View File
@@ -57,6 +57,7 @@ const CheckSchema = mongoose.Schema(
*
* @type {Date}
*/
expiry: {
type: Date,
default: Date.now,
@@ -84,43 +85,38 @@ CheckSchema.pre("save", async function (next) {
});
// Check if there are any notifications
if (notifications && notifications.length > 0) {
// Only send email if monitor status has changed
if (monitor.status !== this.status) {
const emailService = new EmailService();
if (monitor.status === true && this.status === false) {
// Notify users that the monitor is down
for (const notification of notifications) {
if (notification.type === "email") {
await emailService.buildAndSendEmail(
"serverIsDownTemplate",
{ monitorName: monitor.name, monitorUrl: monitor.url },
notification.address,
`Monitor ${monitor.name} is down`
);
}
}
}
// Only send email if monitor status has changed
if (monitor.status !== this.status) {
const emailService = new EmailService();
if (monitor.status === false && this.status === true) {
// Notify users that the monitor is up
for (const notification of notifications) {
if (notification.type === "email") {
await emailService.buildAndSendEmail(
"serverIsUpTemplate",
{ monitorName: monitor.name, monitorUrl: monitor.url },
notification.address,
`Monitor ${monitor.name} is back up`
);
}
}
}
// Update monitor status
monitor.status = this.status;
await monitor.save();
let template = "";
let status = "";
if (monitor.status === true && this.status === false) {
template = "serverIsDownTemplate";
status = "down";
}
if (monitor.status === false && this.status === true) {
// Notify users that the monitor is up
template = "serverIsUpTemplate";
status = "up";
}
for (const notification of notifications) {
if (notification.type === "email") {
await emailService.buildAndSendEmail(
template,
{ monitorName: monitor.name, monitorUrl: monitor.url },
notification.address,
`Monitor ${monitor.name} is ${status}`
);
}
}
// Update monitor status
monitor.status = this.status;
await monitor.save();
}
}
} catch (error) {
+10 -4
View File
@@ -27,6 +27,7 @@
"nodemailer": "^6.9.14",
"ping": "0.4.4",
"sharp": "0.33.4",
"ssl-checker": "2.0.10",
"winston": "^3.13.0"
},
"devDependencies": {
@@ -996,10 +997,9 @@
"license": "MIT"
},
"node_modules/axios": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.3.1.tgz",
"integrity": "sha512-78pWJsQTceInlyaeBQeYZ/QgZeWS8hGeKiIJiDKQe3hEyBb7sEMq0K4gjx+Va6WHTYO4zI/RRl8qGRzn0YMadA==",
"license": "MIT",
"version": "1.7.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz",
"integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==",
"dependencies": {
"follow-redirects": "^1.15.0",
"form-data": "^4.0.0",
@@ -5046,6 +5046,12 @@
"memory-pager": "^1.0.2"
}
},
"node_modules/ssl-checker": {
"version": "2.0.10",
"resolved": "https://registry.npmjs.org/ssl-checker/-/ssl-checker-2.0.10.tgz",
"integrity": "sha512-SS6rrZocToJWHM1p6iVNb583ybB3UqT1fymCHSWuEdXDUqKA6O1D5Fb8KJVmhj3XKXE82IEWcr+idJrc4jUzFQ==",
"license": "MIT"
},
"node_modules/stack-trace": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
+1
View File
@@ -29,6 +29,7 @@
"nodemailer": "^6.9.14",
"ping": "0.4.4",
"sharp": "0.33.4",
"ssl-checker": "2.0.10",
"winston": "^3.13.0"
},
"devDependencies": {
+1
View File
@@ -5,6 +5,7 @@ const Monitor = require("../models/Monitor");
router.get("/", monitorController.getAllMonitors);
router.get("/stats/:monitorId", monitorController.getMonitorStatsById);
router.get("/certificate/:monitorId", monitorController.getMonitorCertificate);
router.get("/:monitorId", monitorController.getMonitorById);
router.get("/user/:userId", monitorController.getMonitorsByUserId);
+1
View File
@@ -77,6 +77,7 @@ const successMessages = {
MONITOR_CREATE: "Monitor created successfully",
MONITOR_DELETE: "Monitor deleted successfully",
MONITOR_EDIT: "Monitor edited successfully",
MONITOR_CERTIFICATE: "Got monitor certificate successfully",
//Job Queue
JOB_QUEUE_DELETE_JOB: "Job removed successfully",
+1 -1
View File
@@ -126,7 +126,7 @@ const getMonitorByIdQueryValidation = joi.object({
status: joi.boolean(),
sortOrder: joi.string().valid("asc", "desc"),
limit: joi.number(),
filter: joi.string().valid("day", "week", "month"),
dateRange: joi.string().valid("day", "week", "month"),
numToDisplay: joi.number(),
normalize: joi.boolean(),
});