|
| 1 | +var dgram = require('dgram') |
| 2 | + |
| 3 | + |
| 4 | +function DeployRiskBackend(startupTime, config, emitter){ |
| 5 | + var self = this |
| 6 | + |
| 7 | + this.client = dgram.createSocket('udp4') |
| 8 | + |
| 9 | + this.score = 0 |
| 10 | + |
| 11 | + this.config = config.deployrisk || {} |
| 12 | + |
| 13 | + this.config.port = this.config.port || 8125 |
| 14 | + this.config.host = this.config.host || '127.0.0.1' |
| 15 | + |
| 16 | + this.inputs = this.config.inputs || [] |
| 17 | + |
| 18 | + this.inputs.forEach(function (input) { |
| 19 | + var mod = input.mod |
| 20 | + var max = input.max |
| 21 | + |
| 22 | + mod = |
| 23 | + null == mod ? function (x) {return x} |
| 24 | + : 'invert' === mod ? function (x, input) {return input.min + input.max - x} |
| 25 | + : mod |
| 26 | + |
| 27 | + input.mod = mod |
| 28 | + |
| 29 | + input.min = input.min || 0 |
| 30 | + }) |
| 31 | + |
| 32 | + emitter.on('flush', function(timestamp, metrics) { |
| 33 | + self.flush(timestamp, metrics) |
| 34 | + }) |
| 35 | + |
| 36 | + emitter.on('status', function(callback) { |
| 37 | + self.status(callback) |
| 38 | + }) |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +DeployRiskBackend.prototype.flush = function(timestamp, metrics) { |
| 43 | + |
| 44 | + var table = [] |
| 45 | + |
| 46 | + this.inputs.forEach(function (input) { |
| 47 | + var name = 'deployrisk.'+input.name |
| 48 | + var min = input.min |
| 49 | + var max = input.max |
| 50 | + var mod = input.mod |
| 51 | + var weight = input.weight |
| 52 | + |
| 53 | + var v = metrics.gauges[name] |
| 54 | + |
| 55 | + if (null != v) { |
| 56 | + v = mod(v, input) |
| 57 | + table.push( weight * Math.max(0, (Math.min(1, (v-min) / (max-min)))) ) |
| 58 | + } |
| 59 | + }) |
| 60 | + |
| 61 | + this.score = Math.round( 100 * table.reduce(function(ac, v) {return ac+v}, 0) ) |
| 62 | + |
| 63 | + var data = new Buffer('deployrisk.score:'+this.score+'|g') |
| 64 | + this.client.send(data, 0, data.length, this.config.port, this.config.host, |
| 65 | + function(err) { if (err) console.log(err) }) |
| 66 | +} |
| 67 | + |
| 68 | + |
| 69 | +DeployRiskBackend.prototype.status = function(write) { |
| 70 | + write(null, 'deployrisk', 'score', this.score) |
| 71 | +} |
| 72 | + |
| 73 | +exports.init = function(startupTime, config, events) { |
| 74 | + var instance = new DeployRiskBackend(startupTime, config, events) |
| 75 | + return true |
| 76 | +} |
0 commit comments