-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.js
executable file
·102 lines (85 loc) · 2.33 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
const chokidar = require('chokidar')
const cluster = require('cluster')
const config = require('./config')
const fs = require('fs')
const path = require('path')
// Console start message
const dadiBoot = require('@dadi/boot')
dadiBoot.start(require('./package.json'))
require('console-stamp')(console, 'yyyy-mm-dd HH:MM:ss.l')
if (config.get('cluster')) {
if (cluster.isMaster) {
const numWorkers = require('os').cpus().length
console.log('Master cluster setting up ' + numWorkers + ' workers...')
for (let i = 0; i < numWorkers; i++) {
cluster.fork()
}
cluster.on('online', function(worker) {
console.log('Worker ' + worker.process.pid + ' is online')
})
cluster.on('exit', function(worker, code, signal) {
console.log(
'Worker ' +
worker.process.pid +
' died with code: ' +
code +
', and signal: ' +
signal
)
console.log('Starting a new worker')
cluster.fork()
})
const watcher = chokidar.watch(process.cwd(), {
depth: 0,
ignored: /[/\\]\./,
ignoreInitial: true
})
watcher.on('add', function(filePath) {
if (path.basename(filePath) === 'restart.cdn') {
console.log('Shutdown requested')
fs.unlinkSync(filePath)
restartWorkers()
}
})
} else {
const app = (module.exports = require('./dadi/lib'))
app.start(function() {
console.log(
'Process ' + process.pid + ' is listening for incoming requests'
)
process.on('message', function(message) {
if (message.type === 'shutdown') {
console.log('Process ' + process.pid + ' is shutting down...')
process.exit(0)
}
})
})
}
} else {
const app = (module.exports = require('./dadi/lib'))
app.start(function() {
console.log(
'Process ' + process.pid + ' is listening for incoming requests'
)
})
}
function restartWorkers() {
let wid
const workerIds = []
for (wid in cluster.workers) {
workerIds.push(wid)
}
workerIds.forEach(function(wid) {
if (cluster.workers[wid]) {
cluster.workers[wid].send({
type: 'shutdown',
from: 'master'
})
setTimeout(function() {
if (cluster.workers[wid]) {
cluster.workers[wid].kill('SIGKILL')
}
}, 5000)
}
})
}