Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
samlambert committed Jan 28, 2014
0 parents commit 0d6a212
Show file tree
Hide file tree
Showing 10 changed files with 377 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
node_modules
40 changes: 40 additions & 0 deletions Gruntfile.js
@@ -0,0 +1,40 @@
'use strict';

module.exports = function(grunt) {

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

grunt.initConfig({
mochaTest: {
test: {
options: {
reporter: 'spec',
require: 'coffee-script'
},
src: ['test/**/*.coffee']
}
},
release: {
options: {
tagName: 'v<%= version %>',
commitMessage: 'Prepared to release <%= version %>.'
}
},
watch: {
files: ['Gruntfile.js', 'test/**/*.coffee'],
tasks: ['test']
}
});

grunt.event.on('watch', function(action, filepath, target) {
grunt.log.writeln(target + ': ' + filepath + ' has ' + action);
});

// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

grunt.registerTask('test', ['mochaTest']);
grunt.registerTask('test:watch', ['watch']);
grunt.registerTask('default', ['test']);
};
20 changes: 20 additions & 0 deletions LICENSE
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2014 Sam Lambert

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.
49 changes: 49 additions & 0 deletions README.md
@@ -0,0 +1,49 @@
# Hubot: hubot-mysql-chatops

A small collection of MySQL ChatOps scripts.

See each script in `src/` for full documentation.

## Installation

Add **hubot-mysql-chatops** to your `package.json` file:

```json
"dependencies": {
"hubot-mysql-chatops": ">= 1.0.0",
}
```

Add **hubot-mysql-chatops** to your `external-scripts.json`:

```json
["hubot-mysql-chatops"]
```

Run `npm install`

## Warnings

Some of these scripts execute queries. It is very strongly recommended that a read only user is used and queries are executed on a MySQL slave.

I can't be responsible for you deleting all your data ;)

An example GRANT would be: `GRANT SELECT ON some_db.* TO 'hubot_mysql'@'hubot_host' IDENTIFIED BY 'some_pass';`

## Sample Interaction

```
user1>> mysql explain SELECT * FROM users
hubot>> user1:
┌───────────────┬─────────┬──────────┬────────┬────────┬──────────┬────────┬──────────┬────┐
│Select Type │Table │Type │Possibl…│Key │Key Len │Ref │Rows │Ext…│
├───────────────┼─────────┼──────────┼────────┼────────┼──────────┼────────┼──────────┼────┤
│SIMPLE │users │ALL │null │null │null │null │0 │ │
└───────────────┴─────────┴──────────┴────────┴────────┴──────────┴────────┴──────────┴────┘
```

## Thanks

Thanks to everyone who has contributed to Hubot and this packages dependencies.

A special thank you to @technicalpickles for being awesome.
12 changes: 12 additions & 0 deletions index.coffee
@@ -0,0 +1,12 @@
fs = require 'fs'
path = require 'path'

module.exports = (robot, scripts) ->
scriptsPath = path.resolve(__dirname, 'src')
fs.exists scriptsPath, (exists) ->
if exists
for script in fs.readdirSync(scriptsPath)
if scripts? and '*' not in scripts
robot.loadFile(scriptsPath, script) if script in scripts
else
robot.loadFile(scriptsPath, script)
42 changes: 42 additions & 0 deletions package.json
@@ -0,0 +1,42 @@
{
"name": "hubot-mysql-chatops",
"description": "Hubot ChatOps scripts for MySQL",
"version": "1.0.0",
"author": "samlambert <sam.lambert@github.com>",
"license": "MIT",

"keywords": ["hubot","MySQL","ChatOps","queries","profile","explain"],

"repository": {
"type": "git",
"url": "git://github.com/samlambert/hubot-mysql-chatops.git"
},

"bugs": {
"url": "https://github.com/samlambert/hubot-mysql-chatops/issues"
},

"dependencies": {
"coffee-script": "~1.6.3",
"cli-table": "~0.2.0",
"mysql": "~0.9.5",
"validator": "3.1.0"
},

"devDependencies": {
"mocha": "*",
"chai": "*",
"sinon-chai": "*",
"sinon": "*",
"grunt-mocha-test": "~0.7.0",
"grunt-release": "~0.6.0",
"matchdep": "~0.1.2",
"grunt-contrib-watch": "~0.5.3"
},

"main": "index.coffee",

"scripts": {
"test": "grunt test"
}
}
18 changes: 18 additions & 0 deletions script/bootstrap
@@ -0,0 +1,18 @@
#!/bin/bash

