Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use asynchronous operations everywhere to avoid blocking the main thread #948

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions lib/audio.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
// ----------------------------------------------------------------------------------

const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const util = require('./util');
const execAsync = util.execAsync;

let _platform = process.platform;

Expand Down Expand Up @@ -55,11 +55,11 @@ function parseAudioType(str, input, output) {
}


function getLinuxAudioPci() {
async function getLinuxAudioPci() {
let cmd = 'lspci -v 2>/dev/null';
let result = [];
try {
const parts = execSync(cmd, util.execOptsLinux).toString().split('\n\n');
const parts = (await execAsync(cmd, util.execOptsLinux)).toString().split('\n\n');
parts.forEach(element => {
const lines = element.split('\n');
if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) {
Expand Down Expand Up @@ -154,10 +154,10 @@ function audio(callback) {
let result = [];
if (_linux || _freebsd || _openbsd || _netbsd) {
let cmd = 'lspci -vmm 2>/dev/null';
exec(cmd, function (error, stdout) {
exec(cmd, async function (error, stdout) {
// PCI
if (!error) {
const audioPCI = getLinuxAudioPci();
const audioPCI = await getLinuxAudioPci();
const parts = stdout.toString().split('\n\n');
parts.forEach(element => {
const lines = element.split('\n');
Expand Down
4 changes: 2 additions & 2 deletions lib/battery.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
module.exports = function (callback) {

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {
let result = {
hasBattery: false,
cycleCount: 0,
Expand Down Expand Up @@ -100,7 +100,7 @@ module.exports = function (callback) {
}

if (acPath) {
const file = fs.readFileSync(acPath);
const file = await fs.promises.readFile(acPath);
acConnected = file.toString().trim() === '1';
}

Expand Down
10 changes: 5 additions & 5 deletions lib/bluetooth.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
// ----------------------------------------------------------------------------------

const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const path = require('path');
const util = require('./util');
const execAsync = util.execAsync;
const fs = require('fs');

let _platform = process.platform;
Expand Down Expand Up @@ -112,24 +112,24 @@ function parseWindowsBluetooth(lines) {
function bluetoothDevices(callback) {

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {
let result = [];
if (_linux) {
// get files in /var/lib/bluetooth/ recursive
const btFiles = util.getFilesInPath('/var/lib/bluetooth/');
btFiles.forEach((element) => {
btFiles.forEach(async (element) => {
const filename = path.basename(element);
const pathParts = element.split('/');
const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null;
const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null;
if (filename === 'info') {
const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n');
const infoFile = (await fs.promises.readFile(element, { encoding: 'utf8' })).split('\n');
result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2));
}
});
// determine "connected" with hcitool con
try {
const hdicon = execSync('hcitool con', util.execOptsLinux).toString().toLowerCase();
const hdicon = (await execAsync('hcitool con', util.execOptsLinux)).toString().toLowerCase();
for (let i = 0; i < result.length; i++) {
if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) {
result[i].connected = true;
Expand Down
18 changes: 9 additions & 9 deletions lib/cpu.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@

const os = require('os');
const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const fs = require('fs');
const util = require('./util');
const execAsync = util.execAsync;

let _platform = process.platform;

Expand Down Expand Up @@ -676,7 +676,7 @@ function getCpu() {
result.flags = flags;
result.virtualization = flags.indexOf('vmx') > -1 || flags.indexOf('svm') > -1;
if (_darwin) {
exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', function (error, stdout) {
exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', async function (error, stdout) {
let lines = stdout.toString().split('\n');
const modelline = util.getValue(lines, 'machdep.cpu.brand_string');
const modellineParts = modelline.split('@');
Expand All @@ -702,7 +702,7 @@ function getCpu() {
if (os.arch() === 'arm64') {
result.socket = 'SOC';
try {
const clusters = execSync('ioreg -c IOPlatformDevice -d 3 -r | grep cluster-type').toString().split('\n');
const clusters = (await execAsync('ioreg -c IOPlatformDevice -d 3 -r | grep cluster-type')).toString().split('\n');
const efficiencyCores = clusters.filter(line => line.indexOf('"E"') >= 0).length;
const performanceCores = clusters.filter(line => line.indexOf('"P"') >= 0).length;
result.efficiencyCores = efficiencyCores;
Expand All @@ -728,7 +728,7 @@ function getCpu() {
let modelline = '';
let lines = [];
if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) {
exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', async function (error, stdout) {
if (!error) {
lines = stdout.toString().split('\n');
}
Expand Down Expand Up @@ -777,7 +777,7 @@ function getCpu() {

// Test Raspberry
if (result.vendor === 'ARM') {
const linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
const linesRpi = (await fs.promises.readFile('/proc/cpuinfo')).toString().split('\n');
const rPIRevision = util.decodePiCpuinfo(linesRpi);
if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) {
result.family = result.manufacturer;
Expand Down Expand Up @@ -1037,7 +1037,7 @@ exports.cpuCurrentSpeed = cpuCurrentSpeed;
function cpuTemperature(callback) {

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {
let result = {
main: null,
cores: [],
Expand All @@ -1049,7 +1049,7 @@ function cpuTemperature(callback) {
// CPU Chipset, Socket
try {
const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;';
const parts = execSync(cmd, util.execOptsLinux).toString().split('-----\n');
const parts = (await execAsync(cmd, util.execOptsLinux)).toString().split('-----\n');
if (parts.length === 2) {
const lines = parts[0].split('\n');
const lines2 = parts[1].split('\n');
Expand Down Expand Up @@ -1579,7 +1579,7 @@ exports.cpuCache = cpuCache;
function getLoad() {

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {
let loads = os.loadavg().map(function (x) { return x / util.cores(); });
let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
let result = {};
Expand All @@ -1605,7 +1605,7 @@ function getLoad() {
// linux: try to get other cpu stats
if (_linux) {
try {
const lines = execSync('cat /proc/stat 2>/dev/null | grep cpu', util.execOptsLinux).toString().split('\n');
const lines = (await execAsync('cat /proc/stat 2>/dev/null | grep cpu', util.execOptsLinux)).toString().split('\n');
if (lines.length > 1) {
lines.shift();
if (lines.length === cpus.length) {
Expand Down
47 changes: 23 additions & 24 deletions lib/filesystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ const util = require('./util');
const fs = require('fs');

const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const execPromiseSave = util.promisifySave(require('child_process').exec);
const execAsync = util.execAsync;

let _platform = process.platform;

Expand Down Expand Up @@ -115,7 +114,7 @@ function fsSize(drive, callback) {
}

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {
let data = [];
if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
let cmd = '';
Expand All @@ -124,10 +123,10 @@ function fsSize(drive, callback) {
if (_darwin) {
cmd = 'df -kP';
try {
macOsDisks = execSync('diskutil list').toString().split('\n').filter(line => {
macOsDisks = (await execAsync('diskutil list')).toString().split('\n').filter(line => {
return !line.startsWith('/') && line.indexOf(':') > 0;
});
execSync('mount').toString().split('\n').filter(line => {
(await execAsync('mount')).toString().split('\n').filter(line => {
return line.startsWith('/');
}).forEach((line) => {
osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
Expand All @@ -139,7 +138,7 @@ function fsSize(drive, callback) {
if (_linux) {
try {
cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL';
execSync('cat /proc/mounts 2>/dev/null', util.execOptsLinux).toString().split('\n').filter(line => {
(await execAsync('cat /proc/mounts 2>/dev/null', util.execOptsLinux)).toString().split('\n').filter(line => {
return line.startsWith('/');
}).forEach((line) => {
osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false;
Expand All @@ -154,7 +153,7 @@ function fsSize(drive, callback) {
if (_freebsd || _openbsd || _netbsd) {
try {
cmd = 'df -lkPT';
execSync('mount').toString().split('\n').forEach((line) => {
(await execAsync('mount')).toString().split('\n').forEach((line) => {
osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
});
} catch (e) {
Expand Down Expand Up @@ -420,13 +419,13 @@ function decodeMdabmData(lines) {
};
}

function raidMatchLinux(data) {
async function raidMatchLinux(data) {
// for all block devices of type "raid%"
let result = data;
try {
data.forEach(element => {
for (let element of data) {
if (element.type.startsWith('raid')) {
const lines = execSync(`mdadm --export --detail /dev/${element.name}`, util.execOptsLinux).toString().split('\n');
const lines = (await execAsync(`mdadm --export --detail /dev/${element.name}`, util.execOptsLinux)).toString().split('\n');
const mdData = decodeMdabmData(lines);

element.label = mdData.label; // <- assign label info
Expand All @@ -441,7 +440,7 @@ function raidMatchLinux(data) {
});
}
}
});
}
} catch (e) {
util.noop();
}
Expand Down Expand Up @@ -570,27 +569,27 @@ function blkStdoutToObject(stdout) {
function blockDevices(callback) {

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {
let data = [];
if (_linux) {
// see https://wiki.ubuntuusers.de/lsblk/
// exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) {
exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, async function (error, stdout) {
if (!error) {
let lines = blkStdoutToObject(stdout).split('\n');
data = parseBlk(lines);
data = raidMatchLinux(data);
data = await raidMatchLinux(data);
data = matchDevicesLinux(data);
if (callback) {
callback(data);
}
resolve(data);
} else {
exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, async function (error, stdout) {
if (!error) {
let lines = blkStdoutToObject(stdout).split('\n');
data = parseBlk(lines);
data = raidMatchLinux(data);
data = await raidMatchLinux(data);
}
if (callback) {
callback(data);
Expand Down Expand Up @@ -1056,7 +1055,7 @@ function diskLayout(callback) {
}

return new Promise((resolve) => {
process.nextTick(() => {
process.nextTick(async () => {

const commitResult = res => {
for (let i = 0; i < res.length; i++) {
Expand All @@ -1074,7 +1073,7 @@ function diskLayout(callback) {
if (_linux) {
let cmdFullSmart = '';

exec('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
exec('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, async function (error, stdout) {
if (!error) {
try {
const out = stdout.toString().trim();
Expand All @@ -1087,20 +1086,20 @@ function diskLayout(callback) {
} catch (e) {
// fallback to older version of lsblk
try {
const out2 = execSync('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString();
const out2 = (await execAsync('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL', util.execOptsLinux)).toString();
let lines = blkStdoutToObject(out2).split('\n');
const data = parseBlk(lines);
devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); });
} catch (e) {
util.noop();
}
}
devices.forEach((device) => {
for (let device of devices) {
let mediumType = '';
const BSDName = '/dev/' + device.name;
const logical = device.name;
try {
mediumType = execSync('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null', util.execOptsLinux).toString().split('\n')[0];
mediumType = (await execAsync('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null', util.execOptsLinux)).toString().split('\n')[0];
} catch (e) {
util.noop();
}
Expand Down Expand Up @@ -1131,7 +1130,7 @@ function diskLayout(callback) {
});
cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`;
cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`;
});
}
} catch (e) {
util.noop();
}
Expand Down Expand Up @@ -1406,10 +1405,10 @@ function diskLayout(callback) {
workload.push(util.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl'));
if (util.smartMonToolsInstalled()) {
try {
const smartDev = JSON.parse(execSync('smartctl --scan -j').toString());
const smartDev = JSON.parse((await execAsync('smartctl --scan -j')).toString());
if (smartDev && smartDev.devices && smartDev.devices.length > 0) {
smartDev.devices.forEach((dev) => {
workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util.execOptsWin));
workload.push(execAsync(`smartctl -j -a ${dev.name}`, util.execOptsWin).catch(() => ''));
});
}
} catch (e) {
Expand Down
Loading