This repository has been archived by the owner on Aug 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
90 lines (57 loc) · 1.91 KB
/
server.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
/* eslint no-console: 0 */
const CHILD_EXIT_LIMIT = 5;
const CHILD_EXIT_THRESHOLD = 60000; //1 minute
const childProcess = require( 'child_process' );
const pkg = require( './package.json' );
let clusterFile = '/app/cluster.js';
const childExits = [];
let child;
if( !process.env.NODE_ENV || process.env.NODE_ENV === 'development' ){
clusterFile = ( '/src/' + clusterFile );
}
function createChildProcess(){
child = childProcess.fork( __dirname + clusterFile );
console.info( 'Child process created, pid: ' + child.pid );
child.on( 'exit', handleChildExit );
}
function handleChildExit( e ){
const now = Date.now();
let exitsInLastMinute = 0;
console.log( 'Child exits so far: %d', childExits.length );
if( childExits.length >= CHILD_EXIT_LIMIT ){
childExits.slice( -CHILD_EXIT_LIMIT ).forEach( function( item ){
var delta = now - item;
if( delta < CHILD_EXIT_THRESHOLD ){
exitsInLastMinute++;
}
} );
}
console.log( 'Child exits in last minute: %d', exitsInLastMinute );
if( exitsInLastMinute >= CHILD_EXIT_LIMIT ){
console.log( 'Too many exits within the last minute, not spawning new child' );
} else {
console.error( 'Process terminated, restarting...', e );
childExits.push( Date.now() );
createChildProcess();
}
}
function createErrorHandler( type ){
return function(){
console.log( 'Parent event: %s', type );
if( child ){
child.kill();
child = null;
}
process.exit( 0 );
};
}
process.on( 'unhandledException', createErrorHandler( 'unhandled exception' ) );
process.on( 'SIGTERM', createErrorHandler( 'SIGTERM' ) );
process.on( 'SIGINT', createErrorHandler( 'SIGINT' ) );
process.on( 'SIGQUIT', createErrorHandler( 'SIGQUIT' ) );
process.on( 'exit', createErrorHandler( 'exit' ) );
process.on( 'message', function( msg ){
console.log( 'server got message: ' + msg );
} );
console.log( 'Starting ' + pkg.name + ', version: ' + pkg.version );
createChildProcess();