Skip to content

Instantly share code, notes, and snippets.

@fujiwara
Created January 28, 2011 08:57
Show Gist options
  • Save fujiwara/800014 to your computer and use it in GitHub Desktop.
Save fujiwara/800014 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use Plack::Builder;
use AnyEvent;
use Cache::LRU;
use Sys::Virt;
use JSON;
use Data::Section::Simple qw/ get_data_section /;
sub watch {
my $cb = shift;
my $cache = Cache::LRU->new( size => 60 );
my $timer = AnyEvent->timer(
interval => 1,
cb => sub {
$cache->set( time() => $cb->() );
},
);
sub {
$timer; # hold in closure
my $now = time;
return [
map {
[ $_ => $cache->get($now + $_) ]
} (-59 .. 0)
];
};
}
my $feeder = do {
my $virt = Sys::Virt->new( uri => "qemu:///system" );
my $prev_value;
sub {
my $dom = $virt->get_domain_by_name("foo");
my ($vcpu) = $dom->get_vcpu_info();
my $usage;
if ($prev_value) {
$usage = ($vcpu->{cpuTime} - $prev_value) / (1000 ** 3) * 100;
}
$prev_value = $vcpu->{cpuTime};
return $usage;
};
};
my $retriever = watch $feeder;
builder {
enable "Plack::Middleware::Static",
path => qr{^/static/}, root => ".";
mount "/" => sub {
[ 200,
[ "Content-Type" => "text/html" ],
[ get_data_section("html") ],
];
};
mount "/usage" => sub {
[ 200,
[ "Content-Type" => "application/json" ],
[ encode_json $retriever->() ],
];
};
};
__DATA__
@@ html
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="static/jquery.jqplot.css" />
<script type="text/javascript" src="static/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="static/jquery.jqplot.min.js"></script>
<script type="text/javascript">
function plot() {
$.getJSON("/usage", function(data) {
$("#chartdiv").html("");
$.jqplot('chartdiv',
[ data ],
{ title:'CPU Uasge(%)',
axes:{ yaxis:{ min:0, max:100 }, xaxis:{ min:-60, max:0 } },
}
);
});
}
$(document).ready(function(){
setInterval(plot, 1000)
});
</script>
</head>
<body>
<div id="chartdiv" style="height:400px;width:600px;"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment