database.class.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 { ServiceConfig, validateParamType } from '../../../common/interfaces/service-config.interface';
  7. import { Logger } from '../../../common/util/logger.class';
  8. import { ValidationException } from '../lib/validation-exception.class';
  9. import { DBMigration } from './db-migration.class';
  10. import { SQLiteController } from './sqlite-controller.base';
  11. export class Database extends SQLiteController {
  12. public set onError(listener: (error: any) => void) {
  13. this._onError = listener;
  14. }
  15. private _onError: (error: any) => void = err => console.error('[DB.ONERROR]', err);
  16. public async open(migrate = false) {
  17. try {
  18. const DATA_DIR = process.env.DATA_DIR || 'data';
  19. if (!fs.existsSync(DATA_DIR)) await fsp.mkdir(DATA_DIR);
  20. const DATA_FILE = path.resolve(DATA_DIR, 'data.db');
  21. const exists = fs.existsSync(DATA_FILE);
  22. await new Promise<void>((res, rej) => {
  23. this.db = new SQLiteDB(DATA_FILE, OPEN_READWRITE | OPEN_CREATE, err => (err ? rej(err) : res()));
  24. this.db.on('error', this._onError);
  25. });
  26. Logger.info('[INFO]', exists ? 'Opened' : 'Created', 'SQLite3 Database file', DATA_FILE);
  27. if (!exists) {
  28. // INITIAL TABLE SETUP
  29. await this.run(
  30. `CREATE TABLE Server (
  31. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  32. Title TEXT NOT NULL UNIQUE,
  33. FQDN TEXT NOT NULL UNIQUE
  34. );`,
  35. []
  36. );
  37. await this.run(
  38. `CREATE TABLE ServerConfig (
  39. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  40. ServerID INTEGER NOT NULL,
  41. Key TEXT NOT NULL,
  42. Value TEXT NOT NULL,
  43. FOREIGN KEY(ServerID) REFERENCES Server(ID),
  44. UNIQUE(ServerID, Key)
  45. )`,
  46. []
  47. );
  48. await this.run(
  49. `CREATE TABLE ServerDataEntry (
  50. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  51. ServerID INTEGER NOT NULL,
  52. Timestamp INTEGER NOT NULL,
  53. FOREIGN KEY(ServerID) REFERENCES Server(ID),
  54. UNIQUE(ServerID, Timestamp)
  55. );`,
  56. []
  57. );
  58. await this.run(
  59. `CREATE TABLE ServerDataValue (
  60. ID INTEGER PRIMARY KEY AUTOINCREMENT,
  61. EntryID INTEGER NOT NULL,
  62. Type Text NOT NULL,
  63. Key TEXT NOT NULL,
  64. Value REAL NOT NULL,
  65. FOREIGN KEY(EntryID) REFERENCES ServerDataEntry(ID),
  66. UNIQUE(EntryID, Type, Key)
  67. );`,
  68. []
  69. );
  70. let result = await this.run(`INSERT INTO Server(Title, FQDN) VALUES(?, ?);`, ['Raspi4', '10.8.0.10']);
  71. const serverID = result.lastID;
  72. Logger.debug(`[DEBUG] Created Server #${serverID}`);
  73. result = await this.run(`INSERT INTO ServerConfig(ServerID, Key, Value) VALUES(?, ?, ?);`, [serverID, 'syncInterval', 300]);
  74. }
  75. if (migrate) {
  76. // RUN DB MIGRATIONS
  77. const mig = new DBMigration(this.db);
  78. await mig.update();
  79. }
  80. } catch (err) {
  81. Logger.error('[FATAL] Initializing Database failed:', err);
  82. Logger.error('[EXITING]');
  83. process.exit(1);
  84. }
  85. }
  86. public async getAllServerConfigs(): Promise<Server[]> {
  87. const res = await this.stmt(
  88. `SELECT
  89. Server.*,
  90. ServerConfig.Key,
  91. ServerConfig.Value
  92. FROM Server
  93. LEFT OUTER JOIN ServerConfig ON Server.ID = ServerConfig.ServerID
  94. ORDER BY Server.Title, ServerConfig.Key`,
  95. []
  96. );
  97. return res.rows.reduce((res: Server[], line, i) => {
  98. const serverID = line['ID'];
  99. let server: Server;
  100. if (i === 0 || res[res.length - 1].id !== serverID) {
  101. server = { id: serverID, title: line['Title'], fqdn: line['FQDN'], config: {} };
  102. res.push(server);
  103. } else {
  104. server = res[res.length - 1];
  105. }
  106. if (!!line['Key']) {
  107. server.config[line['Key']] = line['Value'];
  108. }
  109. return res;
  110. }, [] as Server[]);
  111. }
  112. public async insertServerData(serverID: number, data: ReducedData[]) {
  113. if (!data.length) return;
  114. await this.beginTransaction();
  115. try {
  116. for (const entry of data) {
  117. const result = await this.run('INSERT INTO ServerDataEntry(ServerID, Timestamp) VALUES(?, ?);', [serverID, entry.time.getTime()]);
  118. let entryID = result.lastID;
  119. for (const type of Object.keys(entry).filter(t => !['time', 'hdd'].includes(t))) {
  120. for (const key of Object.keys((entry as any)[type])) {
  121. await this.run('INSERT INTO ServerDataValue(EntryID, Type, Key, Value) VALUES(?, ?, ?, ?);', [
  122. entryID,
  123. type,
  124. key,
  125. (entry as any)[type][key]
  126. ]);
  127. }
  128. }
  129. if (entry.hdd) {
  130. for (const mount of Object.keys(entry.hdd)) {
  131. for (const key of Object.keys(entry.hdd[mount])) {
  132. await this.run('INSERT INTO ServerDataValue(EntryID, Type, Key, Value) VALUES(?, ?, ?, ?);', [
  133. entryID,
  134. `hdd:${mount}`,
  135. key,
  136. (entry.hdd[mount] as any)[key]
  137. ]);
  138. }
  139. }
  140. }
  141. }
  142. await this.commit();
  143. } catch (err) {
  144. await this.rollback();
  145. throw err;
  146. }
  147. }
  148. public async getServerDataTypes(serverID: number) {
  149. const results = await this.stmt(
  150. `
  151. SELECT
  152. ServerDataValue.Type
  153. FROM ServerDataEntry
  154. JOIN ServerDataValue ON ServerDataEntry.ID = ServerDataValue.EntryID
  155. WHERE ServerDataEntry.ServerID = ?
  156. GROUP BY ServerDataValue.Type
  157. ORDER BY ServerDataValue.Type;
  158. `,
  159. [serverID]
  160. );
  161. return results.rows.reduce((res: Array<ServerDataTypesConfig>, { Type: type }) => {
  162. if (!type.startsWith('hdd:')) {
  163. res.push({ type });
  164. } else {
  165. let hdd = res.find(c => c.type === 'hdd');
  166. if (!hdd) {
  167. hdd = { type: 'hdd', subtypes: [] };
  168. res.push(hdd);
  169. }
  170. hdd.subtypes?.push({ type: type.substring(4) });
  171. }
  172. return res;
  173. }, []) as Array<ServerDataTypesConfig>;
  174. }
  175. public async queryServerData(serverID: number, type: ServerDataType, from: Date, to: Date): Promise<ServerData[]> {
  176. const diffMs = moment(to).diff(moment(from));
  177. const sectionMs = Math.floor(diffMs / 100);
  178. const select_max = type !== 'cpu';
  179. const select_types = select_max ? [type, type, type] : [type, type];
  180. const result = await this.stmt(
  181. `
  182. SELECT
  183. CEIL(Timestamp / ?) * ? as 'Timegroup',
  184. AVG(VALUE_AVG.Value) as 'avg',
  185. MAX(VALUE_PEAK.Value) as 'peak'${
  186. select_max
  187. ? `,
  188. MAX(VALUE_MAX.Value) as 'max'`
  189. : ''
  190. }
  191. FROM ServerDataEntry
  192. JOIN ServerDataValue AS VALUE_AVG ON ServerDataEntry.ID = VALUE_AVG.EntryID AND VALUE_AVG.Type = ? AND VALUE_AVG.Key = 'avg'
  193. JOIN ServerDataValue AS VALUE_PEAK ON ServerDataEntry.ID = VALUE_PEAK.EntryID AND VALUE_PEAK.Type = ? AND VALUE_PEAK.Key = 'peak'
  194. ${
  195. select_max
  196. ? "JOIN ServerDataValue AS VALUE_MAX ON ServerDataEntry.ID = VALUE_MAX.EntryID AND VALUE_MAX.Type = ? AND VALUE_MAX.Key = 'max'"
  197. : ''
  198. }
  199. WHERE ServerDataEntry.ServerID = ?
  200. AND ServerDataEntry.Timestamp BETWEEN ? AND ?
  201. GROUP BY Timegroup
  202. ORDER BY Timegroup;
  203. `,
  204. [sectionMs, sectionMs, ...select_types, serverID, from.getTime(), to.getTime()]
  205. );
  206. return result.rows.map(r => ({ time: new Date(r.Timegroup), avg: r.avg, peak: r.peak, max: r.max }));
  207. }
  208. private async getHealthCheckConfigs(serverID: number) {
  209. const res = await this.stmt(
  210. `SELECT
  211. HealthCheckConfig.*,
  212. HealthCheckParams.Type as '_ParamType',
  213. HealthCheckParams.Key as '_ParamKey',
  214. HealthCheckParams.Value as '_ParamValue'
  215. FROM HealthCheckConfig
  216. LEFT OUTER JOIN HealthCheckParams ON HealthCheckConfig.ID = HealthCheckParams.ConfigID
  217. WHERE HealthCheckConfig.ServerID = ?
  218. ORDER BY HealthCheckConfig.Title, _ParamType, _ParamKey`,
  219. [serverID]
  220. );
  221. return this.configFromResultRows(res.rows);
  222. }
  223. public async getHttpCheckConfigs(serverID: number) {
  224. return (await this.getHealthCheckConfigs(serverID)).map(this.httpCheckConfigFrom);
  225. }
  226. private async getHealthCheckConfigByID(serverID: number, configID: number) {
  227. if (!serverID && !configID) return null;
  228. const res = await this.stmt(
  229. `SELECT
  230. HealthCheckConfig.*,
  231. HealthCheckParams.Type as '_ParamType',
  232. HealthCheckParams.Key as '_ParamKey',
  233. HealthCheckParams.Value as '_ParamValue'
  234. FROM HealthCheckConfig
  235. LEFT OUTER JOIN HealthCheckParams ON HealthCheckConfig.ID = HealthCheckParams.ConfigID
  236. WHERE HealthCheckConfig.ID = ?
  237. AND HealthCheckConfig.ServerID = ?
  238. ORDER BY HealthCheckConfig.Title, _ParamType, _ParamKey`,
  239. [configID, serverID]
  240. );
  241. if (!res.rows.length) return null;
  242. const configs = this.configFromResultRows(res.rows);
  243. return configs[0];
  244. }
  245. public async getHttpCheckConfigByID(serverID: number, configID: number) {
  246. return this.httpCheckConfigFrom(await this.getHealthCheckConfigByID(serverID, configID));
  247. }
  248. public async saveHttpCheckConfig(serverID: number, conf: HttpCheckConfig) {
  249. const validationErrors = this.validateHttpCheckConfig(conf);
  250. if (validationErrors) throw new ValidationException('Validation of HttpCheckConfig object failed', validationErrors);
  251. conf.serverId = serverID;
  252. const oldConf = await this.getHttpCheckConfigByID(serverID, conf.id);
  253. await this.beginTransaction();
  254. try {
  255. if (oldConf) {
  256. // UPDATE
  257. if (oldConf.title !== conf.title) {
  258. await this.stmt('UPDATE HealthCheckConfig SET Title = ?', [conf.title]);
  259. }
  260. let updValues: any[][] = [];
  261. if (oldConf.interval !== conf.interval) updValues.push([conf.interval, conf.id, 'interval']);
  262. if (oldConf.url !== conf.url) updValues.push([conf.url, conf.id, 'url']);
  263. if (updValues.length) {
  264. for (const data of updValues) {
  265. await this.run(`UPDATE HealthCheckParams SET Value = ? WHERE ConfigID = ? AND Key = ?;`, data);
  266. }
  267. }
  268. const res = await this.stmt('SELECT * FROM HealthCheckParams WHERE ConfigID = ? and Key = "check";', [conf.id]);
  269. updValues = [];
  270. const delIDs: any[][] = [];
  271. res.rows.forEach((row, i) => {
  272. if (i < conf.checks.length) {
  273. updValues.push([conf.checks[i], row['ID']]);
  274. } else {
  275. delIDs.push(row['ID']);
  276. }
  277. });
  278. if (delIDs.length) {
  279. const delSql = 'DELETE FROM HealthCheckParams WHERE ID IN (?);';
  280. await this.run(delSql, [delIDs]);
  281. }
  282. if (updValues.length) {
  283. for (const data of updValues) {
  284. await this.run('UPDATE HealthCheckParams SET Value = ? WHERE ID = ?;', data);
  285. }
  286. }
  287. const insValues = conf.checks.filter((c, i) => i > res.rows.length - 1).map(c => [conf.id, 'regexp', 'check', c]);
  288. if (insValues.length) {
  289. for (const data of insValues) {
  290. await this.run('INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES(?, ?, ?, ?);', data);
  291. }
  292. }
  293. } else {
  294. // INSERT
  295. const res = await this.run('INSERT INTO HealthCheckConfig(ServerID, Type, Title) VALUES(?, ?, ?);', [serverID, 'http', conf.title]);
  296. const insCheckValues = conf.checks.map(c => [res.lastID, 'regexp', 'check', c]);
  297. await this.run(
  298. `INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value) VALUES
  299. (?, ?, ?, ?),
  300. (?, ?, ?, ?)${conf.checks.length ? `,${insCheckValues.map(() => '(?, ?, ?, ?)').join(',')}` : ''}`,
  301. [
  302. ...[res.lastID, 'text', 'url', conf.url],
  303. ...[res.lastID, 'number', 'interval', conf.interval],
  304. ...conf.checks.reduce((res, arr) => [...res, ...arr], [] as any[])
  305. ]
  306. );
  307. }
  308. await this.commit();
  309. return conf;
  310. } catch (err) {
  311. await this.rollback();
  312. throw err;
  313. }
  314. }
  315. private configFromResultRows(rows: any[]) {
  316. return rows.reduce((res: ServiceConfig[], line, i) => {
  317. const configID = line['ID'];
  318. let config: ServiceConfig;
  319. if (i === 0 || res[res.length - 1].id !== configID) {
  320. config = {
  321. id: configID,
  322. title: line['Title'],
  323. type: line['Type'],
  324. params: []
  325. };
  326. res.push(config);
  327. } else {
  328. config = res[res.length - 1];
  329. }
  330. if (!!line['_ParamKey']) {
  331. const type = validateParamType(line['_ParamType']);
  332. const key = line['_ParamKey'];
  333. if (key === 'check') {
  334. let checkParam = config.params.find(c => c.key === 'check');
  335. if (!checkParam) {
  336. config.params.push(
  337. (checkParam = {
  338. key: 'check',
  339. type: 'regexp',
  340. value: []
  341. })
  342. );
  343. }
  344. (checkParam.value as string[]).push(line['_ParamValue']);
  345. } else {
  346. config.params.push({
  347. type,
  348. key,
  349. value: type === 'number' ? Number(line['_ParamValue']) : line['_ParamValue']
  350. });
  351. }
  352. }
  353. return res;
  354. }, [] as ServiceConfig[]);
  355. }
  356. private httpCheckConfigFrom(hcConf: ServiceConfig | null): HttpCheckConfig | null {
  357. if (!hcConf) return null;
  358. const params = {
  359. url: hcConf.params?.find(p => p.key === 'url')?.value as string,
  360. interval: hcConf.params?.find(p => p.key === 'interval')?.value as number,
  361. checks: hcConf.params?.reduce((res, p) => (p.key === 'check' && Array.isArray(p.value) ? [...res, ...p.value] : res), [] as string[])
  362. };
  363. return {
  364. id: hcConf.id,
  365. title: hcConf.title,
  366. type: hcConf.type,
  367. ...params
  368. };
  369. }
  370. private validateHttpCheckConfig(conf: Partial<HttpCheckConfig>): { [key: string]: string } | null {
  371. const errors = {} as any;
  372. if (!conf) return { null: 'Object was null or undefined' };
  373. if (!conf.title?.trim().length) errors['required|title'] = `Field 'title' is required.`;
  374. if (!conf.url?.trim().length) errors['required|url'] = `Field 'url' is required.`;
  375. if ((!conf.interval && conf.interval !== 0) || Number.isNaN(Number(conf.interval))) errors['required|interval'] = `Field 'interval' is required.`;
  376. if (!conf.checks || !Array.isArray(conf.checks))
  377. errors['required|checks'] = `Field 'checks' is required and must be an array of check expressions.`;
  378. return Object.keys(errors).length ? errors : null;
  379. }
  380. }