/
hostStatus.js
60 lines (53 loc) · 2.18 KB
/
hostStatus.js
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
import { binary } from 'source/common/format.js'
import { isString, isBasicFunction } from 'source/common/check.js'
import { runStdout } from 'source/node/run.js'
import { describeSystemStatus } from 'source/node/system/Status.js'
// TODO: allow user change || overwrite commands
const IS_WIN32 = process.platform === 'win32'
const IS_DARWIN = process.platform === 'darwin'
const COMMON_HOST_STATUS_COMMAND_LIST = [
// [ title, ...tryList ]
[ 'Disk', async (rootPath) => {
if (IS_WIN32) { // win32 alternative, sample stdout: `27 Dir(s) 147,794,321,408 bytes free`
const freeByteString = (await runQuick('cmd.exe /C dir', rootPath))
.match(/ ([\d,]+) bytes free/)[ 1 ]
.replace(/\D/g, '')
return `${binary(Number(freeByteString))}B free storage`
} else {
const diskStatus = await runQuick('df -h .', rootPath)
if (!diskStatus.includes('/dev/')) return diskStatus // on remote-mount fs, skip `du` check (may be slow)
return [ diskStatus, 'Usage', await runQuick('du -hd1', rootPath) ].join('\n')
}
} ],
!IS_WIN32 && [ 'Network', 'vnstat -s' ],
[ 'System',
IS_DARWIN
? 'top -l1 -n0'
: async (rootPath) => (await runQuick('top -bn1', rootPath)).split('\n').slice(0, 5).join('\n'),
() => describeSystemStatus()
],
[ 'Time', () => new Date().toISOString() ]
].filter(Boolean)
const runQuick = async (command, rootPath) => String(await runStdout(command.split(' '), { cwd: rootPath }))
const runStatusCommand = async (statusCommand, rootPath) => {
let output = ''
if (isString(statusCommand)) output = await runQuick(statusCommand, rootPath)
else if (isBasicFunction(statusCommand)) output = await statusCommand(rootPath)
return output
}
const getCommonHostStatus = async (rootPath, statusCommandList = COMMON_HOST_STATUS_COMMAND_LIST) => {
const resultList = []
for (const [ title, ...tryList ] of statusCommandList) {
let output = ''
for (const statusCommand of tryList) {
output = await runStatusCommand(statusCommand, rootPath).catch(() => '')
if (output) break
}
resultList.push([ title, output ])
}
return resultList
}
export {
COMMON_HOST_STATUS_COMMAND_LIST,
getCommonHostStatus
}