# Make sure everything is development forever
export NODE_ENV=development

# Load environment specific environment variables
if [ -f .env ]; then
source .env
fi

if [ -f .env.${NODE_ENV} ]; then
source .env.${NODE_ENV}
fi

npm install

# Make sure coffee and mocha are on the path
export PATH="node_modules/.bin:$PATH"
6 changes: 6 additions & 0 deletions script/test
@@ -0,0 +1,6 @@
#!/bin/bash

# bootstrap environment
source script/bootstrap

mocha --compilers coffee:coffee-script
93 changes: 93 additions & 0 deletions src/mysql-explain.coffee
@@ -0,0 +1,93 @@
# Description:
# Explain a MySQL Query
#
# Notes:
# This script requires a MySQL user with SELECT priviliges.
# You can create a user like so: GRANT SELECT ON some_db.* TO 'hubot_mysql'@'hubot_host' IDENTIFIED BY 'some_pass';
# !! It is very strongly recommended that you use a read only user on a MySQL slave !!
#
# Dependencies:
# "cli-table" : "https://github.com/LearnBoost/cli-table"
# "mysql" : "https://github.com/felixge/node-mysql"
# "validator" : "https://github.com/chriso/validator.js"
#
# Configuration:
# HUBOT_MYSQL_CHATOPS_HOST
# HUBOT_MYSQL_CHATOPS_DATABASE
# HUBOT_MYSQL_CHATOPS_USER
# HUBOT_MYSQL_CHATOPS_PASS
#
# Commands:
# hubot mysql explain <sql> - Run MySQL EXPLAIN on <sql>

mysql = require 'mysql'
table = require 'cli-table'
validator = require 'validator'

module.exports = (robot) ->
robot.respond /mysql explain (.*)/i, (msg) ->
query = validator.blacklist(msg.match[1], [';'])

unless process.env.HUBOT_MYSQL_CHATOPS_HOST?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_HOST"
return

unless process.env.HUBOT_MYSQL_CHATOPS_DATABASE?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_DATABASE"
return

unless process.env.HUBOT_MYSQL_CHATOPS_USER?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_USER"
return

unless process.env.HUBOT_MYSQL_CHATOPS_PASS?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_PASS"
return

@client = mysql.createClient
host: "#{process.env.HUBOT_MYSQL_CHATOPS_HOST}"
database: "#{process.env.HUBOT_MYSQL_CHATOPS_DATABASE}"
user: "#{process.env.HUBOT_MYSQL_CHATOPS_USER}"
password: "#{process.env.HUBOT_MYSQL_CHATOPS_PASS}"
@client.on 'error', (err) ->
robot.emit 'error', err, msg

@client.query "EXPLAIN #{query}", (err, results) =>
if err
msg.reply err
return

table_max = 0
poss_max = 0
key_max = 0
ref_max = 0
extra_max = 0

rows = []

for row in results
row.Extra ?= ''
explain = ["#{row.select_type}", "#{row.table}", "#{row.type}", "#{row.possible_keys}", "#{row.key}", "#{row.key_len}", "#{row.ref}", "#{row.rows}", "#{row.Extra}"]
padding = 4
if explain[1].length + padding > table_max
table_max = explain[1].length + padding
if explain[3].length + padding > poss_max
poss_max = explain[3].length + padding
if explain[4].length + padding > key_max
key_max = explain[4].length + padding
if explain[6].length + padding > ref_max
ref_max = explain[6].length + padding
if explain[8].length + padding > extra_max
extra_max = explain[8].length + padding
rows.push explain

