This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
start.js
74 lines (63 loc) · 1.45 KB
/
start.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
'use strict'
const path = require('path')
const fs = require('fs')
const logger = require('pino')()
const throng = require('throng')
const server = require('./server')
const pidFile = path.join(__dirname, '/.start.pid')
const fileOptions = { encoding: 'utf-8' }
let pid
/**
* Throng is a wrapper around node cluster
* https://github.com/hunterloftis/throng
*/
function start () {
throng({
workers: process.env.NODE_WORKER_COUNT || 1,
master: startMaster,
start: startWorker
})
}
/**
* Start master process
*/
function startMaster () {
logger.info(`Master started. PID: ${process.pid}`)
process.on('SIGINT', () => {
logger.info(`Master exiting`)
process.exit()
})
}
/**
* Start cluster worker. Log start and exit
* @param {Number} workerId
*/
function startWorker (workerId) {
server.start()
logger.info(`Started worker ${workerId}, PID: ${process.pid}`)
process.on('SIGINT', () => {
logger.info(`Worker ${workerId} exiting...`)
process.exit()
})
}
/**
* Make sure all child processes are cleaned up
*/
function onInterrupt () {
pid = fs.readFileSync(pidFile, fileOptions)
fs.unlink(pidFile, (err) => {
if (err) throw err
console.log('File successfully deleted')
})
process.kill(pid, 'SIGTERM')
process.exit()
}
/**
* Keep track of processes, and clean up on SIGINT
*/
function monitor () {
fs.writeFileSync(pidFile, process.pid, fileOptions)
process.on('SIGINT', onInterrupt)
}
monitor()
start()