+my $last;
+
+while(1) {
+
+my $skip;
+
+my $begin_t = time();
+my $t = int( time() * 1000_000_000 );
+
+foreach my $instance ( glob '/var/run/ganeti/kvm-hypervisor/pid/*' ) {
+
+ open(my $fh, '<', $instance);
+ my $pid = <$fh>; chomp $pid;
+
+ $instance =~ s{^.*/}{};
+
+ if ( ! -d "/proc/$pid" ) {
+ $skip->{$instance}++;
+ XXX $skip;
+ next;
+ }
+
+ my $vcpu = $last->{$instance}->{vcpu};
+
+ if ( ! $vcpu ) {
+ foreach my $fd ( glob "/proc/$pid/fd/*" ) {
+ $vcpu++ if -l $fd && readlink($fd) =~ m/kvm-vcpu/;
+ }
+
+ $last->{$instance}->{vcpu} = $vcpu;
+ }
+
+ # https://www.kernel.org/doc/Documentation/filesystems/proc.txt
+ open($fh, '<', "/proc/$pid/stat");
+ my $line = <$fh>; chomp $line;
+ my $gtime = (split(/\s+/,$line))[42]; # guest time of the task in jiffies
+
+ if ( my $last_gtime = $last->{$instance}->{gtime} ) {
+ my $clock_ticks = POSIX::sysconf( &POSIX::_SC_CLK_TCK ); # clock ticks per second
+
+ my $cpu = ( ( $gtime - $last_gtime ) * 100 ) / ( $clock_ticks * $vcpu ) / $INTERVAL;
+ $stat->{$instance}->{cpu} = $cpu;
+ $stat->{$instance}->{ticks} = ($gtime - $last_gtime) / $INTERVAL;
+ }
+
+ $last->{$instance}->{gtime} = $gtime;
+}
+