UNPKG

1.93 kBJavaScriptView Raw
1'use strict'
2
3const fs = require('fs')
4const makeDir = require('mkdirp')
5const systemInfo = require('../collect/system-info.js')
6const ProcessStat = require('../collect/process-stat.js')
7const getLoggingPaths = require('@nearform/clinic-common').getLoggingPaths('doctor')
8const ProcessStatEncoder = require('../format/process-stat-encoder.js')
9
10// create encoding files and directory
11const paths = getLoggingPaths({ path: process.env.NODE_CLINIC_DOCTOR_DATA_PATH, identifier: process.pid })
12
13makeDir.sync(paths['/'])
14
15// write system file
16fs.writeFileSync(paths['/systeminfo'], JSON.stringify(systemInfo(), null, 2))
17
18const processStatEncoder = new ProcessStatEncoder()
19const out = processStatEncoder.pipe(fs.createWriteStream(paths['/processstat']))
20
21// sample every 10ms
22const processStat = new ProcessStat(parseInt(
23 process.env.NODE_CLINIC_DOCTOR_SAMPLE_INTERVAL, 10
24))
25
26// keep sample time unrefed such it doesn't interfere too much
27let timer = null
28function scheduleSample () {
29 timer = setTimeout(saveSample, processStat.sampleInterval)
30 timer.unref()
31}
32
33function saveSample () {
34 const sample = processStat.sample()
35 processStatEncoder.write(sample)
36 processStat.refresh()
37
38 scheduleSample()
39}
40
41// start sampler on next tick, to avoid measuring the startup time
42process.nextTick(function () {
43 processStat.refresh()
44 scheduleSample()
45})
46
47// before process exits, flush the encoded data to the sample file
48process.once('beforeExit', function () {
49 clearTimeout(timer)
50 processStatEncoder.end()
51 out.on('close', function () {
52 process.exit()
53 })
54})
55
56// NOTE: Workaround until https://github.com/nodejs/node/issues/18476 is solved
57process.on('SIGINT', function () {
58 if (process.listenerCount('SIGINT') === 1) process.emit('beforeExit')
59})
60
61process.on('SIGUSR2', function () {
62 // noop to avoid process ending on SIGUSR2
63})
64
65process.on('SIGUSR1', function () {
66 // noop to avoid process ending on SIGUSR1
67})