database.class.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. private async getHealthCheckConfigs(serverID?: number, type = 'http') {
  221. const res = await this.stmt(
  222. `SELECT
  223. HealthCheckConfig.*,
  224. HealthCheckParams.Type as '_ParamType',
  225. HealthCheckParams.Key as '_ParamKey',
  226. HealthCheckParams.Value as '_ParamValue'
  227. FROM HealthCheckConfig
  228. LEFT OUTER JOIN HealthCheckParams ON HealthCheckConfig.ID = HealthCheckParams.ConfigID
  229. WHERE HealthCheckConfig.Type = ?
  230. ${!!serverID ? 'AND HealthCheckConfig.ServerID = ?' : ''}
  231. ORDER BY HealthCheckConfig.Title, _ParamType, _ParamKey`,
  232. [type, serverID]
  233. );
  234. return this.configFromResultRows(res.rows);
  235. }
  236. public async getHttpCheckConfigs(serverID?: number) {
  237. return (await this.getHealthCheckConfigs(serverID)).map(this.httpCheckConfigFrom);
  238. }
  239. private async getHealthCheckConfigByID(serverID: number, configID: number) {
  240. if (!serverID && !configID) return null;
  241. const res = await this.stmt(
  242. `SELECT
  243. HealthCheckConfig.*,
  244. HealthCheckParams.Type as '_ParamType',
  245. HealthCheckParams.Key as '_ParamKey',
  246. HealthCheckParams.Value as '_ParamValue'
  247. FROM HealthCheckConfig
  248. LEFT OUTER JOIN HealthCheckParams ON HealthCheckConfig.ID = HealthCheckParams.ConfigID
  249. WHERE HealthCheckConfig.ID = ?
  250. AND HealthCheckConfig.ServerID = ?
  251. ORDER BY HealthCheckConfig.Title, _ParamType, _ParamKey`,
  252. [configID, serverID]
  253. );
  254. if (!res.rows.length) return null;
  255. const configs = this.configFromResultRows(res.rows);
  256. return configs[0];
  257. }
  258. public async getHttpCheckConfigByID(serverID: number, configID: number) {
  259. return this.httpCheckConfigFrom(await this.getHealthCheckConfigByID(serverID, configID));
  260. }
  261. public async saveHttpCheckConfig(serverID: number, conf: HttpCheckConfig) {
  262. const validationErrors = this.validateHttpCheckConfig(conf);
  263. if (validationErrors) throw new ValidationException('Validation of HttpCheckConfig object failed', validationErrors);
  264. conf.serverId = serverID;
  265. let status = ServiceChangedStatus.None;
  266. const oldConf = await this.getHttpCheckConfigByID(serverID, conf.id);
  267. await this.beginTransaction();
  268. try {
  269. if (oldConf) {
  270. // UPDATE
  271. if (oldConf.title !== conf.title) {
  272. await this.stmt('UPDATE HealthCheckConfig SET Title = ?', [conf.title]);
  273. }
  274. let updValues: any[][] = [];
  275. if (oldConf.url !== conf.url) updValues.push([conf.url, conf.id, 'url']);
  276. if (oldConf.interval !== conf.interval) {
  277. updValues.push([conf.interval, conf.id, 'interval']);
  278. status = ServiceChangedStatus.Rescheduled;
  279. }
  280. if (oldConf.timeout !== conf.timeout) updValues.push([conf.timeout ?? defaults.serviceChecks.httpTimeout, conf.id, 'timeout']);
  281. if (oldConf.active !== conf.active) {
  282. updValues.push([conf.active ?? defaults.serviceChecks.active ? 1 : 0, conf.id, 'active']);
  283. status = conf.active ?? defaults.serviceChecks.active ? ServiceChangedStatus.Activated : ServiceChangedStatus.Deactivated;
  284. }
  285. if (updValues.length) {
  286. for (const data of updValues) {
  287. await this.run(`UPDATE HealthCheckParams SET Value = ? WHERE ConfigID = ? AND Key = ?;`, data);
  288. }
  289. }
  290. const res = await this.stmt('SELECT * FROM HealthCheckParams WHERE ConfigID = ? and Key = "check";', [conf.id]);
  291. updValues = [];
  292. const delIDs: number[] = [];
  293. res.rows.forEach((row, i) => {
  294. if (i < conf.checks.length) {
  295. updValues.push([conf.checks[i], row['ID']]);
  296. } else {
  297. delIDs.push(row['ID']);
  298. }
  299. });
  300. if (delIDs.length) {
  301. const delSql = 'DELETE FROM HealthCheckParams WHERE ID IN (?);';
  302. await this.run(delSql, [delIDs]);
  303. }
  304. if (updValues.length) {
  305. for (const data of updValues) {
  306. await this.run('UPDATE HealthCheckParams SET Value = ? WHERE ID = ?;', data);
  307. }
  308. }
  309. const insValues = conf.checks.filter((c, i) => i > res.rows.length - 1).map(c => [conf.id, 'regexp', 'check', c]);
  310. if (insValues.length) {
  311. for (const data of insValues) {
  312. await this.run('INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES(?, ?, ?, ?);', data);
  313. }
  314. }
  315. } else {
  316. // INSERT
  317. const res = await this.run('INSERT INTO HealthCheckConfig(ServerID, Type, Title) VALUES(?, ?, ?);', [serverID, 'http', conf.title]);
  318. conf.id = res.lastID;
  319. if (conf.active ?? defaults.serviceChecks.active) {
  320. status = ServiceChangedStatus.Created;
  321. }
  322. const insCheckValues = conf.checks.map(c => [res.lastID, 'regexp', 'check', c]);
  323. await this.run(
  324. `INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES
  325. (?, ?, ?, ?),
  326. (?, ?, ?, ?),
  327. (?, ?, ?, ?),
  328. (?, ?, ?, ?)${conf.checks.length ? `,${insCheckValues.map(() => '(?, ?, ?, ?)').join(',')}` : ''}`,
  329. [
  330. ...[res.lastID, 'text', 'url', conf.url],
  331. ...[res.lastID, 'boolean', 'active', conf.active ?? defaults.serviceChecks.active ? 1 : 0],
  332. ...[res.lastID, 'number', 'interval', conf.interval],
  333. ...[res.lastID, 'number', 'timeout', conf.timeout ?? defaults.serviceChecks.httpTimeout],
  334. ...conf.checks.reduce((ret, check) => [...ret, res.lastID, 'regexp', 'check', check], [] as any[])
  335. ]
  336. );
  337. }
  338. await this.commit();
  339. return { status, result: conf };
  340. } catch (err) {
  341. await this.rollback();
  342. throw err;
  343. }
  344. }
  345. async deleteHealthCheckConfig(serverID: number, confID: number) {
  346. const conf = await this.getHealthCheckConfigByID(serverID, confID);
  347. if (!conf) return false;
  348. await this.run('DELETE FROM HealthCheckConfig WHERE ID = ?;', [confID]);
  349. return true;
  350. }
  351. async insertHealthCheckData(confID: number, time: Date, status: HttpCheckStatus, message: string) {
  352. const res = await this.run('INSERT INTO HealthCheckDataEntry(ConfigID, Timestamp, Status, Message) VALUES(?, ?, ?, ?);', [
  353. confID,
  354. time.getTime(),
  355. status,
  356. message
  357. ]);
  358. return {
  359. id: res.lastID,
  360. configId: confID,
  361. time,
  362. status,
  363. message
  364. } as HttpCheckData;
  365. }
  366. async queryServiceCheckData(serverID: number, confID: number, from: Date, to: Date) {
  367. const result = await this.stmt(
  368. `
  369. SELECT
  370. HealthCheckDataEntry.*
  371. FROM HealthCheckDataEntry
  372. JOIN HealthCheckConfig ON HealthCheckConfig.ID = HealthCheckDataEntry.ConfigID
  373. WHERE HealthCheckConfig.ServerID = ?
  374. AND HealthCheckDataEntry.ConfigID = ?
  375. AND HealthCheckDataEntry.Timestamp BETWEEN ? AND ?
  376. ORDER BY Timestamp, ID;
  377. `,
  378. [serverID, confID, from.getTime(), to.getTime()]
  379. );
  380. const mapByTimestamp = result.rows.reduce((res: Map<number, ServiceCheckDataEntry[]>, row) => {
  381. const time: number = row['Timestamp'];
  382. if (!res.has(time)) res.set(time, []);
  383. res.get(time)?.push({
  384. status: row['Status'] as number,
  385. message: row['Message']
  386. });
  387. return res;
  388. }, new Map()) as Map<number, ServiceCheckDataEntry[]>;
  389. const arr: ServiceCheckData[] = [];
  390. for (const entry of mapByTimestamp.entries()) {
  391. arr.push({
  392. time: new Date(entry[0]),
  393. data: entry[1]
  394. });
  395. }
  396. return arr;
  397. }
  398. private configFromResultRows(rows: any[]) {
  399. return rows.reduce((res: ServiceConfig[], line, i) => {
  400. const configID = line['ID'];
  401. let config: ServiceConfig;
  402. if (i === 0 || res[res.length - 1].id !== configID) {
  403. config = {
  404. id: configID,
  405. title: line['Title'],
  406. type: line['Type'],
  407. serverId: line['ServerID'],
  408. params: []
  409. };
  410. res.push(config);
  411. } else {
  412. config = res[res.length - 1];
  413. }
  414. if (!!line['_ParamKey']) {
  415. const type = validateParamType(line['_ParamType']);
  416. const key = line['_ParamKey'];
  417. if (key === 'check') {
  418. let checkParam = config.params.find(c => c.key === 'check');
  419. if (!checkParam) {
  420. config.params.push(
  421. (checkParam = {
  422. key: 'check',
  423. type: 'regexp',
  424. value: []
  425. })
  426. );
  427. }
  428. (checkParam.value as string[]).push(line['_ParamValue']);
  429. } else {
  430. config.params.push({
  431. type,
  432. key,
  433. value: type === 'number' ? Number(line['_ParamValue']) : type === 'boolean' ? Boolean(Number(line['_ParamValue'])) : line['_ParamValue']
  434. });
  435. }
  436. }
  437. return res;
  438. }, [] as ServiceConfig[]);
  439. }
  440. private httpCheckConfigFrom(hcConf: ServiceConfig | null): HttpCheckConfig | null {
  441. if (!hcConf) return null;
  442. const params = {
  443. url: hcConf.params?.find(p => p.key === 'url')?.value as string,
  444. active: (hcConf.params?.find(p => p.key === 'active')?.value as boolean) ?? defaults.serviceChecks.active,
  445. interval: hcConf.params?.find(p => p.key === 'interval')?.value as number,
  446. timeout: (hcConf.params?.find(p => p.key === 'timeout')?.value as number) ?? defaults.serviceChecks.httpTimeout,
  447. checks: hcConf.params?.reduce((res, p) => (p.key === 'check' && Array.isArray(p.value) ? [...res, ...p.value] : res), [] as string[])
  448. };
  449. return {
  450. id: hcConf.id,
  451. title: hcConf.title,
  452. type: hcConf.type,
  453. serverId: hcConf.serverId,
  454. ...params
  455. };
  456. }
  457. private validateHttpCheckConfig(conf: Partial<HttpCheckConfig>): { [key: string]: string } | null {
  458. const errors = {} as any;
  459. if (!conf) return { null: 'Object was null or undefined' };
  460. if (!conf.title?.trim().length) errors['required|title'] = `Field 'title' is required.`;
  461. if (!conf.url?.trim().length) errors['required|url'] = `Field 'url' is required.`;
  462. if ((!conf.interval && conf.interval !== 0) || Number.isNaN(Number(conf.interval))) errors['required|interval'] = `Field 'interval' is required.`;
  463. if (!conf.checks || !Array.isArray(conf.checks))
  464. errors['required|checks'] = `Field 'checks' is required and must be an array of check expressions.`;
  465. return Object.keys(errors).length ? errors : null;
  466. }
  467. }