database.class.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. import fs from 'fs';
  2. import fsp from 'fs/promises';
  3. import moment from 'moment';
  4. import path from 'path';
  5. import { Database as SQLiteDB, OPEN_CREATE, OPEN_READWRITE } from 'sqlite3';
  6. import defaults from '../../../common/defaults.module';
  7. import { ServiceConfig, validateParamType } from '../../../common/interfaces/service-config.interface';
  8. import { HttpCheckData, HttpCheckStatus, ServiceCheckData, ServiceCheckDataEntry } from '../../../common/lib/http-check-data.module';
  9. import { Logger } from '../../../common/util/logger.class';
  10. import { ValidationException } from '../lib/validation-exception.class';
  11. import { DBMigration } from './db-migration.class';
  12. import { SQLiteController } from './sqlite-controller.base';
  13. export enum ServiceChangedStatus {
  14. None,
  15. Created,
  16. Activated,
  17. Deactivated,
  18. Rescheduled
  19. }
  20. export class Database extends SQLiteController {
  21. public set onError(listener: (error: any) => void) {
  22. this._onError = listener;
  23. }
  24. private _onError: (error: any) => void = err => console.error('[DB.ONERROR]', err);
  25. public async open(migrate = false) {
  26. try {
  27. const DATA_DIR = process.env.DATA_DIR || 'data';
  28. if (!fs.existsSync(DATA_DIR)) await fsp.mkdir(DATA_DIR);
  29. const DATA_FILE = path.resolve(DATA_DIR, 'data.db');
  30. const exists = fs.existsSync(DATA_FILE);
  31. await new Promise<void>((res, rej) => {
  32. this.db = new SQLiteDB(DATA_FILE, OPEN_READWRITE | OPEN_CREATE, err => (err ? rej(err) : res()));
  33. this.db.on('error', this._onError);
  34. });
  35. Logger.info('[INFO]', exists ? 'Opened' : 'Created', 'SQLite3 Database file', DATA_FILE);
  36. if (!this.db) throw new Error('Database not opened.');
  37. if (!exists) {
  38. // INITIAL TABLE SETUP
  39. await this.run(
  40. `CREATE TABLE Server (
  41. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  42. Title TEXT NOT NULL UNIQUE,
  43. FQDN TEXT NOT NULL UNIQUE
  44. );`,
  45. []
  46. );
  47. await this.run(
  48. `CREATE TABLE ServerConfig (
  49. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  50. ServerID INTEGER NOT NULL,
  51. Key TEXT NOT NULL,
  52. Value TEXT NOT NULL,
  53. FOREIGN KEY(ServerID) REFERENCES Server(ID),
  54. UNIQUE(ServerID, Key)
  55. )`,
  56. []
  57. );
  58. await this.run(
  59. `CREATE TABLE ServerDataEntry (
  60. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  61. ServerID INTEGER NOT NULL,
  62. Timestamp INTEGER NOT NULL,
  63. FOREIGN KEY(ServerID) REFERENCES Server(ID),
  64. UNIQUE(ServerID, Timestamp)
  65. );`,
  66. []
  67. );
  68. await this.run(
  69. `CREATE TABLE ServerDataValue (
  70. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  71. EntryID INTEGER NOT NULL,
  72. Type Text NOT NULL,
  73. Key TEXT NOT NULL,
  74. Value REAL NOT NULL,
  75. FOREIGN KEY(EntryID) REFERENCES ServerDataEntry(ID),
  76. UNIQUE(EntryID, Type, Key)
  77. );`,
  78. []
  79. );
  80. let result = await this.run(`INSERT INTO Server(Title, FQDN) VALUES(?, ?);`, ['Raspi4', '10.8.0.10']);
  81. const serverID = result.lastID;
  82. Logger.debug(`[DEBUG] Created Server #${serverID}`);
  83. result = await this.run(`INSERT INTO ServerConfig(ServerID, Key, Value) VALUES(?, ?, ?);`, [serverID, 'syncInterval', 300]);
  84. }
  85. if (migrate) {
  86. // RUN DB MIGRATIONS
  87. const mig = new DBMigration(this.db);
  88. await mig.update();
  89. }
  90. // DB RUNTIME SETTINGS
  91. await this.exec('PRAGMA foreign_keys=on;');
  92. } catch (err) {
  93. Logger.error('[FATAL] Initializing Database failed:', err);
  94. Logger.error('[EXITING]');
  95. process.exit(1);
  96. }
  97. }
  98. public async getAllServerConfigs(): Promise<Server[]> {
  99. const res = await this.stmt(
  100. `SELECT
  101. Server.*,
  102. ServerConfig.Key,
  103. ServerConfig.Value
  104. FROM Server
  105. LEFT OUTER JOIN ServerConfig ON Server.ID = ServerConfig.ServerID
  106. ORDER BY Server.Title, ServerConfig.Key`,
  107. []
  108. );
  109. return res.rows.reduce((res: Server[], line, i) => {
  110. const serverID = line['ID'];
  111. let server: Server;
  112. if (i === 0 || res[res.length - 1].id !== serverID) {
  113. server = { id: serverID, title: line['Title'], fqdn: line['FQDN'], config: {} };
  114. res.push(server);
  115. } else {
  116. server = res[res.length - 1];
  117. }
  118. if (!!line['Key']) {
  119. server.config[line['Key']] = line['Value'];
  120. }
  121. return res;
  122. }, [] as Server[]);
  123. }
  124. public async insertServerData(serverID: number, data: ReducedData[]) {
  125. if (!data.length) return;
  126. await this.beginTransaction();
  127. try {
  128. for (const entry of data) {
  129. const result = await this.run('INSERT INTO ServerDataEntry(ServerID, Timestamp) VALUES(?, ?);', [serverID, entry.time.getTime()]);
  130. let entryID = result.lastID;
  131. for (const type of Object.keys(entry).filter(t => !['time', 'hdd'].includes(t))) {
  132. for (const key of Object.keys((entry as any)[type])) {
  133. await this.run('INSERT INTO ServerDataValue(EntryID, Type, Key, Value) VALUES(?, ?, ?, ?);', [
  134. entryID,
  135. type,
  136. key,
  137. (entry as any)[type][key]
  138. ]);
  139. }
  140. }
  141. if (entry.hdd) {
  142. for (const mount of Object.keys(entry.hdd)) {
  143. for (const key of Object.keys(entry.hdd[mount])) {
  144. await this.run('INSERT INTO ServerDataValue(EntryID, Type, Key, Value) VALUES(?, ?, ?, ?);', [
  145. entryID,
  146. `hdd:${mount}`,
  147. key,
  148. (entry.hdd[mount] as any)[key]
  149. ]);
  150. }
  151. }
  152. }
  153. }
  154. await this.commit();
  155. } catch (err) {
  156. await this.rollback();
  157. throw err;
  158. }
  159. }
  160. public async getServerDataTypes(serverID: number) {
  161. const results = await this.stmt(
  162. `
  163. SELECT
  164. ServerDataValue.Type
  165. FROM ServerDataEntry
  166. JOIN ServerDataValue ON ServerDataEntry.ID = ServerDataValue.EntryID
  167. WHERE ServerDataEntry.ServerID = ?
  168. GROUP BY ServerDataValue.Type
  169. ORDER BY ServerDataValue.Type;
  170. `,
  171. [serverID]
  172. );
  173. return results.rows.reduce((res: Array<ServerDataTypesConfig>, { Type: type }) => {
  174. if (!type.startsWith('hdd:')) {
  175. res.push({ type });
  176. } else {
  177. let hdd = res.find(c => c.type === 'hdd');
  178. if (!hdd) {
  179. hdd = { type: 'hdd', subtypes: [] };
  180. res.push(hdd);
  181. }
  182. hdd.subtypes?.push({ type: type.substring(4) });
  183. }
  184. return res;
  185. }, []) as Array<ServerDataTypesConfig>;
  186. }
  187. public async queryServerData(serverID: number, type: ServerDataType, from: Date, to: Date): Promise<ServerData[]> {
  188. const diffMs = moment(to).diff(moment(from));
  189. const sectionMs = Math.floor(diffMs / 100);
  190. const select_max = type !== 'cpu';
  191. const select_types = select_max ? [type, type, type] : [type, type];
  192. const result = await this.stmt(
  193. `
  194. SELECT
  195. CEIL(Timestamp / ?) * ? as 'Timegroup',
  196. AVG(VALUE_AVG.Value) as 'avg',
  197. MAX(VALUE_PEAK.Value) as 'peak'${
  198. select_max
  199. ? `,
  200. MAX(VALUE_MAX.Value) as 'max'`
  201. : ''
  202. }
  203. FROM ServerDataEntry
  204. JOIN ServerDataValue AS VALUE_AVG ON ServerDataEntry.ID = VALUE_AVG.EntryID AND VALUE_AVG.Type = ? AND VALUE_AVG.Key = 'avg'
  205. JOIN ServerDataValue AS VALUE_PEAK ON ServerDataEntry.ID = VALUE_PEAK.EntryID AND VALUE_PEAK.Type = ? AND VALUE_PEAK.Key = 'peak'
  206. ${
  207. select_max
  208. ? "JOIN ServerDataValue AS VALUE_MAX ON ServerDataEntry.ID = VALUE_MAX.EntryID AND VALUE_MAX.Type = ? AND VALUE_MAX.Key = 'max'"
  209. : ''
  210. }
  211. WHERE ServerDataEntry.ServerID = ?
  212. AND ServerDataEntry.Timestamp BETWEEN ? AND ?
  213. GROUP BY Timegroup
  214. ORDER BY Timegroup;
  215. `,
  216. [sectionMs, sectionMs, ...select_types, serverID, from.getTime(), to.getTime()]
  217. );
  218. return result.rows.map(r => ({ time: new Date(r.Timegroup), avg: r.avg, peak: r.peak, max: r.max }));
  219. }
  220. public async queryServerStats(serverID: number, type: ServerDataType, from: Date, to: Date): Promise<ReducedValuesPerc> {
  221. const select_max = type !== 'cpu';
  222. const select_types = select_max ? [type, type, type] : [type, type];
  223. const result = await this.stmt(
  224. `
  225. SELECT
  226. AVG(VALUE_AVG.Value) as 'avg',
  227. AVG(VALUE_PEAK.Value) as 'peak'${
  228. select_max
  229. ? `,
  230. MAX(VALUE_MAX.Value) as 'max'`
  231. : ''
  232. }
  233. FROM ServerDataEntry
  234. JOIN ServerDataValue AS VALUE_AVG ON ServerDataEntry.ID = VALUE_AVG.EntryID AND VALUE_AVG.Type = ? AND VALUE_AVG.Key = 'avg'
  235. JOIN ServerDataValue AS VALUE_PEAK ON ServerDataEntry.ID = VALUE_PEAK.EntryID AND VALUE_PEAK.Type = ? AND VALUE_PEAK.Key = 'peak'
  236. ${
  237. select_max
  238. ? "JOIN ServerDataValue AS VALUE_MAX ON ServerDataEntry.ID = VALUE_MAX.EntryID AND VALUE_MAX.Type = ? AND VALUE_MAX.Key = 'max'"
  239. : ''
  240. }
  241. WHERE ServerDataEntry.ServerID = ?
  242. AND ServerDataEntry.Timestamp BETWEEN ? AND ?;
  243. `,
  244. [...select_types, serverID, from.getTime(), to.getTime()]
  245. );
  246. const row = result.rows[0];
  247. if (Object.keys(row).includes('max')) {
  248. return {
  249. avg: ((row['avg'] as number) / (row['max'] as number)) * 100,
  250. peak: ((row['peak'] as number) / (row['peak'] as number)) * 100
  251. };
  252. } else {
  253. return {
  254. avg: row['avg'] as number,
  255. peak: row['peak'] as number
  256. };
  257. }
  258. }
  259. private async getHealthCheckConfigs(serverID?: number, type = 'http') {
  260. const res = await this.stmt(
  261. `SELECT
  262. HealthCheckConfig.*,
  263. HealthCheckParams.Type as '_ParamType',
  264. HealthCheckParams.Key as '_ParamKey',
  265. HealthCheckParams.Value as '_ParamValue'
  266. FROM HealthCheckConfig
  267. LEFT OUTER JOIN HealthCheckParams ON HealthCheckConfig.ID = HealthCheckParams.ConfigID
  268. WHERE HealthCheckConfig.Type = ?
  269. ${!!serverID ? 'AND HealthCheckConfig.ServerID = ?' : ''}
  270. ORDER BY HealthCheckConfig.Title, _ParamType, _ParamKey`,
  271. [type, serverID]
  272. );
  273. return this.configFromResultRows(res.rows);
  274. }
  275. public async getHttpCheckConfigs(serverID?: number) {
  276. return (await this.getHealthCheckConfigs(serverID)).map(this.httpCheckConfigFrom);
  277. }
  278. private async getHealthCheckConfigByID(serverID: number, configID: number) {
  279. if (!serverID && !configID) return null;
  280. const res = await this.stmt(
  281. `SELECT
  282. HealthCheckConfig.*,
  283. HealthCheckParams.Type as '_ParamType',
  284. HealthCheckParams.Key as '_ParamKey',
  285. HealthCheckParams.Value as '_ParamValue'
  286. FROM HealthCheckConfig
  287. LEFT OUTER JOIN HealthCheckParams ON HealthCheckConfig.ID = HealthCheckParams.ConfigID
  288. WHERE HealthCheckConfig.ID = ?
  289. AND HealthCheckConfig.ServerID = ?
  290. ORDER BY HealthCheckConfig.Title, _ParamType, _ParamKey`,
  291. [configID, serverID]
  292. );
  293. if (!res.rows.length) return null;
  294. const configs = this.configFromResultRows(res.rows);
  295. return configs[0];
  296. }
  297. public async getHttpCheckConfigByID(serverID: number, configID: number) {
  298. return this.httpCheckConfigFrom(await this.getHealthCheckConfigByID(serverID, configID));
  299. }
  300. public async saveHttpCheckConfig(serverID: number, conf: HttpCheckConfig) {
  301. const validationErrors = this.validateHttpCheckConfig(conf);
  302. if (validationErrors) throw new ValidationException('Validation of HttpCheckConfig object failed', validationErrors);
  303. conf.serverId = serverID;
  304. let status = ServiceChangedStatus.None;
  305. const oldConf = await this.getHttpCheckConfigByID(serverID, conf.id);
  306. await this.beginTransaction();
  307. try {
  308. if (oldConf) {
  309. // UPDATE
  310. if (oldConf.title !== conf.title) {
  311. await this.stmt('UPDATE HealthCheckConfig SET Title = ?', [conf.title]);
  312. }
  313. let updValues: any[][] = [];
  314. if (oldConf.url !== conf.url) updValues.push([conf.url, conf.id, 'url']);
  315. if (oldConf.interval !== conf.interval) {
  316. updValues.push([conf.interval, conf.id, 'interval']);
  317. status = ServiceChangedStatus.Rescheduled;
  318. }
  319. if (oldConf.timeout !== conf.timeout) updValues.push([conf.timeout ?? defaults.serviceChecks.httpTimeout, conf.id, 'timeout']);
  320. if (oldConf.active !== conf.active) {
  321. updValues.push([conf.active ?? defaults.serviceChecks.active ? 1 : 0, conf.id, 'active']);
  322. status = conf.active ?? defaults.serviceChecks.active ? ServiceChangedStatus.Activated : ServiceChangedStatus.Deactivated;
  323. }
  324. if (oldConf.notify !== conf.notify) updValues.push([conf.notify ?? defaults.serviceChecks.notify ? 1 : 0, conf.id, 'notify']);
  325. if (oldConf.notifyThreshold !== conf.notifyThreshold)
  326. updValues.push([conf.notifyThreshold ?? defaults.serviceChecks.notifyThreshold, conf.id, 'notifyThreshold']);
  327. if (updValues.length) {
  328. for (const data of updValues) {
  329. await this.run(`UPDATE HealthCheckParams SET Value = ? WHERE ConfigID = ? AND Key = ?;`, data);
  330. }
  331. }
  332. const res = await this.stmt('SELECT * FROM HealthCheckParams WHERE ConfigID = ? and Key = "check";', [conf.id]);
  333. updValues = [];
  334. const delIDs: number[] = [];
  335. res.rows.forEach((row, i) => {
  336. if (i < conf.checks.length) {
  337. updValues.push([conf.checks[i], row['ID']]);
  338. } else {
  339. delIDs.push(row['ID']);
  340. }
  341. });
  342. if (delIDs.length) {
  343. const delSql = `DELETE FROM HealthCheckParams WHERE ID IN (${delIDs.map(() => '?').join(',')});`;
  344. await this.run(delSql, delIDs);
  345. }
  346. if (updValues.length) {
  347. for (const data of updValues) {
  348. await this.run('UPDATE HealthCheckParams SET Value = ? WHERE ID = ?;', data);
  349. }
  350. }
  351. const insValues = conf.checks.filter((c, i) => i > res.rows.length - 1).map(c => [conf.id, 'regexp', 'check', c]);
  352. if (insValues.length) {
  353. for (const data of insValues) {
  354. await this.run('INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES(?, ?, ?, ?);', data);
  355. }
  356. }
  357. } else {
  358. // INSERT
  359. const res = await this.run('INSERT INTO HealthCheckConfig(ServerID, Type, Title) VALUES(?, ?, ?);', [serverID, 'http', conf.title]);
  360. conf.id = res.lastID;
  361. if (conf.active ?? defaults.serviceChecks.active) {
  362. status = ServiceChangedStatus.Created;
  363. }
  364. const insCheckValues = conf.checks.map(c => [res.lastID, 'regexp', 'check', c]);
  365. await this.run(
  366. `INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES
  367. (?, ?, ?, ?),
  368. (?, ?, ?, ?),
  369. (?, ?, ?, ?),
  370. (?, ?, ?, ?),
  371. (?, ?, ?, ?),
  372. (?, ?, ?, ?)${conf.checks.length ? `,${insCheckValues.map(() => '(?, ?, ?, ?)').join(',')}` : ''}`,
  373. [
  374. ...[res.lastID, 'text', 'url', conf.url],
  375. ...[res.lastID, 'boolean', 'active', conf.active ?? defaults.serviceChecks.active ? 1 : 0],
  376. ...[res.lastID, 'number', 'interval', conf.interval],
  377. ...[res.lastID, 'number', 'timeout', conf.timeout ?? defaults.serviceChecks.httpTimeout],
  378. ...[res.lastID, 'boolean', 'notify', conf.notify ?? defaults.serviceChecks.notify],
  379. ...[res.lastID, 'number', 'notifyThreshold', conf.notifyThreshold ?? defaults.serviceChecks.notifyThreshold],
  380. ...conf.checks.reduce((ret, check) => [...ret, res.lastID, 'regexp', 'check', check], [] as any[])
  381. ]
  382. );
  383. }
  384. await this.commit();
  385. return { status, result: conf };
  386. } catch (err) {
  387. await this.rollback();
  388. throw err;
  389. }
  390. }
  391. async deleteHealthCheckConfig(serverID: number, confID: number) {
  392. const conf = await this.getHealthCheckConfigByID(serverID, confID);
  393. if (!conf) return false;
  394. await this.run('DELETE FROM HealthCheckConfig WHERE ID = ?;', [confID]);
  395. return true;
  396. }
  397. async insertHealthCheckData(confID: number, time: Date, status: HttpCheckStatus, message: string) {
  398. const res = await this.run('INSERT INTO HealthCheckDataEntry(ConfigID, Timestamp, Status, Message) VALUES(?, ?, ?, ?);', [
  399. confID,
  400. time.getTime(),
  401. status,
  402. message
  403. ]);
  404. return {
  405. id: res.lastID,
  406. configId: confID,
  407. time,
  408. status,
  409. message
  410. } as HttpCheckData;
  411. }
  412. async queryServiceCheckData(serverID: number, confID: number, from: Date, to: Date) {
  413. const result = await this.stmt(
  414. `
  415. SELECT DataEntryChanges.*
  416. FROM HealthCheckConfig
  417. JOIN (
  418. SELECT * FROM (
  419. SELECT
  420. *
  421. FROM HealthCheckDataEntry
  422. WHERE ConfigID = ?
  423. AND Timestamp BETWEEN ? AND ?
  424. ORDER BY ID
  425. LIMIT 0, 1
  426. ) AS FIRST_STATE
  427. UNION --+--+--
  428. SELECT
  429. ID,
  430. ConfigID,
  431. Timestamp,
  432. Status,
  433. Message
  434. FROM
  435. (
  436. SELECT
  437. HealthCheckDataEntry.*,
  438. LAG(Status) OVER (ORDER BY ConfigID, Timestamp) AS previous_state,
  439. LAG(Message) OVER (ORDER BY ConfigID, Timestamp) AS previous_msg
  440. FROM HealthCheckDataEntry
  441. WHERE ConfigID = ?
  442. )
  443. WHERE Status <> previous_state
  444. AND Message <> previous_msg
  445. UNION --+--+--
  446. SELECT * FROM (
  447. SELECT
  448. *
  449. FROM HealthCheckDataEntry
  450. WHERE ConfigID = ?
  451. AND Timestamp BETWEEN ? AND ?
  452. ORDER BY ID DESC
  453. LIMIT 0, 1
  454. ) AS LAST_STATE
  455. ORDER BY ConfigID, Timestamp
  456. ) AS DataEntryChanges ON DataEntryChanges.ConfigID = HealthCheckConfig.ID
  457. WHERE HealthCheckConfig.ServerID = ?
  458. AND DataEntryChanges.Timestamp BETWEEN ? AND ?
  459. ORDER BY Timestamp, ID;`,
  460. [confID, from.getTime(), to.getTime(), confID, confID, from.getTime(), to.getTime(), serverID, from.getTime(), to.getTime()]
  461. );
  462. const mapByTimestamp = this.mapServiceCheckDataByTimestamp(result.rows);
  463. const arr: ServiceCheckData[] = [];
  464. for (const entry of mapByTimestamp.entries()) {
  465. arr.push({
  466. time: new Date(entry[0]),
  467. data: entry[1]
  468. });
  469. }
  470. return arr;
  471. }
  472. public async getLastErrors(confID: number, threshold: number) {
  473. const result = await this.stmt(
  474. `SELECT * FROM HealthCheckDataEntry
  475. WHERE ConfigID = ?
  476. AND Timestamp IN (
  477. SELECT Timestamp
  478. FROM HealthCheckDataEntry
  479. WHERE ConfigID = ?
  480. GROUP BY Timestamp
  481. ORDER BY Timestamp DESC
  482. LIMIT 0, ?
  483. )
  484. ORDER BY Timestamp DESC, ID DESC`,
  485. [confID, confID, threshold]
  486. );
  487. const mapByTimestamp = this.mapServiceCheckDataByTimestamp(result.rows);
  488. const errors: ServiceCheckData[] = [];
  489. for (const entry of mapByTimestamp.entries()) {
  490. const time = entry[0];
  491. const data = entry[1];
  492. const errorData = data.filter(d => d.status !== HttpCheckStatus.OK);
  493. if (!errorData.length) break;
  494. errors.push({
  495. time: new Date(time),
  496. data: errorData
  497. });
  498. }
  499. return errors;
  500. }
  501. private mapServiceCheckDataByTimestamp(rows: any[]) {
  502. return rows.reduce((res: Map<number, ServiceCheckDataEntry[]>, row) => {
  503. const time: number = row['Timestamp'];
  504. if (!res.has(time)) res.set(time, []);
  505. res.get(time)?.push({
  506. status: row['Status'] as number,
  507. message: row['Message']
  508. });
  509. return res;
  510. }, new Map()) as Map<number, ServiceCheckDataEntry[]>;
  511. }
  512. private configFromResultRows(rows: any[]) {
  513. return rows.reduce((res: ServiceConfig[], line, i) => {
  514. const configID = line['ID'];
  515. let config: ServiceConfig;
  516. if (i === 0 || res[res.length - 1].id !== configID) {
  517. config = {
  518. id: configID,
  519. title: line['Title'],
  520. type: line['Type'],
  521. serverId: line['ServerID'],
  522. params: []
  523. };
  524. res.push(config);
  525. } else {
  526. config = res[res.length - 1];
  527. }
  528. if (!!line['_ParamKey']) {
  529. const type = validateParamType(line['_ParamType']);
  530. const key = line['_ParamKey'];
  531. if (key === 'check') {
  532. let checkParam = config.params.find(c => c.key === 'check');
  533. if (!checkParam) {
  534. config.params.push(
  535. (checkParam = {
  536. key: 'check',
  537. type: 'regexp',
  538. value: []
  539. })
  540. );
  541. }
  542. (checkParam.value as string[]).push(line['_ParamValue']);
  543. } else {
  544. config.params.push({
  545. type,
  546. key,
  547. value: type === 'number' ? Number(line['_ParamValue']) : type === 'boolean' ? Boolean(Number(line['_ParamValue'])) : line['_ParamValue']
  548. });
  549. }
  550. }
  551. return res;
  552. }, [] as ServiceConfig[]);
  553. }
  554. private httpCheckConfigFrom(hcConf: ServiceConfig | null): HttpCheckConfig | null {
  555. if (!hcConf) return null;
  556. const params = {
  557. url: hcConf.params?.find(p => p.key === 'url')?.value as string,
  558. active: (hcConf.params?.find(p => p.key === 'active')?.value as boolean) ?? defaults.serviceChecks.active,
  559. interval: hcConf.params?.find(p => p.key === 'interval')?.value as number,
  560. timeout: (hcConf.params?.find(p => p.key === 'timeout')?.value as number) ?? defaults.serviceChecks.httpTimeout,
  561. notify: (hcConf.params?.find(p => p.key === 'notify')?.value as boolean) ?? defaults.serviceChecks.notify,
  562. notifyThreshold: (hcConf.params?.find(p => p.key === 'notifyThreshold')?.value as number) ?? defaults.serviceChecks.notifyThreshold,
  563. checks: hcConf.params?.reduce((res, p) => (p.key === 'check' && Array.isArray(p.value) ? [...res, ...p.value] : res), [] as string[])
  564. };
  565. return {
  566. id: hcConf.id,
  567. title: hcConf.title,
  568. type: hcConf.type,
  569. serverId: hcConf.serverId,
  570. ...params
  571. };
  572. }
  573. private validateHttpCheckConfig(conf: Partial<HttpCheckConfig>): { [key: string]: string } | null {
  574. const errors = {} as any;
  575. if (!conf) return { null: 'Object was null or undefined' };
  576. if (!conf.title?.trim().length) errors['required|title'] = `Field 'title' is required.`;
  577. if (!conf.url?.trim().length) errors['required|url'] = `Field 'url' is required.`;
  578. if ((!conf.interval && conf.interval !== 0) || Number.isNaN(Number(conf.interval))) errors['required|interval'] = `Field 'interval' is required.`;
  579. if (!conf.checks || !Array.isArray(conf.checks))
  580. errors['required|checks'] = `Field 'checks' is required and must be an array of check expressions.`;
  581. return Object.keys(errors).length ? errors : null;
  582. }
  583. }