-
Notifications
You must be signed in to change notification settings - Fork 15
/
covercouch.js
59 lines (49 loc) · 1.7 KB
/
covercouch.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
/**
* CoverCouch 0.1.5 main
* Read ACL for CouchDB
*
* Created by ermouth on 18.01.15.
*/
require('sugar');
var worker = require('./cvr/worker'),
runtime = {
cluster: require('cluster'),
root: __dirname
},
conf = require('./cvr/config')(runtime),
log = require('./cvr/logger')(runtime);
if (runtime.cluster.isMaster) {
var cpus = conf.workers.count || require('os').cpus().length,
fs = require('fs'),
workers = [];
// On worker die
runtime.cluster.on('exit', function (worker) {
for (var i = 0; i < workers.length; i++) if (worker.id == workers[i].id) workers[i] = null;
workers = workers.compact(true);
workers.push(runtime.cluster.fork());
});
fs.watch(runtime.root + '/cvr/config.js', function (event, filename) {
_restart('Config changed');
});
// Fork workers
for (var i = 0; i < cpus; i++) workers.push(runtime.cluster.fork());
// Restarter
var _restart = function (msg) {
log('Restart workers: ' + msg);
var i = workers.length;
while (i--) _stop.fill(workers[i]).delay(i * conf.workers.reloadOverlap);
},
_stop = function (w) {
if (w) {
w.send({event: 'shutdown', time: Date.now()});
_kill.fill(w).delay(conf.workers.killDelay);
}
},
_kill = function (w) {
if (w && w.suicide === undefined) w.kill();
},
_restarter = function () {
if (Date.create().getHours() == (conf.workers.reloadAt || 0)) _restart('Daily restart');
},
restarter = setInterval(_restarter, 36e5);
} else if (runtime.cluster.isWorker) worker(runtime);