-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
582 lines (499 loc) · 14.1 KB
/
index.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
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
const isRunning = require('is-running')
const Resource = require('nanoresource')
const pidusage = require('pidusage')
const pidtree = require('pidtree')
const assert = require('nanoassert')
const Batch = require('batch')
const spawn = require('cross-spawn')
const fkill = require('fkill')
const pfind = require('find-process')
const once = require('once')
const { PassThrough } = require('stream')
// quick util
const errback = (p, cb) => void p.then((r) => cb(null, r), cb).catch(cb)
const noop = () => void 0
const find = (pid, cb) => errback(pfind('pid', pid), cb)
const kill = (pid, o, cb) => errback(fkill(pid, o), cb)
// timeout in milliseconds to wait before calling `pidusage.clear()`
// after the usage of `pidusage()`. Timers are cleared on each use
// of the `pidusage()` function.
const PIDUSAGE_CLEAR_TIMEOUT = 1100
// timer from `setTimeout()` uses to call `pidusage.clear()` for
// event loop clean (https://github.com/soyuka/pidusage#pidusageclear)
// which is called
let pidusageClearTimer = 0
/**
* `PROCESS_CLOSED_ERR` is thrown when the `Process` instance
* is used after being closed.
* @private
*/
class PROCESS_CLOSED_ERR extends Error {
constructor() {
super('Process is closed.')
}
}
/**
* `PROCESS_NOT_RUNNING_ERR` is thrown when the `Process` instance
* is not yet running (typically when opening).
* @private
*/
class PROCESS_NOT_RUNNING_ERR extends Error {
constructor() {
super('Process not running.')
}
}
/**
* The `Stats` class represents a container of information
* about the runtime of the process.
* @private
*/
class Stats {
/**
* `Stats` class constructor.
* @private
* @param {Number} pid
*/
constructor(pid) {
this.bin = null // initial binary used invoke the child process
this.uid = 0 // user ID
this.gid = 0 // group ID
this.cpu = 0 // CPU usage as a percentage
this.pid = pid // child process ID
this.ppid = 0 // parent process ID of the child process
this.pids = [] // child process IDs of the child process
this.name = null // the name of process
this.atime = Date.now() // access time
this.uptime = 0 // time in milliseconds since process started
this.memory = 0 // memory usage bytes
this.command = null // the command used to start the child process
this._stdout = null
this._stderr = null
}
/**
* Accessor to return `true` if any process in the process tree
* is still running.
* @accessor
*/
get isRunning() {
return this.pids.concat(this.pid).some(isRunning)
}
}
/**
* The `Process` class represents an abstraction over a spawned child
* process managed by a `nanoresource` instance.
* @public
* @class
* @extends nanoresource
*/
class Process extends Resource {
/**
* `Process` class constructor
* @public
* @param {String} command
* @param {?(Array|String)} args
* @param {?(Object)} options
*/
constructor(command, args, options) {
super()
assert('string' === typeof command && command.length > 0,
'Command is not a string.')
if (args && 'object' === typeof args && !Array.isArray(args)) {
options = args
args = null
}
if ('string' === typeof args) {
args = args.split(' ')
}
this.options = options || {}
this.command = command
this.killedByProcess = false
this.process = null
this.exiting = false
this.exited = false
this.signal = null
this.code = null
this.ppid = null
this.args = Array.isArray(args) ? args : []
}
/**
* Accessor for getting the process pid.
* @accessor
*/
get pid() {
return this.process && this.process.pid
}
/**
* Accessor for getting the process stdin.
* @accessor
*/
get stdin() {
return this.process && this.process.stdin
}
/**
* Accessor for getting the process stdout.
* @accessor
*/
get stdout() {
return this._stdout
}
/**
* Accessor for getting the process stderr.
* @accessor
*/
get stderr() {
return this._stderr
}
/**
* Accessor for getting the process channel.
* @accessor
*/
get channel() {
return this.process && this.process.channel
}
/**
* Accessor for getting the process connection state.
* @accessor
*/
get connected() {
return Boolean(this.process && this.process.connected)
}
/**
* Accessor for getting the process killed state.
* @accessor
*/
get killed() {
const killed = Boolean(this.process && this.process.killed)
if (killed) {
this.killedByProcess = true
}
return this.killedByProcess || killed
}
/**
* `spawn()` implementation for extending classes to
* overload and provide a `ChildProcess` from some
* other means.
* @protected
* @param {String} command
* @param {?(Array|String)} args
* @param {?(Object)} options
* @param {Function} callback
*/
spawn(command, args, options, callback) {
if ('function' === typeof this.options.spawn) {
try {
this.options.spawn(command, args, options, callback)
} catch (err) {
callback(err)
}
} else {
try {
callback(null, spawn(command, args, options))
} catch (err) {
// istanbul ignore next
callback(err)
}
}
}
/**
* Implements the `_open()` methods for the `nanoresource` class.
* @protected
*/
_open(callback) {
const { command, options, args } = this
this.spawn(command, args, options, (err, child) => {
let bufferedError = Buffer.alloc(0)
let active = false
if (err) {
return callback(err)
}
callback = once(callback)
child.once('exit', (code, signal) => {
this.exiting = true
this.signal = signal
this.ppid = null
this.code = code || 0
child.removeAllListeners('exit')
if (active) {
this.inactive()
}
this.close(() => {
this.exited = true
this.exiting = false
})
})
child.once('error', callback)
// Pipe the child's stdout and stderr into passthrough streams
// so that all data right from the beginning is captured.
// The open callback is only invoked after a nextTick (due to stats capturing)
// and the stdout and stderr sockets do not buffer data after being closed.
if (child.stdout) {
this._stdout = new PassThrough()
child.stdout.pipe(this._stdout)
}
if (child.stderr) {
this._stderr = new PassThrough()
child.stderr.pipe(this._stderr)
child.stderr.on('data', onerrors)
}
// istanbul ignore next
function onerrors(err) {
bufferedError = Buffer.concat([bufferedError, Buffer.from('\n'), err])
}
this.stat(child, (err, stats) => {
// process may have ended before a stat
// is possible so `err` is `null` here
if (err && /not?|found/i.test(err.message)) {
err = null
}
if (child.stderr) {
child.stderr.removeListener('data', onerrors)
}
child.removeListener('error', callback)
this.process = child
if (stats && stats.ppid) {
this.ppid = stats.ppid
}
if (this.exiting || this.exited) {
// istanbul ignore next
if (this.code && bufferedError.length) {
return process.nextTick(callback, new Error(String(bufferedError)))
} else {
process.nextTick(callback, null)
// remite exit code and signal if exited right away during open
// istanbul ignore next
return process.nextTick(() => child.emit('exit', this.code, this.signal))
}
}
this.active()
active = true
process.nextTick(callback, err)
})
})
}
/**
* Closes the child process and all decedent child process in the process
* tree calling `callback(err)` when closed or if an error occurs during
* the closing of the spawned child process. Setting `allowActive` to
* `false` (default) will cause a `'SIGTERM'` to be sent to the child process
* causing it to close. You can call `child.kill({ force: true })` prior to
* calling this method if you want force the processed to be killed. Set
* `allowActive` to `true` to wait for the process to close on its and mark
* the [nanoresource][nanoresource] instance **inactive**.
* @public
* @param {?(Boolean)} allowActive
* @param {?(Function)} callback
*/
close(allowActive, callback) {
if ('function' === typeof allowActive) {
callback = allowActive
allowActive = false
}
// istanbul ignore next
if ('boolean' !== typeof allowActive) {
allowActive = false
}
// istanbul ignore next
if ('function' !== typeof callback) {
callback = noop
}
if (false === allowActive && this.process && this.process.pid) {
this.kill(noop)
}
return super.close(allowActive, callback)
}
/**
* Kill the child process.
* @public
* @param {?(Object)} opts
* @param {?(Boolean)} [opts.force = false]
* @param {Function} callback
*/
kill(opts, callback) {
if ('function' === typeof opts) {
callback = opts
opts = {}
}
assert('function' == typeof callback, 'Callback must be a function.')
if (null === this.process && (this.closed || this.closing)) {
return process.nextTick(callback, new PROCESS_CLOSED_ERR())
}
if (null === this.process) {
return process.nextTick(callback, new PROCESS_NOT_RUNNING_ERR())
}
if (undefined === opts.force) {
opts.force = false
}
kill(this.process.pid, opts, callback)
}
/**
* Implements the `_close()` methods for the `nanoresource` class.
* @protected
*/
_close(callback) {
this.opened = false
this.closed = true
this.opening = false
this.closing = false
this.process = null
process.nextTick(callback, null)
}
/**
* Queries statistics about the running process.
* @public
* @param {?(Object)} opts
* @param {?(Number)} opts.pid
* @param {?(Boolean)} [opts.shallow = false]
* @param {Function} callback
*/
stat(opts, callback) {
if ('function' === typeof opts) {
callback = opts
opts = {}
}
assert('function' == typeof callback, 'Callback must be a function.')
assert(opts && 'object' === typeof opts, 'Options must be an object.')
if (!opts || !opts.pid) {
if (null === this.process && (this.closed || this.closing)) {
return process.nextTick(callback, new PROCESS_CLOSED_ERR())
}
if (null === this.process) {
return process.nextTick(callback, new PROCESS_NOT_RUNNING_ERR())
}
}
// istanbul ignore next
const { pid = this.process ? this.process.pid : null } = opts
const stats = new Stats(pid)
const self = this
find(pid, onfind)
function onfind(err, results) {
// istanbul ignore next
if (err) { return callback(err) }
// istanbul ignore next
if (!results || false === Array.isArray(results)) {
return callback(null, new PROCESS_NOT_RUNNING_ERR())
}
const result = results[0]
if (result) {
Object.assign(stats, {
bin: result.bin,
uid: result.uid,
gid: result.gid,
name: result.name,
})
if (self.process && result.pid === self.process.pid) {
stats.command = self.command
} else {
stats.command = result.cmd
}
}
if (true === opts.shallow) {
pidusage([ pid ], onusage)
} else {
pidtree(pid, { root: true }, onpids)
}
}
function onpids(err, pids) {
// istanbul ignore next
if (err) { return callback(err) }
stats.pids = pids.filter((p) => p !== pid)
pidusage(pids, onusage)
}
function onusage(err, usages) {
clearTimeout(pidusageClearTimer)
pidusageClearTimer = setTimeout(pidusage.clear, PIDUSAGE_CLEAR_TIMEOUT)
// istanbul ignore if
if (err) {
return callback(err)
}
usages = Object.values(usages)
for (const usage of usages) {
if (usage && pid === usage.pid) {
stats.cpu = usage.cpu
stats.ppid = usage.ppid
stats.uptime = usage.elapsed
stats.memory = usage.memory
}
}
callback(null, stats)
}
}
/**
* Adds an event listener to the child process.
* @protected
*/
// istanbul ignore next
addListener(event, callback) {
if (this.process) {
return this.process.addListener(event, callback)
}
return false
}
/**
* Removes an event listener to the child process.
* @protected
*/
// istanbul ignore next
removeListener(event, callback) {
if (this.process) {
return this.process.removeListener(event, callback)
}
return false
}
/**
* Alias to `addListener()`.
* @protected
*/
on(event, callback) {
// istanbul ignore next
return this.addListener(event, callback)
}
/**
* Alias to `removeListener()`.
* @protected
*/
off(event, callback) {
// istanbul ignore next
return this.removeListener(event, callback)
}
/**
* Send a message to the child process.
* @see {@link https://nodejs.org/api/child_process.html#child_process_subprocess_send_message_sendhandle_options_callback}
* @return {Boolean}
*/
send(...args) {
// istanbul ignore next
if (this.process && 'function' === typeof this.process.send) {
return this.process.send(...args)
}
// istanbul ignore next
return false
}
/**
* Disconnect the child process.
* @see {@link https://nodejs.org/api/child_process.html#child_process_subprocess_disconnect}
*/
disconnect() {
// istanbul ignore next
if (this.process && 'function' === typeof this.process.disconnect) {
this.process.disconnect()
}
}
}
/**
* Factory for creating `Process` instances.
* @public
* @default
* @param {String} command
* @param {?(Array)} args
* @param {?(Object)} opts
* @return {Process}
*/
function createProcess(...args) {
return new Process(...args)
}
/**
* Module exports.
*/
module.exports = Object.assign(createProcess, {
Process,
})