Skip to content

Commit

Permalink
Pinzy yeah!
Browse files Browse the repository at this point in the history
  • Loading branch information
Flolagale committed Dec 27, 2014
0 parents commit b75f4f5
Show file tree
Hide file tree
Showing 13 changed files with 537 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
.tmp
*.swp
*.pyc
24 changes: 24 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"curly": false,
"eqeqeq": true,
"indent": 4,
"latedef": true,
"newcap": true,
"nonew": true,
"undef": true,
"unused": true,
"trailing": true,
"white": true,
"globalstrict": true,
"browser": true,
"node": true,
"jquery": true,
"devel": true,
"globals": {
"before": false,
"after": false,
"it": false,
"describe": false,
"beforeEach": false
}
}
68 changes: 68 additions & 0 deletions Gruntfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
'use strict';

var fs = require('fs');

module.exports = function (grunt) {

// Load .jshintrc file.
var hintOptions = JSON.parse(fs.readFileSync('.jshintrc', 'utf8'));

grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.loadNpmTasks('grunt-contrib-jshint');

grunt.loadNpmTasks('grunt-mocha-test');

// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),

jsfiles: [
'Gruntfile.js',
'package.json',
'index.js',
'lib/**/*.js',
'test/**/*.js',
'!node_modules/**/*.js'
],

jsbeautifier: {
files: ['<%= jsfiles %>'],
options: {
space_after_anon_function: true
}
},

jshint: {
options: hintOptions,
files: ['<%= jsfiles %>']
},

mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*Spec.js']
}
},

watch: {
files: ['<%= jsfiles %>'],
tasks: ['test']
}
});

grunt.registerTask('lint', [
'jsbeautifier',
'jshint'
]);

grunt.registerTask('test', [
'mochaTest'
]);

grunt.registerTask('precommit', [
'lint',
'test'
]);
};
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Flolagale

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#node-cli-boilerplate

__A boilerplate for building node command line modules that run forever.__

Is a boilerplate for building node command line interface modules. Module based on this repo can be installed via ```npm install -g mymodule``` and used from the command line or required locally in an application.

