database.class.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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['max'] 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. Logger.debug('[DEBUG] Updating HealthCheckConfig', conf.title, `(${oldConf.id})`);
  311. if (oldConf.title !== conf.title) {
  312. await this.stmt('UPDATE HealthCheckConfig SET Title = ? WHERE ID = ?', [conf.title, oldConf.id]);
  313. }
  314. let updValues: any[][] = [];
  315. if (oldConf.url !== conf.url) updValues.push([conf.url, conf.id, 'url']);
  316. if (oldConf.interval !== conf.interval) {
  317. updValues.push([conf.interval, conf.id, 'interval']);
  318. status = ServiceChangedStatus.Rescheduled;
  319. }
  320. if (oldConf.timeout !== conf.timeout) updValues.push([conf.timeout ?? defaults.serviceChecks.httpTimeout, conf.id, 'timeout']);
  321. if (oldConf.active !== conf.active) {
  322. updValues.push([conf.active ?? defaults.serviceChecks.active ? 1 : 0, conf.id, 'active']);
  323. status = conf.active ?? defaults.serviceChecks.active ? ServiceChangedStatus.Activated : ServiceChangedStatus.Deactivated;
  324. }
  325. if (oldConf.notify !== conf.notify) updValues.push([conf.notify ?? defaults.serviceChecks.notify ? 1 : 0, conf.id, 'notify']);
  326. if (oldConf.notifyThreshold !== conf.notifyThreshold)
  327. updValues.push([conf.notifyThreshold ?? defaults.serviceChecks.notifyThreshold, conf.id, 'notifyThreshold']);
  328. if (updValues.length) {
  329. for (const data of updValues) {
  330. await this.run(`UPDATE HealthCheckParams SET Value = ? WHERE ConfigID = ? AND Key = ?;`, data);
  331. }
  332. }
  333. const res = await this.stmt('SELECT * FROM HealthCheckParams WHERE ConfigID = ? and Key = "check";', [conf.id]);
  334. updValues = [];
  335. const delIDs: number[] = [];
  336. res.rows.forEach((row, i) => {
  337. if (i < conf.checks.length) {
  338. updValues.push([JSON.stringify(conf.checks[i]), row['ID']]);
  339. } else {
  340. delIDs.push(row['ID']);
  341. }
  342. });
  343. if (delIDs.length) {
  344. const delSql = `DELETE FROM HealthCheckParams WHERE ID IN (${delIDs.map(() => '?').join(',')});`;
  345. await this.run(delSql, delIDs);
  346. }
  347. if (updValues.length) {
  348. for (const data of updValues) {
  349. await this.run('UPDATE HealthCheckParams SET Value = ? WHERE ID = ?;', data);
  350. }
  351. }
  352. const insValues = conf.checks.filter((c, i) => i > res.rows.length - 1).map(c => [conf.id, 'regexp', 'check', JSON.stringify(c)]);
  353. if (insValues.length) {
  354. for (const data of insValues) {
  355. await this.run('INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES(?, ?, ?, ?);', data);
  356. }
  357. }
  358. } else {
  359. // INSERT
  360. Logger.debug('[DEBUG] Inserting new HealthCheckConfig', conf.title);
  361. const res = await this.run('INSERT INTO HealthCheckConfig(ServerID, Type, Title) VALUES(?, ?, ?);', [serverID, 'http', conf.title]);
  362. conf.id = res.lastID;
  363. if (conf.active ?? defaults.serviceChecks.active) {
  364. status = ServiceChangedStatus.Created;
  365. }
  366. const insCheckValues = conf.checks.map(c => [res.lastID, 'regexp', 'check', c]);
  367. await this.run(
  368. `INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES
  369. (?, ?, ?, ?),
  370. (?, ?, ?, ?),
  371. (?, ?, ?, ?),
  372. (?, ?, ?, ?),
  373. (?, ?, ?, ?),
  374. (?, ?, ?, ?)${conf.checks.length ? `,${insCheckValues.map(() => '(?, ?, ?, ?)').join(',')}` : ''}`,
  375. [
  376. ...[res.lastID, 'text', 'url', conf.url],
  377. ...[res.lastID, 'boolean', 'active', conf.active ?? defaults.serviceChecks.active ? 1 : 0],
  378. ...[res.lastID, 'number', 'interval', conf.interval],
  379. ...[res.lastID, 'number', 'timeout', conf.timeout ?? defaults.serviceChecks.httpTimeout],
  380. ...[res.lastID, 'boolean', 'notify', conf.notify ?? defaults.serviceChecks.notify],
  381. ...[res.lastID, 'number', 'notifyThreshold', conf.notifyThreshold ?? defaults.serviceChecks.notifyThreshold],
  382. ...conf.checks.reduce((ret, check) => [...ret, res.lastID, 'regexp', 'check', JSON.stringify(check)], [] as any[])
  383. ]
  384. );
  385. }
  386. await this.commit();
  387. return { status, result: conf };
  388. } catch (err) {
  389. await this.rollback();
  390. throw err;
  391. }
  392. }
  393. async deleteHealthCheckConfig(serverID: number, confID: number) {
  394. const conf = await this.getHealthCheckConfigByID(serverID, confID);
  395. if (!conf) return false;
  396. await this.run('DELETE FROM HealthCheckConfig WHERE ID = ?;', [confID]);
  397. return true;
  398. }
  399. async insertHealthCheckData(confID: number, time: Date, status: HttpCheckStatus, message: string) {
  400. const res = await this.run('INSERT INTO HealthCheckDataEntry(ConfigID, Timestamp, Status, Message) VALUES(?, ?, ?, ?);', [
  401. confID,
  402. time.getTime(),
  403. status,
  404. message
  405. ]);
  406. return {
  407. id: res.lastID,
  408. configId: confID,
  409. time,
  410. status,
  411. message
  412. } as HttpCheckData;
  413. }
  414. async queryServiceCheckData(serverID: number, confID: number, from: Date, to: Date) {
  415. const result = await this.stmt(
  416. `
  417. SELECT DataEntryChanges.*
  418. FROM HealthCheckConfig
  419. JOIN (
  420. SELECT * FROM (
  421. SELECT
  422. *
  423. FROM HealthCheckDataEntry
  424. WHERE ConfigID = ?
  425. AND Timestamp BETWEEN ? AND ?
  426. ORDER BY ID
  427. LIMIT 0, 1
  428. ) AS FIRST_STATE
  429. UNION --+--+--
  430. SELECT
  431. ID,
  432. ConfigID,
  433. Timestamp,
  434. Status,
  435. Message
  436. FROM
  437. (
  438. SELECT
  439. HealthCheckDataEntry.*,
  440. LAG(Status) OVER (ORDER BY ConfigID, Timestamp) AS previous_state,
  441. LAG(Message) OVER (ORDER BY ConfigID, Timestamp) AS previous_msg
  442. FROM HealthCheckDataEntry
  443. WHERE ConfigID = ?
  444. )
  445. WHERE Status <> previous_state
  446. AND Message <> previous_msg
  447. UNION --+--+--
  448. SELECT * FROM (
  449. SELECT
  450. *
  451. FROM HealthCheckDataEntry
  452. WHERE ConfigID = ?
  453. AND Timestamp BETWEEN ? AND ?
  454. ORDER BY ID DESC
  455. LIMIT 0, 1
  456. ) AS LAST_STATE
  457. ORDER BY ConfigID, Timestamp
  458. ) AS DataEntryChanges ON DataEntryChanges.ConfigID = HealthCheckConfig.ID
  459. WHERE HealthCheckConfig.ServerID = ?
  460. AND DataEntryChanges.Timestamp BETWEEN ? AND ?
  461. ORDER BY Timestamp, ID;`,
  462. [confID, from.getTime(), to.getTime(), confID, confID, from.getTime(), to.getTime(), serverID, from.getTime(), to.getTime()]
  463. );
  464. const mapByTimestamp = this.mapServiceCheckDataByTimestamp(result.rows);
  465. const arr: ServiceCheckData[] = [];
  466. for (const entry of mapByTimestamp.entries()) {
  467. arr.push({
  468. time: new Date(entry[0]),
  469. data: entry[1]
  470. });
  471. }
  472. return arr;
  473. }
  474. public async getLastErrors(confID: number, threshold: number) {
  475. const result = await this.stmt(
  476. `SELECT * FROM HealthCheckDataEntry
  477. WHERE ConfigID = ?
  478. AND Timestamp IN (
  479. SELECT Timestamp
  480. FROM HealthCheckDataEntry
  481. WHERE ConfigID = ?
  482. GROUP BY Timestamp
  483. ORDER BY Timestamp DESC
  484. LIMIT 0, ?
  485. )
  486. ORDER BY Timestamp DESC, ID DESC`,
  487. [confID, confID, threshold]
  488. );
  489. const mapByTimestamp = this.mapServiceCheckDataByTimestamp(result.rows);
  490. const errors: ServiceCheckData[] = [];
  491. for (const entry of mapByTimestamp.entries()) {
  492. const time = entry[0];
  493. const data = entry[1];
  494. const errorData = data.filter(d => d.status !== HttpCheckStatus.OK);
  495. if (!errorData.length) break;
  496. errors.push({
  497. time: new Date(time),
  498. data: errorData
  499. });
  500. }
  501. return errors;
  502. }
  503. private mapServiceCheckDataByTimestamp(rows: any[]) {
  504. return rows.reduce((res: Map<number, ServiceCheckDataEntry[]>, row) => {
  505. const time: number = row['Timestamp'];
  506. if (!res.has(time)) res.set(time, []);
  507. res.get(time)?.push({
  508. status: row['Status'] as number,
  509. message: row['Message']
  510. });
  511. return res;
  512. }, new Map()) as Map<number, ServiceCheckDataEntry[]>;
  513. }
  514. private configFromResultRows(rows: any[]) {
  515. return rows.reduce((res: ServiceConfig[], line, i) => {
  516. const configID = line['ID'];
  517. let config: ServiceConfig;
  518. if (i === 0 || res[res.length - 1].id !== configID) {
  519. config = {
  520. id: configID,
  521. title: line['Title'],
  522. type: line['Type'],
  523. serverId: line['ServerID'],
  524. params: []
  525. };
  526. res.push(config);
  527. } else {
  528. config = res[res.length - 1];
  529. }
  530. if (!!line['_ParamKey']) {
  531. const type = validateParamType(line['_ParamType']);
  532. const key = line['_ParamKey'];
  533. if (key === 'check') {
  534. let checkParam = config.params.find(c => c.key === 'check');
  535. if (!checkParam) {
  536. config.params.push(
  537. (checkParam = {
  538. key: 'check',
  539. type: 'regexp',
  540. value: []
  541. })
  542. );
  543. }
  544. (checkParam.value as string[]).push(line['_ParamValue']);
  545. } else {
  546. config.params.push({
  547. type,
  548. key,
  549. value: type === 'number' ? Number(line['_ParamValue']) : type === 'boolean' ? Boolean(Number(line['_ParamValue'])) : line['_ParamValue']
  550. });
  551. }
  552. }
  553. return res;
  554. }, [] as ServiceConfig[]);
  555. }
  556. private httpCheckConfigFrom(hcConf: ServiceConfig | null): HttpCheckConfig | null {
  557. if (!hcConf) return null;
  558. const params = {
  559. url: hcConf.params?.find(p => p.key === 'url')?.value as string,
  560. active: (hcConf.params?.find(p => p.key === 'active')?.value as boolean) ?? defaults.serviceChecks.active,
  561. interval: hcConf.params?.find(p => p.key === 'interval')?.value as number,
  562. timeout: (hcConf.params?.find(p => p.key === 'timeout')?.value as number) ?? defaults.serviceChecks.httpTimeout,
  563. notify: (hcConf.params?.find(p => p.key === 'notify')?.value as boolean) ?? defaults.serviceChecks.notify,
  564. notifyThreshold: (hcConf.params?.find(p => p.key === 'notifyThreshold')?.value as number) ?? defaults.serviceChecks.notifyThreshold,
  565. checks: hcConf.params?.reduce(
  566. (res, p) => (p.key === 'check' && Array.isArray(p.value) ? [...res, ...p.value.map(c => JSON.parse(c))] : res),
  567. [] as string[]
  568. )
  569. };
  570. return {
  571. id: hcConf.id,
  572. title: hcConf.title,
  573. type: hcConf.type,
  574. serverId: hcConf.serverId,
  575. ...params
  576. };
  577. }
  578. private validateHttpCheckConfig(conf: Partial<HttpCheckConfig>): { [key: string]: string } | null {
  579. const errors = {} as any;
  580. if (!conf) return { null: 'Object was null or undefined' };
  581. if (!conf.title?.trim().length) errors['required|title'] = `Field 'title' is required.`;
  582. if (!conf.url?.trim().length) errors['required|url'] = `Field 'url' is required.`;
  583. if ((!conf.interval && conf.interval !== 0) || Number.isNaN(Number(conf.interval))) errors['required|interval'] = `Field 'interval' is required.`;
  584. if (!conf.checks || !Array.isArray(conf.checks))
  585. errors['required|checks'] = `Field 'checks' is required and must be an array of check expressions.`;
  586. return Object.keys(errors).length ? errors : null;
  587. }
  588. }