├── .gitignore ├── LICENSE ├── README.md ├── config.example.yml ├── index.js ├── package.json ├── template.md └── test └── throw.js /.gitignore: -------------------------------------------------------------------------------- 1 | config.yml 2 | node_modules/ 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright © 2015 Antoine Bluchet 2 | 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU Affero General Public License as 5 | published by the Free Software Foundation, either version 3 of the 6 | License, or (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU Affero General Public License for more details. 12 | 13 | You should have received a copy of the GNU Affero General Public License 14 | along with this program. If not, see . 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## How does it work? 2 | 3 | We're listening on pm2 bus **automatic** events (manual exits won't be mailed). When an exit event happend we're keeping the pm2 process environnement in a queue. Those elements are then emailed through SMTP by using the famous [nodemailer](https://github.com/nodemailer/nodemailer). 4 | 5 | Templates can be customized, if you want to use another mailing protocol feel free to dig into the code! This is meant to be used out of the box with minimal configuration but it can't fit everyone needs. 6 | 7 | If you need better email interactions have a look at [Keymetrics](https://keymetrics.io/)! 8 | 9 | ## Configuration 10 | 11 | ``` 12 | mail: 13 | from: "me@example.com" 14 | to: "you@example.com" 15 | # see https://github.com/andris9/nodemailer-smtp-transport#usage 16 | smtp: 17 | host: "smtp.gmail.com" 18 | port: 25 19 | # Events list: 20 | # - restart 21 | # - delete 22 | # - stop 23 | # - restart overlimit 24 | # - exit 25 | # - start 26 | # - online 27 | events: 28 | - exit 29 | template: './template.md' 30 | # this is the process subject if there is only one event to be mailed 31 | subject: '<%= process.name %> errored (<%= process.NODE_ENV %>)' 32 | # if multiple events are going to be mailed, use a global subject: 33 | multiple_subject: 'Error on <%= hostname %>' 34 | #wait for 5 seconds after the last event before sending an email - avoid spam when a lot of events happened 35 | polling: 5000 36 | #if events are sent continuously, an email will be sent after 5 minutes anyway 37 | max_polling_time: 300000 38 | #attach your process logs to the email 39 | attach_logs: true 40 | ``` 41 | 42 | ## Templating 43 | 44 | This is how a standard pm2 object looks like: 45 | 46 | ``` 47 | { event: 'exit', 48 | manually: false, 49 | process: 50 | { name: 'throw', 51 | vizion: true, 52 | autorestart: true, 53 | exec_mode: 'fork_mode', 54 | exec_interpreter: 'node', 55 | pm_exec_path: '/usr/share/nginx/www/pm2-notify/throw.js', 56 | pm_cwd: '/usr/share/nginx/www/pm2-notify', 57 | instances: 1, 58 | node_args: [], 59 | pm_out_log_path: '/home/abluchet/.pm2/logs/throw-out-0.log', 60 | pm_err_log_path: '/home/abluchet/.pm2/logs/throw-error-0.log', 61 | pm_pid_path: '/home/abluchet/.pm2/pids/throw-0.pid', 62 | NODE_APP_INSTANCE: 0, 63 | NODE_ENV: 'production', 64 | 65 | ... //your env variables here 66 | 67 | status: 'stopped', 68 | pm_uptime: 1434096604224, 69 | axm_actions: [], 70 | axm_monitor: {}, 71 | axm_options: {}, 72 | axm_dynamic: {}, 73 | vizion_running: false, 74 | created_at: 1434096545628, 75 | pm_id: 0, 76 | restart_time: 19, 77 | unstable_restarts: 0, 78 | started_inside: false, 79 | command: 80 | { locked: false, 81 | metadata: {}, 82 | started_at: null, 83 | finished_at: null, 84 | error: null }, 85 | versioning: null, 86 | exit_code: 1 }, 87 | at: 1434096607294 } 88 | ``` 89 | 90 | You can use all those variables in the template. We're adding the `hostname` and we format `at` in a `date` variable by using `date = new Date(at).toString()`. 91 | Templating is done through lodash and the email should be markdown-formatted. 92 | 93 | ## Testing 94 | 95 | Mail testing is hard to automate. There is a sample throwing process in the `test` directory. To test manually just launch `pm2 start test/throw.js` with `node index.js`. 96 | If you have an idea to unit test this feel free to open an issue. 97 | -------------------------------------------------------------------------------- /config.example.yml: -------------------------------------------------------------------------------- 1 | mail: 2 | from: "me@example.com" 3 | to: "you@example.com" 4 | # see https://github.com/andris9/nodemailer-smtp-transport#usage 5 | smtp: 6 | host: "smtp.gmail.com" 7 | port: 25 8 | # Events list: 9 | # - restart 10 | # - delete 11 | # - stop 12 | # - restart overlimit 13 | # - exit 14 | # - start 15 | # - online 16 | events: 17 | - exit 18 | template: './template.md' 19 | # this is the process subject if there is only one event to be mailed 20 | subject: '<%= process.name %> errored (<%= process.NODE_ENV %>)' 21 | # if multiple events are going to be mailed, use a global subject: 22 | multiple_subject: 'Error on <%= hostname %>' 23 | #wait for 5 seconds after the last event before sending an email - avoid spam when a lot of events happened 24 | polling: 5000 25 | #if events are sent continuously, an email will be sent after 5 minutes anyway 26 | max_polling_time: 300000 27 | #attach your process logs to the email 28 | attach_logs: true 29 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var pm2 = require('pm2') 2 | var hostname = require('os').hostname() 3 | var nodemailer = require('nodemailer') 4 | var markdown = require('nodemailer-markdown').markdown 5 | var config = require('yamljs').load(__dirname + '/config.yml') 6 | var _ = require('lodash.template') 7 | var template = require('fs').readFileSync(config.template) 8 | var async = require('async') 9 | var util = require('util') 10 | var p = require('path') 11 | 12 | var transporter = nodemailer.createTransport(require('nodemailer-smtp-transport')(config.smtp)) 13 | 14 | transporter.use('compile', markdown({useEmbeddedImages: true})) 15 | 16 | var queue = [] 17 | var timeout = null 18 | var lastEventTime = null 19 | 20 | /** 21 | * Compile template 22 | * @param string template 23 | * @param object data 24 | */ 25 | function compile(template, data) { 26 | var s = _(template) 27 | return s(data) 28 | } 29 | 30 | /** 31 | * Send an email through smtp transport 32 | * @param object opts 33 | */ 34 | function sendMail(opts) { 35 | 36 | if(!opts.subject || !opts.text) { 37 | throw new ReferenceError("No text or subject to be mailed") 38 | } 39 | 40 | var opts = { 41 | from: opts.from || config.mail.from, 42 | to: opts.to ? opts.to : config.mail.to, 43 | subject: opts.subject, 44 | markdown: opts.text, 45 | attachments: opts.attachments || [] 46 | } 47 | 48 | transporter.sendMail(opts, function(err, info) { 49 | if(err) { 50 | console.error(err) 51 | } 52 | 53 | console.log('Mail sent', info) 54 | }) 55 | } 56 | 57 | /** 58 | * Process the events queue 59 | * if there is only one event, send an email with it 60 | * if there are more than one, join texts and attachments 61 | */ 62 | function processQueue() { 63 | var l = queue.length 64 | 65 | if(l == 0) { 66 | return; 67 | } 68 | 69 | //just one? 70 | if(l === 1) { 71 | return sendMail(queue[0]) 72 | } 73 | 74 | //Concat texts, get the multiple subject 75 | var text = '' 76 | var attachments = [] 77 | 78 | var subject = compile(config.multiple_subject, queue[0]) 79 | 80 | for(var i in queue) { 81 | text += queue[i].text 82 | 83 | if(config.attach_logs) { 84 | 85 | //don't attach twice the same file 86 | for(var j in queue[i].attachments) { 87 | var has = false 88 | 89 | for(var a in attachments) { 90 | if(attachments[a].path == queue[i].attachments[j].path) { 91 | has = true 92 | break; 93 | } 94 | } 95 | 96 | if(has === false) { 97 | attachments.push(queue[i].attachments[j]) 98 | } 99 | } 100 | } 101 | } 102 | sendMail({ 103 | subject: subject, 104 | text: text, 105 | attachments: attachments 106 | }) 107 | 108 | //reset queue 109 | queue.length = 0 110 | 111 | // Reset send mail delay 112 | lastEventTime = null 113 | } 114 | 115 | pm2.launchBus(function(err, bus) { 116 | 117 | if(err) { 118 | throw err 119 | } 120 | 121 | bus.on('process:event', function(e) { 122 | 123 | if(e.manually === true) { 124 | return; 125 | } 126 | 127 | //it's an event we should watch 128 | if(~config.events.indexOf(e.event)) { 129 | 130 | e.date = new Date(e.at).toString() 131 | 132 | e = util._extend(e, { 133 | hostname: hostname, 134 | text: compile(template, e), 135 | subject: compile(config.subject, e) 136 | }) 137 | 138 | //should we add logs? 139 | if(config.attach_logs) { 140 | e.attachments = [] 141 | ;['pm_out_log_path', 'pm_err_log_path'] 142 | .forEach(function(log) { 143 | e.attachments.push({ 144 | filename: p.basename(e.process[log]), 145 | path: e.process[log] 146 | }) 147 | }) 148 | } 149 | 150 | queue.push(e) 151 | 152 | if(timeout) { 153 | clearTimeout(timeout) 154 | 155 | if (lastEventTime && Date.now() - lastEventTime >= config.max_polling_time) { 156 | processQueue() 157 | } 158 | } 159 | 160 | timeout = setTimeout(processQueue, config.polling) 161 | if (!lastEventTime) { 162 | lastEventTime = Date.now() 163 | } 164 | } 165 | }) 166 | 167 | bus.on('pm2:kill', function() { 168 | console.error('PM2 is beeing killed') 169 | }) 170 | }) 171 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pm2-notify", 3 | "version": "1.0.2", 4 | "description": "SMTP PM2 notifier", 5 | "main": "index.js", 6 | "dependencies": { 7 | "async": "^1.2.1", 8 | "lodash.template": "^3.6.1", 9 | "nodemailer": "^1.3.4", 10 | "nodemailer-markdown": "^1.0.0", 11 | "nodemailer-smtp-transport": "^1.0.3", 12 | "pm2": "^0.12.16", 13 | "yamljs": "^0.2.3" 14 | }, 15 | "devDependencies": {}, 16 | "scripts": { 17 | "test": "echo \"Error: no test specified\" && exit 1" 18 | }, 19 | "author": "soyuka", 20 | "license": "GNU-AGPL3.0" 21 | } 22 | -------------------------------------------------------------------------------- /template.md: -------------------------------------------------------------------------------- 1 | # <%= process.name %> - <%= process.NODE_ENV %> (<%= event %>) 2 | 3 | Process <%= process.name %> has a "<%= process.status %>" status. It restarted <%= process.restart_time %> time(s). 4 | 5 | <%= date %> 6 | -------------------------------------------------------------------------------- /test/throw.js: -------------------------------------------------------------------------------- 1 | setTimeout(function() { 2 | throw new Exception("FAILURE") 3 | }, 3000) 4 | --------------------------------------------------------------------------------