The entry point is run-cli.js, which will run the cli.js file with [forever](https://github.com/nodejitsu/forever), restarting it when it crashes.

The boilerplate comes bundled with ```grunt lint``` and ```grunt test``` commands to either lint all the files or run the tests.
To run the tests, you will need to install the grunt-cli globally ```npm install -g grunt-cli```.

To use this boilerplate, clone this repo locally, remove the .git folder, run git init and hack at will.

If you use it, feel free to improve it or report bugs here.
65 changes: 65 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/usr/bin/env node
'use strict';

var logger = require('./lib/logger');
var program = require('commander');

/* Here come the core module of your command line app. Change this to something
* that really suit your needs. */
var core = require('./lib/core');

var pkg = require('./package.json');

var parseList = function (val) {
return val.split(',');
};

program.version(pkg.version)
.option('-u, --urls <items>', 'The urls to monitor separated by commas without spaces. (http://mysite.com,https://my.othersite.com', parseList)
.option('-d, --slack-domain [Slack domain]', 'Your Slack domain as in http://domain.slack.com.')
.option('-t, --slack-token [Slack webhook token]', 'The Slack webhook token of your webhook integration.')
.option('-c, --slack-channel [Slack channel]', 'The Slack channel to post to. Default to #general.')
.option('-i, --interval <n>', 'The interval in minutes between each check of the urls. Default to 1 minute.', parseInt)
.option('-l, --log-file [file path]', "The log file path. Default to './.tmp/" + pkg.name + ".log'.")
.option('--verbose', 'Set the logging level to verbose.');

/* Hack the argv object so that commander thinks that this script is called
* 'pkg.name'. The help info will look nicer. */
process.argv[1] = pkg.name;
program.parse(process.argv);

logger.info(pkg.name + ' v' + pkg.version);

if (!program.urls || program.urls.length === 0) {
console.log('Provide at least 1 url to monitor.');
process.exit(0);
}

if (!program.slackDomain) {
console.log('Provide a Slack domain.');
process.exit(0);
}

if (!program.slackToken) {
console.log('Provide a Slack webhook token.');
process.exit(0);
}

if (!program.slackChannel) {
console.log('Provide a Slack channel.');
process.exit(0);
}

core.start({
urls: program.urls,
slackDomain: program.slackDomain,
slackToken: program.slackToken,
slackChannel: program.slackChannel || '#general',
interval: program.interval || 1,
logFile: program.logFile || './.tmp/' + pkg.name + '.log',
verbose: program.verbose,
}, function (err) {
if (err) process.exit(1);

if (core.options.logFile) logger.info('Log file: ' + core.options.logFile);
});
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use strict';
var core = require('./lib/core');
module.exports = core;
171 changes: 171 additions & 0 deletions lib/core.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
'use strict';

var _ = require('lodash');
var events = require('events');
var fs = require('fs');
var request = require('request');
var shell = require('shelljs');
var util = require('util');

var logger = require('./logger');

var Core = function () {
events.EventEmitter.call(this);

/* Set up the default options. */
this.options = {
tmp: '.tmp',
logFile: null,
verbose: false,
};
};
util.inherits(Core, events.EventEmitter);

Core.prototype.start = function (options, callback) {
debugger;
var _this = this;

options = options || {};
if (_.isFunction(options)) {
callback = options;
options = {};
}

this.options = _.defaults(options, this.options);

callback = callback || function () {};

/* Create tmp dir if necessary. */
if (!fs.existsSync(this.options.tmp)) {
shell.mkdir('-p', this.options.tmp);
}

/* Log to a file if necessary. */
if (this.options.logFile) {
logger.setLogFile(this.options.logFile);
}

/* Set log level if necessary. */
if (this.options.verbose) {
logger.setLevel('verbose');
logger.info('Log level set to verbose.');
}

var postToSlack = function (data) {
request({
url: _this.options.slackToken,
method: 'POST',
body: JSON.stringify(data)
}, function (err, response) {
if (err || response.statusCode !== 200) {
err = err || new Error('Unable to post to slack.\n' + response.body);
logger.error(err.stack);
}
});
};

var websites = this.options.urls.map(function (url) {
return {
url: url,
isDown: false,
wentDownAt: null,
downtimeCount: 0
};
});

var checkWebsites = function () {
debugger;
websites.forEach(function (website) {
debugger;
logger.info('Checking ' + website.url);
logger.info(website);

request({
url: website.url,
method: 'GET',
timeout: 5000,

This comment has been minimized.

Copy link
@moleculext

moleculext Dec 29, 2014

N'est ce pas un peu court comme temps d'expiration ? J'aurais mis au moins 10 secondes pour éviter les faux positifs si le site web est occupé !

Sinon c'est une super idée ce module ! Je n'ai pas lu tout le code source mais est-ce que tu testes aussi le vrai "ping" du serveur (via l'adresse ip par exemple) ?

@+

This comment has been minimized.

Copy link
@Flolagale

Flolagale Dec 29, 2014

Author Owner

@moleculext oui c'est trop court ! Excellente remarque, on a déjà eu pas mal de faux positifs ! Il faudrait déclarer le site down uniquement si il ne répond pas 2 checks consécutifs. Tu connais Slack ? Ça poste les notifications dedans. Hey plus généralement ça roule toi ?

headers: {
'User-Agent': 'Pingzy'
}
}, function (err, response) {
debugger;
if (err) {
logger.error('Error while checking ' + website.url +
'\n' + err.stack);
}

var fifteenMinutes = 1000 * 60 * 15;
var prettyUrl = website.url.substr(website.url.indexOf('/') + 2);
if (err || response.statusCode !== 200) {
if (!website.isDown) {
logger.warn('Website went down: ' + website.url);

website.isDown = true;
website.wentDownAt = new Date();
website.downtimeCount++;

postToSlack({
fallback: 'Website <' + website.url + '|' + prettyUrl + '> just went down at ' + website.wentDownAt,
color: 'danger',
fields: [{
value: 'Website <' + website.url + '|' + prettyUrl + '> just went down at ' + website.wentDownAt
}],
channel: _this.options.slackChannel,
username: 'Pingzy',
icon_emoji: ':thumbsdown:'
});
} else if ((Date.now() - website.wentDownAt.getTime()) > fifteenMinutes) {
logger.warn('Website is still down: ' + website.url);

postToSlack({
fallback: 'Website <' + website.url + '|' + prettyUrl + '> is still down.',
color: 'danger',
fields: [{
value: 'Website <' + website.url + '|' + prettyUrl + '> is still down.'
}],
channel: _this.options.slackChannel,
username: 'Pingzy',
icon_emoji: ':thumbsdown:'
});
}
} else if (website.isDown) {
logger.warn('Website is back up: ' + website.url);

website.isDown = false;
postToSlack({
fallback: 'Website <' + website.url + '|' + prettyUrl + '> went back online. Good job!',
color: 'good',
fields: [{
value: 'Website <' + website.url + '|' + prettyUrl + '> went back online. Good job!',
}],
channel: _this.options.slackChannel,
username: 'Pingzy',
icon_emoji: ':thumbsup:'
});
}
});
});
};

// setInterval(checkWebsites, 1000 * 60 * this.options.interval);
setInterval(checkWebsites, 1000 * 5);

var stringUrls = '';
this.options.urls.forEach(function (url, index) {
stringUrls += '<' + url + '|' + url + '>';
if (index < _this.options.urls.length - 1) {
stringUrls += ', ';
}
});

postToSlack({
text: 'Starting monitoring urls: ' + stringUrls,
channel: _this.options.slackChannel,
username: 'Pingzy',
icon_emoji: ':thumbsup:'
});

checkWebsites();
};

module.exports = new Core();
Loading

0 comments on commit b75f4f5

Please sign in to comment.