forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pm2Start.js
81 lines (72 loc) · 1.98 KB
/
pm2Start.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
require('dotenv').load();
var pm2 = require('pm2');
var nodemailer = require('nodemailer');
var moment = require('moment-timezone');
var _ = require('lodash');
var instances = process.env.INSTANCES || 1;
var serverName = process.env.SERVER_NAME || 'server';
var maxMemory = process.env.MAX_MEMORY || '390M';
var transportOptions = {
type: 'smtp',
service: 'Mandrill',
auth: {
user: process.env.MANDRILL_USER || false,
pass: process.env.MANDRILL_PASSWORD
}
};
var mailReceiver = process.env.MAIL_RECEIVER || false;
pm2.connect(function() {
pm2.start({
name: serverName,
script: 'server/production-start.js',
'exec_mode': 'cluster',
instances: instances,
'max_memory_restart': maxMemory,
'NODE_ENV': 'production'
}, function() {
console.log(
'pm2 started %s with %s instances at %s max memory',
serverName,
instances,
maxMemory
);
pm2.disconnect();
});
});
if (transportOptions.auth.user && mailReceiver) {
console.log('setting up mailer');
var transporter = nodemailer.createTransport(transportOptions);
var compiled = _.template(
'An error has occurred on server ' +
'<% name %>\n' +
'Stack Trace:\n\n\n<%= stack %>\n\n\n' +
'Context:\n\n<%= text %>'
);
pm2.launchBus(function(err, bus) {
if (err) {
return console.error(err);
}
console.log('event bus connected');
bus.on('process:exception', function(data) {
var text;
var stack;
var name;
try {
data.date = moment(data.at || new Date())
.tz('America/Los_Angeles')
.format('MMMM Do YYYY, h:mm:ss a z');
text = JSON.stringify(data, null, 2);
stack = data.data.stack;
name = data.process.name;
} catch (e) {
return e;
}
transporter.sendMail({
to: mailReceiver,
from: '[email protected]',
subject: 'Server exception',
text: compiled({ name: name, text: text, stack: stack })
});
});
});
}