Skip to content

Instantly share code, notes, and snippets.

@yurynix
Created July 16, 2019 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurynix/16d96f3e3b5ef2a6a8ed9f96f29cbfd3 to your computer and use it in GitHub Desktop.
Save yurynix/16d96f3e3b5ef2a6a8ed9f96f29cbfd3 to your computer and use it in GitHub Desktop.
const child_process = require('child_process');
const util = require('util');
const fs = require('fs');
const readfile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);
const readlink = util.promisify(fs.readlink);
async function getRunningPids(): Promise<number[]> {
const files = await readdir(`/proc`);
const pids = files
.map((file: string) => parseInt(file, 10))
.filter((pid: number) => !isNaN(pid) && pid !== process.pid && pid !== 1);
return pids;
}
interface ExeData {
exe: string;
pid: number;
}
async function getRunningExecutables(): Promise<ExeData[]> {
const pids = await getRunningPids();
const results = await Promise.all(
pids.map(async (pid: number) => {
try {
const exe = await readlink(`/proc/${pid}/exe`);
return {
exe,
pid,
};
} catch (ex) {
// We might get EACCESS here, since we get the list of all process
// and not all of them belongs to us.
return null;
}
}),
);
return results.filter(result => result) as ExeData[];
}
// based on https://unix.stackexchange.com/questions/62154/when-was-a-process-started
async function getProcessUptimeInSeconds(pid: number) {
const processStat = (await readfile(`/proc/${pid}/stat`)).toString();
const systeUptime = (await readfile(`/proc/uptime`)).toString();
const processStartTime = parseInt(processStat.split(' ')[21], 10) / 100;
const uptime = parseInt(systeUptime.split(' ')[0], 10);
return uptime - processStartTime;
}
describe('lambda health', () => {
it('should run only one chrome', async () => {
const exes = await getRunningExecutables();
const secondsSinceStart = await getProcessUptimeInSeconds(exes[0].pid);
expect(exes.length).toEqual(1);
expect(exes[0].exe).toEqual('/tmp/chromium');
expect(secondsSinceStart).toBeLessThan(60);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment