Skip to content

Instantly share code, notes, and snippets.

@zaftzaft
Created April 11, 2018 05:11
Show Gist options
  • Save zaftzaft/ebfea04ac13788a8e8fb98eaf174800f to your computer and use it in GitHub Desktop.
Save zaftzaft/ebfea04ac13788a8e8fb98eaf174800f to your computer and use it in GitHub Desktop.
'use strict';
const readline = require("readline");
const fs = require("fs");
const {spawn} = require("child_process");
//<flag 2byte><timestamp 4><addr 4><mask 4><asn 4>
const packEvent = ev => {
const buf = Buffer.alloc(18, 0);
const timestamp = +new Date/1000|0;
if(ev.withdrawal) {
buf.writeUInt16BE(0x1, 0); // 0000 0000 0000 0001
}
buf.writeUInt32BE(timestamp, 2);
const cidr = ev.nlri.prefix.split("/");
cidr[0].split(".").forEach((a, i) => {
buf.writeUInt8(parseInt(a, 10), 6 + i);
});
// powwwwwwwwwwwwwwwer!!!!!!!!!
const subnet = (
new Array(parseInt(cidr[1], 10) + 1).join("1")
+ new Array(32).join("0")
).slice(0, 32);
for(let i = 0;i < 4;i++) {
const mask = parseInt(subnet.slice(8*i, 8*(i+1)), 2);
buf.writeUInt8(mask, 10 + i);
}
ev.attrs.forEach(attr => {
if(attr.type === 2 && attr.as_paths) {
const asn = parseInt(attr.as_paths[0].asns.slice(-1)[0], 10);
buf.writeUInt32BE(asn, 14);
}
});
return buf;
};
let counter = 0;
const ws = fs.createWriteStream(`${+new Date}.data`);
const rl = readline.createInterface({
input: spawn("gobgp", ["monitor", "global", "rib", "-j"]).stdout
});
rl.on("line", line => {
const results = JSON.parse(line);
results.forEach(r => {
counter++;
//console.log()
//console.log(r.nlri.prefix);
//console.log(r.attrs);
//console.log(r.withdrawal);
ws.write(packEvent(r));
});
process.stdout.write(`\r${counter}`);
});
rl.on("close", () => {
ws.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment