Created
December 7, 2012 15:17
-
-
Save astro/4233880 to your computer and use it in GitHub Desktop.
jsonchangewatch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var child_process = require('child_process'); | |
function poll(url, cb) { | |
http.get(url, function(res) { | |
var body = ""; | |
res.setEncoding('utf8'); | |
res.on('data', function(data) { | |
body += data; | |
}); | |
res.on('end', function() { | |
var json; | |
try { | |
json = JSON.parse(body); | |
} catch (e) { | |
console.error(e); | |
return cb(error); | |
} | |
return cb(null, json); | |
}); | |
res.on('error', cb); | |
}); | |
} | |
var mailTo = process.argv[2]; | |
var url = process.argv[3]; | |
var interval = parseInt(process.argv[4], 10); | |
var keys = process.argv.slice(5).map(function(s) { | |
var m; | |
if ((m = s.match(/^(.+):(\d+)$/))) { | |
return { path: m[1].split('.'), | |
ttl: parseInt(m[2], 10) * 1000, | |
updated: new Date().getTime() | |
}; | |
} else | |
return { path: s.split('.'), | |
ttl: 3600000, | |
updated: new Date().getTime() | |
}; | |
}); | |
function sendMail(subject, mailTo, body) { | |
var mail = child_process.spawn("mail", ["-s", subject, mailTo]); | |
mail.stdin.write(body); | |
mail.stdin.end(); | |
mail.on('exit', function(code) { | |
if (code !== 0) | |
console.error("mail exited with " + code); | |
}); | |
} | |
if (keys.length < 1) { | |
console.log("Usage: " + process.argv.slice(0, 2).join(" ") + " <mail-to> <json-url> <interval> <key1:maxage1> [key2:maxage2] [.. keyN:maxageN]"); | |
process.exit(1); | |
} | |
setInterval(function() { | |
poll(url, function(error, json) { | |
if (error) { | |
sendMail("Watch error for " + url, mailTo, error.message || error.toString()); | |
return; | |
} | |
// console.log(json); | |
var now = new Date().getTime(); | |
keys.forEach(function(key) { | |
var a = json, p = key.path; | |
while(a && p.length > 0) { | |
a = a[p[0]]; | |
p = p.slice(1); | |
} | |
if (key.state !== a) { | |
key.state = a; | |
key.updated = now; | |
} | |
}); | |
var report = []; | |
keys.forEach(function(key) { | |
var age = now - key.updated; | |
if (age >= key.ttl) { | |
report.push(key.path.join('.') + | |
" has been " + | |
(key.state ? ("at " + key.state) : "unknown") + | |
" for " + | |
Math.floor(age / 1000) + | |
" seconds."); | |
} | |
}); | |
if (report.length > 0) { | |
console.log(report); | |
sendMail("Watch alert for " + url, mailTo, report.join("\n")); | |
} | |
}); | |
}, interval * 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment