forked from alphagov/pay-frontend
-
Notifications
You must be signed in to change notification settings - Fork 1
/
start.js
75 lines (64 loc) · 1.67 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
75
(function () {
'use strict'
var path = require('path')
var fs = require('fs')
const logger = require('./app/utils/logger')(__filename)
var throng = require('throng')
var server = require('./server')
var environment = require('./app/services/environment')
var pidFile = path.join(__dirname, '/.start.pid')
var fileOptions = { encoding: 'utf-8' }
var pid
logger.info(`[process.version=${process.version}] [NODE_VERSION=${process.env.NODE_VERSION}]`)
/**
* throng is a wrapper around node cluster
* https://github.com/hunterloftis/throng
*/
function start () {
throng({
workers: environment.getWorkerCount(),
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)
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()
}())