@grid = new table
head: ['Select Type', 'Table', 'Type', 'Possible Keys', 'Key', 'Key Len', 'Ref', 'Rows', 'Extra']
style: { head: false }
colWidths: [15, table_max, 10, poss_max, key_max, 10, ref_max, 10, extra_max]

for row in rows
@grid.push row

msg.reply "\n#{@grid.toString()}"
@client.destroy()
96 changes: 96 additions & 0 deletions src/mysql-profile.coffee
@@ -0,0 +1,96 @@
# Description:
# Profile a MySQL Query
#
# Notes:
# This script requires a MySQL user with SELECT priviliges.
# You can create a user like so: GRANT SELECT ON some_db.* TO 'hubot_mysql'@'hubot_host' IDENTIFIED BY 'some_pass';
# !! Warning. In order to collect a profile the query is executed. It is very strongly recommended that you use a read only user on a MySQL slave !!
#
# Dependencies:
# "cli-table" : "https://github.com/LearnBoost/cli-table"
# "mysql" : "https://github.com/felixge/node-mysql"
# "validator" : "https://github.com/chriso/validator.js"
#
# Configuration:
# HUBOT_MYSQL_CHATOPS_HOST
# HUBOT_MYSQL_CHATOPS_DATABASE
# HUBOT_MYSQL_CHATOPS_USER
# HUBOT_MYSQL_CHATOPS_PASS
#
# Commands:
# hubot mysql profile <sql> - Run MySQL profile on <sql>

mysql = require 'mysql'
table = require 'cli-table'
validator = require 'validator'

module.exports = (robot) ->

robot.respond /mysql profile (.*)/i, (msg) ->
msg.reply "This will run and profile a query against MySQL. To run this fo realz use mysql profile!. Be careful ;)"
return

robot.respond /mysql profile! (.*)/i, (msg) ->
query = validator.blacklist(msg.match[1], [';'])

unless process.env.HUBOT_MYSQL_CHATOPS_HOST?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_HOST"
return

unless process.env.HUBOT_MYSQL_CHATOPS_DATABASE?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_DATABASE"
return

unless process.env.HUBOT_MYSQL_CHATOPS_USER?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_USER"
return

unless process.env.HUBOT_MYSQL_CHATOPS_PASS?
msg.reply "Would love to, but kind of missing HUBOT_MYSQL_CHATOPS_PASS"
return

@client = mysql.createClient
host: "#{process.env.HUBOT_MYSQL_CHATOPS_HOST}"
database: "#{process.env.HUBOT_MYSQL_CHATOPS_DATABASE}"
user: "#{process.env.HUBOT_MYSQL_CHATOPS_USER}"
password: "#{process.env.HUBOT_MYSQL_CHATOPS_PASS}"
@client.on 'error', (err) ->
robot.emit 'error', err, msg

@client.query "SET PROFILING = 1", (err, results) =>
if err
msg.reply err
return
@client.query "#{query}", (err, results) =>
if err
msg.reply err
return
@client.query "SHOW PROFILE FOR QUERY 1", (err, results) =>
if err
msg.reply err
return

status_max = 0
duration_max = 0

rows = []

for row in results
profile = ["#{row.Status}", "#{row.Duration}"]
padding = 8
if profile[0].length + padding > status_max
status_max = profile[0].length + padding
if profile[1].length + padding > duration_max
duration_max = profile[1].length + padding
rows.push profile

@grid = new table
head: ['Status', 'Duration (secs)']
style: { head: false }
colWidths: [status_max, duration_max]

for row in rows
@grid.push row

msg.reply "\n#{@grid.toString()}"
@client.destroy()

0 comments on commit 0d6a212

Please sign in to comment.