2022-04-19 09:38:59 +02:00
const express = require ( "express" ) ;
const https = require ( "https" ) ;
const fs = require ( "fs" ) ;
const http = require ( "http" ) ;
const { Server } = require ( "socket.io" ) ;
const { R } = require ( "redbean-node" ) ;
2022-04-19 10:46:45 +02:00
const { log } = require ( "../src/util" ) ;
2022-05-06 08:41:34 +02:00
const Database = require ( "./database" ) ;
const util = require ( "util" ) ;
2022-07-18 16:33:35 +02:00
const { CacheableDnsHttpAgent } = require ( "./cacheable-dns-http-agent" ) ;
2022-07-31 17:41:29 +02:00
const { Settings } = require ( "./settings" ) ;
2022-10-09 14:59:58 +02:00
const dayjs = require ( "dayjs" ) ;
2023-01-27 12:25:57 +02:00
const { PluginsManager } = require ( "./plugins-manager" ) ;
2022-10-15 14:15:50 +02:00
// DO NOT IMPORT HERE IF THE MODULES USED `UptimeKumaServer.getInstance()`
2022-04-19 09:38:59 +02:00
/ * *
* ` module.exports ` ( alias : ` server ` ) should be inside this class , in order to avoid circular dependency issue .
* @ type { UptimeKumaServer }
* /
class UptimeKumaServer {
/ * *
*
* @ type { UptimeKumaServer }
* /
static instance = null ;
/ * *
* Main monitor list
* @ type { { } }
* /
monitorList = { } ;
2022-09-17 10:54:21 +02:00
/ * *
* Main maintenance list
* @ type { { } }
* /
maintenanceList = { } ;
2022-04-19 09:38:59 +02:00
entryPage = "dashboard" ;
app = undefined ;
httpServer = undefined ;
io = undefined ;
2022-05-30 09:45:44 +02:00
/ * *
* Cache Index HTML
* @ type { string }
* /
indexHTML = "" ;
2022-10-15 11:17:26 +02:00
generateMaintenanceTimeslotsInterval = undefined ;
2023-01-27 12:25:57 +02:00
/ * *
* Plugins Manager
* @ type { PluginsManager }
* /
pluginsManager = null ;
/ * *
*
* @ type { { } }
* /
static monitorTypeList = {
} ;
2022-04-19 09:38:59 +02:00
static getInstance ( args ) {
if ( UptimeKumaServer . instance == null ) {
UptimeKumaServer . instance = new UptimeKumaServer ( args ) ;
}
return UptimeKumaServer . instance ;
}
constructor ( args ) {
// SSL
2022-04-19 10:46:45 +02:00
const sslKey = args [ "ssl-key" ] || process . env . UPTIME _KUMA _SSL _KEY || process . env . SSL _KEY || undefined ;
const sslCert = args [ "ssl-cert" ] || process . env . UPTIME _KUMA _SSL _CERT || process . env . SSL _CERT || undefined ;
2022-04-19 09:38:59 +02:00
2022-04-19 10:46:45 +02:00
log . info ( "server" , "Creating express and socket.io instance" ) ;
2022-04-19 09:38:59 +02:00
this . app = express ( ) ;
if ( sslKey && sslCert ) {
2022-04-19 10:46:45 +02:00
log . info ( "server" , "Server Type: HTTPS" ) ;
2022-04-19 09:38:59 +02:00
this . httpServer = https . createServer ( {
key : fs . readFileSync ( sslKey ) ,
cert : fs . readFileSync ( sslCert )
} , this . app ) ;
} else {
2022-04-19 10:46:45 +02:00
log . info ( "server" , "Server Type: HTTP" ) ;
2022-04-19 09:38:59 +02:00
this . httpServer = http . createServer ( this . app ) ;
}
2022-05-30 09:45:44 +02:00
try {
this . indexHTML = fs . readFileSync ( "./dist/index.html" ) . toString ( ) ;
} catch ( e ) {
// "dist/index.html" is not necessary for development
if ( process . env . NODE _ENV !== "development" ) {
log . error ( "server" , "Error: Cannot find 'dist/index.html', did you install correctly?" ) ;
process . exit ( 1 ) ;
}
}
2022-04-19 09:38:59 +02:00
this . io = new Server ( this . httpServer ) ;
}
2023-01-06 17:04:02 +02:00
/** Initialise app after the database has been set up */
2022-10-09 14:59:58 +02:00
async initAfterDatabaseReady ( ) {
2022-12-12 11:19:22 +02:00
await CacheableDnsHttpAgent . update ( ) ;
2022-10-09 14:59:58 +02:00
process . env . TZ = await this . getTimezone ( ) ;
dayjs . tz . setDefault ( process . env . TZ ) ;
log . debug ( "DEBUG" , "Timezone: " + process . env . TZ ) ;
log . debug ( "DEBUG" , "Current Time: " + dayjs . tz ( ) . format ( ) ) ;
2022-10-15 11:17:26 +02:00
await this . generateMaintenanceTimeslots ( ) ;
this . generateMaintenanceTimeslotsInterval = setInterval ( this . generateMaintenanceTimeslots , 60 * 1000 ) ;
2022-10-09 14:59:58 +02:00
}
2023-01-06 00:19:05 +02:00
/ * *
* Send list of monitors to client
* @ param { Socket } socket
* @ returns { Object } List of monitors
* /
2022-04-19 09:38:59 +02:00
async sendMonitorList ( socket ) {
let list = await this . getMonitorJSONList ( socket . userID ) ;
this . io . to ( socket . userID ) . emit ( "monitorList" , list ) ;
return list ;
}
2022-04-19 10:46:45 +02:00
/ * *
* Get a list of monitors for the given user .
* @ param { string } userID - The ID of the user to get monitors for .
* @ returns { Promise < Object > } A promise that resolves to an object with monitor IDs as keys and monitor objects as values .
*
* Generated by Trelent
* /
2022-04-19 09:38:59 +02:00
async getMonitorJSONList ( userID ) {
let result = { } ;
let monitorList = await R . find ( "monitor" , " user_id = ? ORDER BY weight DESC, name" , [
userID ,
] ) ;
for ( let monitor of monitorList ) {
result [ monitor . id ] = await monitor . toJSON ( ) ;
}
return result ;
}
2022-05-06 08:41:34 +02:00
2022-09-17 10:54:21 +02:00
/ * *
* Send maintenance list to client
* @ param { Socket } socket Socket . io instance to send to
* @ returns { Object }
* /
async sendMaintenanceList ( socket ) {
2022-10-15 14:15:50 +02:00
return await this . sendMaintenanceListByUserID ( socket . userID ) ;
}
2023-01-06 00:19:05 +02:00
/ * *
* Send list of maintenances to user
* @ param { number } userID
* @ returns { Object }
* /
2022-10-15 14:15:50 +02:00
async sendMaintenanceListByUserID ( userID ) {
let list = await this . getMaintenanceJSONList ( userID ) ;
this . io . to ( userID ) . emit ( "maintenanceList" , list ) ;
2022-09-17 10:54:21 +02:00
return list ;
}
/ * *
* Get a list of maintenances for the given user .
* @ param { string } userID - The ID of the user to get maintenances for .
* @ returns { Promise < Object > } A promise that resolves to an object with maintenance IDs as keys and maintenances objects as values .
* /
async getMaintenanceJSONList ( userID ) {
let result = { } ;
let maintenanceList = await R . find ( "maintenance" , " user_id = ? ORDER BY end_date DESC, title" , [
userID ,
] ) ;
for ( let maintenance of maintenanceList ) {
result [ maintenance . id ] = await maintenance . toJSON ( ) ;
}
return result ;
}
2022-05-06 08:41:34 +02:00
/ * *
* Write error to log file
* @ param { any } error The error to write
* @ param { boolean } outputToConsole Should the error also be output to console ?
* /
static errorLog ( error , outputToConsole = true ) {
const errorLogStream = fs . createWriteStream ( Database . dataDir + "/error.log" , {
flags : "a"
} ) ;
errorLogStream . on ( "error" , ( ) => {
log . info ( "" , "Cannot write to error.log" ) ;
} ) ;
if ( errorLogStream ) {
const dateTime = R . isoDateTime ( ) ;
errorLogStream . write ( ` [ ${ dateTime } ] ` + util . format ( error ) + "\n" ) ;
if ( outputToConsole ) {
console . error ( error ) ;
}
}
errorLogStream . end ( ) ;
}
2022-07-31 17:36:33 +02:00
2023-01-06 00:19:05 +02:00
/ * *
* Get the IP of the client connected to the socket
* @ param { Socket } socket
* @ returns { string }
* /
2022-07-31 17:36:33 +02:00
async getClientIP ( socket ) {
2022-08-01 09:42:58 +02:00
let clientIP = socket . client . conn . remoteAddress ;
if ( clientIP === undefined ) {
clientIP = "" ;
}
2022-07-31 17:36:33 +02:00
2022-07-31 17:41:29 +02:00
if ( await Settings . get ( "trustProxy" ) ) {
2022-10-05 17:45:21 +02:00
const forwardedFor = socket . client . conn . request . headers [ "x-forwarded-for" ] ;
return ( typeof forwardedFor === "string" ? forwardedFor . split ( "," ) [ 0 ] . trim ( ) : null )
2022-07-31 17:36:33 +02:00
|| socket . client . conn . request . headers [ "x-real-ip" ]
2022-08-01 09:42:58 +02:00
|| clientIP . replace ( /^.*:/ , "" ) ;
2022-07-31 17:36:33 +02:00
} else {
2022-08-01 09:42:58 +02:00
return clientIP . replace ( /^.*:/ , "" ) ;
2022-07-31 17:36:33 +02:00
}
}
2022-10-09 14:59:58 +02:00
2023-01-06 00:19:05 +02:00
/ * *
* Attempt to get the current server timezone
* If this fails , fall back to environment variables and then make a
* guess .
* @ returns { string }
* /
2022-10-09 14:59:58 +02:00
async getTimezone ( ) {
let timezone = await Settings . get ( "serverTimezone" ) ;
if ( timezone ) {
return timezone ;
} else if ( process . env . TZ ) {
return process . env . TZ ;
} else {
return dayjs . tz . guess ( ) ;
}
}
2023-01-06 00:19:05 +02:00
/ * *
* Get the current offset
* @ returns { string }
* /
2022-10-11 15:48:43 +02:00
getTimezoneOffset ( ) {
2022-10-11 12:23:17 +02:00
return dayjs ( ) . format ( "Z" ) ;
}
2023-01-06 00:19:05 +02:00
/ * *
* Set the current server timezone and environment variables
* @ param { string } timezone
* /
2022-10-09 14:59:58 +02:00
async setTimezone ( timezone ) {
await Settings . set ( "serverTimezone" , timezone , "general" ) ;
process . env . TZ = timezone ;
dayjs . tz . setDefault ( timezone ) ;
}
2022-10-15 11:17:26 +02:00
2023-01-06 00:19:05 +02:00
/** Load the timeslots for maintenance */
2022-10-15 11:17:26 +02:00
async generateMaintenanceTimeslots ( ) {
2023-03-09 16:03:23 +02:00
log . debug ( "maintenance" , "Routine: Generating Maintenance Timeslots" ) ;
2022-10-15 11:17:26 +02:00
2023-03-07 14:47:57 +02:00
// Prevent #2776
// Remove duplicate maintenance_timeslot with same start_date, end_date and maintenance_id
await R . exec ( "DELETE FROM maintenance_timeslot WHERE id NOT IN (SELECT MIN(id) FROM maintenance_timeslot GROUP BY start_date, end_date, maintenance_id)" ) ;
2022-10-15 11:17:26 +02:00
let list = await R . find ( "maintenance_timeslot" , " generated_next = 0 AND start_date <= DATETIME('now') " ) ;
for ( let maintenanceTimeslot of list ) {
let maintenance = await maintenanceTimeslot . maintenance ;
await MaintenanceTimeslot . generateTimeslot ( maintenance , maintenanceTimeslot . end _date , false ) ;
maintenanceTimeslot . generated _next = true ;
await R . store ( maintenanceTimeslot ) ;
}
}
2023-01-06 00:19:05 +02:00
/** Stop the server */
2022-10-15 11:17:26 +02:00
async stop ( ) {
clearTimeout ( this . generateMaintenanceTimeslotsInterval ) ;
}
2023-01-27 12:25:57 +02:00
loadPlugins ( ) {
this . pluginsManager = new PluginsManager ( this ) ;
}
/ * *
*
* @ returns { PluginsManager }
* /
getPluginManager ( ) {
return this . pluginsManager ;
}
/ * *
*
* @ param { MonitorType } monitorType
* /
addMonitorType ( monitorType ) {
if ( monitorType instanceof MonitorType && monitorType . name ) {
if ( monitorType . name in UptimeKumaServer . monitorTypeList ) {
log . error ( "" , "Conflict Monitor Type name" ) ;
}
UptimeKumaServer . monitorTypeList [ monitorType . name ] = monitorType ;
} else {
log . error ( "" , "Invalid Monitor Type: " + monitorType . name ) ;
}
}
/ * *
*
* @ param { MonitorType } monitorType
* /
removeMonitorType ( monitorType ) {
if ( UptimeKumaServer . monitorTypeList [ monitorType . name ] === monitorType ) {
delete UptimeKumaServer . monitorTypeList [ monitorType . name ] ;
} else {
log . error ( "" , "Remove MonitorType failed: " + monitorType . name ) ;
}
}
2022-04-19 09:38:59 +02:00
}
module . exports = {
UptimeKumaServer
} ;
2022-10-15 11:17:26 +02:00
// Must be at the end
const MaintenanceTimeslot = require ( "./model/maintenance_timeslot" ) ;
2023-01-27 12:25:57 +02:00
const { MonitorType } = require ( "./monitor-types/monitor-type" ) ;