-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsystemInformation.ts
More file actions
712 lines (654 loc) · 17.6 KB
/
Copy pathsystemInformation.ts
File metadata and controls
712 lines (654 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import si from 'systeminformation';
import logger from '../logging/harper_logger.ts';
import * as hdbTerms from '../hdbTerms.ts';
import { getQuotaStatus } from '../../server/storageReclamation.ts';
import { lmdbGetTableSize } from '../../dataLayer/harperBridge/lmdbBridge/lmdbUtility/lmdbGetTableSize.ts';
import { getThreadInfo } from '../../server/threads/manageThreads.js';
import * as env from './environmentManager.ts';
import { getDatabases, type Table } from '../../resources/databases.ts';
import { TableSizeObject } from '../../dataLayer/harperBridge/TableSizeObject.ts';
import { RocksDatabase, StatsHistogramData } from '@harperfast/rocksdb-js';
env.initSync();
//this will hold the system_information which is static to improve performance
let systemInformationCache = undefined;
export class SystemInformationRequest {
operator: string;
attributes: string[];
constructor(attributes) {
this.operator = hdbTerms.OPERATIONS_ENUM.SYSTEM_INFORMATION;
this.attributes = attributes;
}
}
export class SystemInformationResponse {
system?: SystemInfo;
time?: TimeData;
cpu?: CpuInfo;
memory?: MemoryInfo;
disk?: DiskInfo;
network?: NetworkInfo;
harperdb_processes?: HarperdbProcesses;
table_size?: TableSizeObject[];
metrics?: DatabaseMetrics;
threads?: Record<string, unknown>;
constructor(
system?: SystemInfo,
time?: TimeData,
cpu?: CpuInfo,
memory?: MemoryInfo,
disk?: DiskInfo,
network?: NetworkInfo,
harperdbProcesses?: HarperdbProcesses,
tableSize?: TableSizeObject[],
metrics?: DatabaseMetrics,
threads?: Record<string, unknown>
) {
this.system = system;
this.time = time;
this.cpu = cpu;
this.memory = memory;
this.disk = disk;
this.network = network;
this.harperdb_processes = harperdbProcesses;
this.table_size = tableSize;
this.metrics = metrics;
this.threads = threads;
}
}
type TimeData = si.Systeminformation.TimeData;
/**
* Returns the current local time, uptime, timezone, and timezone name.
*/
export function getTimeInfo(): TimeData {
return si.time();
}
type CpuInfo = Pick<
si.Systeminformation.CpuData,
| 'manufacturer'
| 'brand'
| 'vendor'
| 'speed'
| 'cores'
| 'physicalCores'
| 'performanceCores'
| 'efficiencyCores'
| 'processors'
| 'flags'
| 'virtualization'
> & {
cpu_speed: si.Systeminformation.CpuCurrentSpeedData;
current_load: Pick<
si.Systeminformation.CurrentLoadData,
| 'avgLoad'
| 'currentLoad'
| 'currentLoadUser'
| 'currentLoadSystem'
| 'currentLoadNice'
| 'currentLoadIdle'
| 'currentLoadIrq'
> & {
cpus: Pick<
si.Systeminformation.CurrentLoadCpuData,
'load' | 'loadUser' | 'loadSystem' | 'loadNice' | 'loadIdle' | 'loadIrq'
>[];
};
};
/**
* Detects CPU information such as manufacturer, brand, vendor, speed, cores, physical cores, and
* processors.
*/
export async function getCPUInfo(): Promise<CpuInfo | null> {
try {
const [cpu, cpu_speed, loadInfo] = await Promise.all([si.cpu(), si.cpuCurrentSpeed(), si.currentLoad()]);
const {
manufacturer,
brand,
vendor,
speed,
cores,
physicalCores,
performanceCores,
efficiencyCores,
processors,
flags,
virtualization,
} = cpu;
const {
avgLoad,
cpus,
currentLoad,
currentLoadUser,
currentLoadSystem,
currentLoadNice,
currentLoadIdle,
currentLoadIrq,
} = loadInfo;
return {
manufacturer,
brand,
vendor,
speed,
cores,
physicalCores,
performanceCores,
efficiencyCores,
processors,
flags,
virtualization,
cpu_speed,
current_load: {
avgLoad,
cpus: cpus.map(({ load, loadUser, loadSystem, loadNice, loadIdle, loadIrq }) => ({
load,
loadUser,
loadSystem,
loadNice,
loadIdle,
loadIrq,
})),
currentLoad,
currentLoadUser,
currentLoadSystem,
currentLoadNice,
currentLoadIdle,
currentLoadIrq,
},
};
} catch (e) {
logger.error(`error in getCPUInfo: ${e}`);
return null;
}
}
type MemoryInfo = Pick<
si.Systeminformation.MemData,
| 'total'
| 'free'
| 'used'
| 'active'
| 'available'
| 'reclaimable'
| 'swaptotal'
| 'swapused'
| 'swapfree'
| 'writeback'
| 'dirty'
> &
NodeJS.MemoryUsage;
/**
* Detect system and Node.js memory usage.
*/
export async function getMemoryInfo(): Promise<MemoryInfo | null> {
try {
const { total, free, used, active, available, reclaimable, swaptotal, swapused, swapfree, writeback, dirty } =
await si.mem();
return {
total,
free,
used,
active,
available,
reclaimable,
swaptotal,
swapused,
swapfree,
writeback,
dirty,
...process.memoryUsage(),
};
} catch (e) {
logger.error(`error in getMemoryInfo: ${e}`);
return null;
}
}
async function getHdbPid(): Promise<number | null> {
try {
return Number.parseInt(
await readFile(path.join(env.get(hdbTerms.CONFIG_PARAMS.ROOTPATH), hdbTerms.HDB_PID_FILE), 'utf8')
);
} catch (err) {
if (err.code === hdbTerms.NODE_ERROR_CODES.ENOENT) {
logger.warn(
`Unable to locate 'hdb.pid' file, try stopping and starting Harper. This could be because Harper is not running.`
);
} else {
throw err;
}
}
}
type CoreInfo = si.Systeminformation.ProcessesProcessData & { parent?: string };
type HarperdbProcesses = {
core: CoreInfo[];
};
/**
* Detects the Harper process PID and returns the process info.
* @returns {Promise<{core: []}>}
*/
export async function getHDBProcessInfo(): Promise<HarperdbProcesses> {
const harperdbProcesses: HarperdbProcesses = {
core: [],
};
try {
const [processes, hdbPid] = await Promise.all([si.processes(), getHdbPid()]);
const proc = processes.list.find((p) => p.pid === hdbPid);
if (proc) {
harperdbProcesses.core.push(proc);
}
} catch (e) {
logger.error(`error in getHDBProcessInfo: ${e}`);
}
return harperdbProcesses;
}
type DiskInfo = {
io?: Pick<si.Systeminformation.DisksIoData, 'rIO' | 'wIO' | 'tIO'>;
read_write?: Pick<si.Systeminformation.FsStatsData, 'rx' | 'tx' | 'wx'>;
size?: si.Systeminformation.FsSizeData[];
free_space_basis?: 'quota' | 'filesystem';
quota_size_bytes?: number;
quota_used_bytes?: number;
quota_status_age_seconds?: number;
};
/**
* Retrieves disk related info & stats
* @returns {Promise<DiskInfo>}
*/
export async function getDiskInfo(): Promise<DiskInfo> {
const disk: DiskInfo = {};
const quotaStatus = await getQuotaStatus();
if (quotaStatus?.quotaBytes) {
disk.free_space_basis = 'quota';
disk.quota_size_bytes = quotaStatus.quotaBytes;
disk.quota_used_bytes = quotaStatus.usedBytes;
disk.quota_status_age_seconds = Math.floor((Date.now() - quotaStatus.updatedAt) / 1000);
} else {
disk.free_space_basis = 'filesystem';
}
try {
if (!env.get(hdbTerms.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK)) return disk;
const [disksIO, fsStats, fsSize] = await Promise.all([si.disksIO(), si.fsStats(), si.fsSize()]);
const { rIO, wIO, tIO } = disksIO;
disk.io = { rIO, wIO, tIO };
const { rx, tx, wx } = fsStats;
disk.read_write = { rx, tx, wx };
disk.size = fsSize;
} catch (e) {
logger.error(`error in getDiskInfo: ${e}`);
}
return disk;
}
type NetworkInfo = {
default_interface: string | null;
latency: si.Systeminformation.InetChecksiteData | Record<never, never>;
interfaces: Pick<
si.Systeminformation.NetworkInterfacesData,
| 'iface'
| 'ifaceName'
| 'default'
| 'ip4'
| 'ip4subnet'
| 'ip6'
| 'ip6subnet'
| 'mac'
| 'operstate'
| 'type'
| 'duplex'
| 'speed'
>[];
stats: any[];
connections: any[];
};
/**
* Detects networking connection information & stats
* @returns {Promise<{interfaces: [], default_interface: null, stats: [], latency: {}, connections: []}>}
*/
export async function getNetworkInfo(): Promise<NetworkInfo> {
const network: NetworkInfo = {
default_interface: null,
latency: {},
interfaces: [],
stats: [],
connections: [],
};
try {
if (!env.get(hdbTerms.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)) return network;
const [defaultInterface, latency, nInterfaces, stats] = await Promise.all([
si.networkInterfaceDefault(),
si.inetChecksite('https://google.com').catch(() => ({})),
si.networkInterfaces(),
si.networkStats(),
]);
network.default_interface = defaultInterface || null;
network.latency = latency;
for (const nInterface of nInterfaces) {
const {
iface,
ifaceName,
default: isDefault,
ip4,
ip4subnet,
ip6,
ip6subnet,
mac,
operstate,
type,
duplex,
speed,
} = nInterface;
network.interfaces.push({
iface,
ifaceName,
default: isDefault,
ip4,
ip4subnet,
ip6,
ip6subnet,
mac,
operstate,
type,
duplex,
speed,
});
}
for (const nStat of stats) {
const { iface, operstate, rx_bytes, rx_dropped, rx_errors, tx_bytes, tx_dropped, tx_errors } = nStat;
network.stats.push({ iface, operstate, rx_bytes, rx_dropped, rx_errors, tx_bytes, tx_dropped, tx_errors });
}
} catch (e) {
logger.error(`error in getNetworkInfo: ${e}`);
}
return network;
}
type SystemInfo = Partial<
Pick<
si.Systeminformation.OsData,
'platform' | 'distro' | 'release' | 'codename' | 'kernel' | 'arch' | 'hostname' | 'fqdn'
>
> & {
node_version?: string;
npm_version?: string;
};
/**
* Detect operating system and Node.js runtime information.
* @returns {Promise<SystemInfo>}
*/
export async function getSystemInformation(): Promise<SystemInfo> {
if (systemInformationCache !== undefined) {
return systemInformationCache;
}
let systemInfo: SystemInfo = {};
try {
const [osInfo, versions] = await Promise.all([si.osInfo(), si.versions('node, npm')]);
const { platform, distro, release, codename, kernel, arch, hostname, fqdn } = osInfo;
const { node, npm } = versions;
systemInfo = {
platform,
distro,
release,
codename,
kernel,
arch,
hostname,
fqdn,
node_version: node,
npm_version: npm,
};
systemInformationCache = systemInfo;
} catch (e) {
logger.error(`error in getSystemInformation: ${e}`);
}
return systemInfo;
}
function rocksdbGetTableSize(table: Table): TableSizeObject {
const rocksdb: RocksDatabase = table.primaryStore;
const stats = rocksdb.getStats();
const transactionLogSize = rocksdb
.listLogs()
.reduce((sum, logName) => sum + rocksdb.useLog(logName).getLogFileSize(), 0);
return new TableSizeObject(
table.databaseName,
table.tableName,
(stats['rocksdb.estimate-live-data-size'] as number) ?? 0,
(stats['rocksdb.estimate-num-keys'] as number) ?? 0,
transactionLogSize
// transactionLogRecordCount - currently not supported by `rocksdb-js`
);
}
/**
* Retrieves table size information.
* @returns {TableSizeObject[]}
*/
export function getTableSize(): TableSizeObject[] {
const results: TableSizeObject[] = [];
const databases = getDatabases();
for (const db of Object.values(databases)) {
for (const table of Object.values(db)) {
if (table.primaryStore.rootStore instanceof RocksDatabase) {
results.push(rocksdbGetTableSize(table));
} else {
results.push(lmdbGetTableSize(table));
}
}
}
return results;
}
type LMDBEnvStats = {
entryCount: number;
overflowPages: number;
pageSize: number;
treeBranchPageCount: number;
treeDepth: number;
treeLeafPageCount: number;
};
type LMDBStats = LMDBEnvStats & {
free: LMDBEnvStats;
lastPageNumber: number;
lastTxnId: number;
mapSize: number;
maxReaders: number;
numReaders: number;
root: LMDBEnvStats;
};
const rocksDBDatabaseLevelStats = new Set<string>([
'blockCacheCapacity',
'blockCacheDataHit',
'blockCacheDataMiss',
'blockCacheFilterHit',
'blockCacheFilterMiss',
'blockCacheHit',
'blockCacheIndexHit',
'blockCacheIndexMiss',
'blockCacheMiss',
'blockCachePinnedUsage',
'blockCacheUsage',
'bytesRead',
'bytesWritten',
'dbFlushMicros',
'dbGetMicros',
'dbSeekMicros',
'dbWriteMicros',
'noFileErrors',
'numberKeysRead',
'numberKeysWritten',
'numberReseeksIteration',
'numRunningFlushes',
'oldestSnapshotTime',
'stallMicros',
'txnOverheadMutexOldCommitMap',
'txnOverheadMutexPrepare',
'txnOverheadMutexSnapshot',
]);
type RocksDBStats = {
blockCacheCapacity: number;
blockCacheDataHit: number;
blockCacheDataMiss: number;
blockCacheFilterHit: number;
blockCacheFilterMiss: number;
blockCacheHit: number;
blockCacheIndexHit: number;
blockCacheIndexMiss: number;
blockCacheMiss: number;
blockCachePinnedUsage: number;
blockCacheUsage: number;
bytesRead: number;
bytesWritten: number;
dbFlushMicros: StatsHistogramData;
dbGetMicros: StatsHistogramData;
dbSeekMicros: StatsHistogramData;
dbWriteMicros: StatsHistogramData;
noFileErrors: number;
numberKeysRead: number;
numberKeysWritten: number;
numberReseeksIteration: number;
numRunningFlushes: number;
oldestSnapshotTime: number;
stallMicros: number;
txnOverheadMutexOldCommitMap: number;
txnOverheadMutexPrepare: number;
txnOverheadMutexSnapshot: number;
};
type RocksDBTableStats = {
blobdbValueSize: StatsHistogramData;
bloomFilterFullPositive: number;
bloomFilterFullTruePositive: number;
bloomFilterUseful: number;
compactReadBytes: number;
compactWriteBytes: number;
compactionCancelled: number;
compactionPending: number;
compactionTimesMicros: StatsHistogramData;
curSizeActiveMemTable: number;
curSizeAllMemTables: number;
currentSuperVersionNumber: number;
dbIterBytesRead: number;
dbWriteStall: StatsHistogramData;
estimateLiveDataSize: number;
estimateNumKeys: number;
estimatePendingCompactionBytes: number;
liveBlobFileSize: number;
liveSstFilesSize: number;
memTableFlushPending: number;
memtableHit: number;
memtableMiss: number;
numBlobFiles: number;
numDeletesActiveMemTable: number;
numEntriesActiveMemTable: number;
numImmutableMemTable: number;
numImmutableMemTableFlushed: number;
numLiveVersions: number;
numRunningCompactions: number;
readAmpEstimateUsefulBytes: number;
readAmpTotalReadBytes: number;
sizeAllMemTables: number;
sstReadMicros: StatsHistogramData;
totalBlobFileSize: number;
totalSstFilesSize: number;
};
type TableStats =
| RocksDBTableStats
| Pick<LMDBStats, 'entryCount' | 'overflowPages' | 'treeBranchPageCount' | 'treeDepth' | 'treeLeafPageCount'>;
// Strips the "rocksdb." prefix and converts kebab-case to camelCase
function toRocksDBCamelCase(key: string): string {
return key.replace(/^rocksdb\./, '').replace(/[-.]([a-z])/g, (_, c: string) => c.toUpperCase());
}
type DBStats = RocksDBStats & {
audit?: Pick<LMDBStats, 'treeDepth' | 'treeBranchPageCount' | 'treeLeafPageCount' | 'entryCount' | 'overflowPages'>;
readers?: { pid: string; thread: string; txnid: string }[];
tables: Record<string, TableStats>;
};
type DatabaseMetrics = {
[dbName: string]: DBStats;
};
function getRocksDBStats(table: Table, dbStats: DBStats): void {
const stats = table.primaryStore.getStats();
const tableStats = (dbStats.tables[table.tableName] = {} as RocksDBTableStats);
for (const [key, value] of Object.entries(stats)) {
const name = toRocksDBCamelCase(key);
if (rocksDBDatabaseLevelStats.has(name)) {
dbStats[name] = value;
} else {
tableStats[name] = value;
}
}
}
function getLMDBStats(table: Table, dbStats: DBStats): void {
if (!dbStats.readers) {
const { root: _root, ...stats } = table.primaryStore.rootStore.getStats();
Object.assign(dbStats, stats);
dbStats.readers = table.primaryStore.rootStore
.readerList?.()
?.split(/\n\s+/)
.slice(1)
.map((line) => {
const [pid, thread, txnid] = line.trim().split(' ');
return { pid, thread, txnid };
});
if (table.auditStore) {
const { treeDepth, treeBranchPageCount, treeLeafPageCount, entryCount, overflowPages } =
table.auditStore.getStats();
dbStats.audit = { treeDepth, treeBranchPageCount, treeLeafPageCount, entryCount, overflowPages };
}
}
const { entryCount, overflowPages, treeBranchPageCount, treeDepth, treeLeafPageCount } =
table.primaryStore.getStats();
dbStats.tables[table.tableName] = { entryCount, overflowPages, treeBranchPageCount, treeDepth, treeLeafPageCount };
}
/**
* Get RocksDB or LMDB metrics for all databases and tables.
* @returns {Promise<DatabaseMetrics>}
*/
export async function getMetrics(): Promise<DatabaseMetrics> {
const databaseStats: DatabaseMetrics = {};
const databases = getDatabases();
for (const [dbName, db] of Object.entries(databases)) {
const dbStats = { tables: {} } as DBStats;
databaseStats[dbName] = dbStats;
for (const [tableName, table] of Object.entries(db)) {
try {
if (table.primaryStore.rootStore instanceof RocksDatabase) {
getRocksDBStats(table, dbStats);
} else {
getLMDBStats(table, dbStats);
}
} catch (error) {
// if a database no longer exists, don't want to throw an error
logger.notify(`Error getting stats for table ${tableName}: ${error}`);
}
}
}
return databaseStats;
}
const attributeMap: Record<string, () => Promise<any> | any> = {
system: getSystemInformation,
time: getTimeInfo,
cpu: getCPUInfo,
memory: getMemoryInfo,
disk: getDiskInfo,
network: getNetworkInfo,
harperdb_processes: getHDBProcessInfo,
table_size: getTableSize,
metrics: getMetrics,
threads: getThreadInfo,
};
/**
* Retrieves system information for the requested attributes.
* @param {SystemInformationRequest} systemInfoReq
* @returns {Promise<SystemInformationResponse>}
*/
export async function systemInformation(systemInfoReq: SystemInformationRequest): Promise<SystemInformationResponse> {
const attributes =
Array.isArray(systemInfoReq.attributes) && systemInfoReq.attributes.length > 0
? systemInfoReq.attributes
: Object.keys(attributeMap);
const response = new SystemInformationResponse();
await Promise.all(
attributes
.filter((attr) => attr in attributeMap)
.map(async (attr) => {
if (attr === 'database_metrics') {
attr = 'metrics';
}
response[attr] = await attributeMap[attr]();
})
);
return response;
}