-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
88 lines (75 loc) · 2.03 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
'use strict';
const fs = require('fs');
const os = require('os');
/**
Cluster Server
@class
@classdesc ClusterService
@param {Object} [opts] - configuration object
*/
class ClusterService {
constructor(opts = {}) {
this.opts = opts;
this.logger = opts.logger;
this.serviceName = opts.serviceName || 'srv';
this.mode = opts.mode || 'development';
this.pidDir = opts.pidDir || os.tmpdir();
this.workerCount = opts.workerCount || undefined;
this.nodeOptions = opts.nodeOptions || '';
}
run(path) {
if (this.mode.startsWith('production')) {
this.runProduction(path);
} else {
this.runDevelopment(path);
}
}
runProduction(path) {
const recluster = require('recluster');
const opts = {
workers: this.workerCount,
backoff: true,
logger: this.logger
};
const cluster = recluster(path, opts);
cluster.run();
process.on('SIGUSR2', () => {
this.logger.info('Master received reload signal (SIGUSR2), instructing workers to reload.');
cluster.reload();
});
process.on('SIGTERM', () => {
this.logger.info('Master received kill signal (SIGTERM), instructing workers to terminate.');
cluster.terminate();
});
this.cluster = cluster;
this.pid = process.pid;
this.writePid();
}
runDevelopment(path) {
const opts = {
silent: false,
killTree: true,
watch: false,
watchDirectory: '.',
watchIgnoreDotFiles: true,
command: `node${this.nodeOptions}`,
env: { WORKER_ID: 1 }
};
this.forever = require('forever-monitor');
const child = this.forever.start(path, opts);
this.foreverChild = child;
this.pid = child.child.pid;
}
stop() {
if (this.mode.startsWith('development')) {
this.foreverChild.stop();
} else {
this.cluster.terminate(() => {
});
}
}
writePid() {
fs.writeFileSync(`${this.pidDir}/cluster-serverice-master-${this.serviceName}.pid`, process.pid.toString(10), 'utf8');
}
}
module.exports = ClusterService;