#!/usr/bin/perl

# NOTE: In development; not actually used yet.

#Collates the results of listvms from multiple VM servers.  Part of the xvm
#suite.

use Net::Remctl ();
use JSON;

our @servers = qw/black-mesa.mit.edu sx-blade-2.mit.edu/;

our %connections;

sub openConnections() {
    foreach (@servers) { openConnection($_); }
}

sub openConnection($) {
    my ($server) = @_;
    my $remctl = Net::Remctl->new;
    $remctl->open($server)
        or die "Cannot connect to $server: ", $remctl->error, "\n";
    $connections{$server} = $remctl;
}

sub doListVMs() {
    foreach my $remctl (values %connections) {
	$remctl->command("remote", "web", "listvms", "--json");
    }
    my %vmstate;
    foreach my $server (keys %connections) {
	my $remctl = $connections{$server};
	my $jsonData = '';
	do {
	    $output = $remctl->output;
	    if ($output->type eq 'output') {
		if ($output->stream == 1) {
		    $jsonData .= $output->data;
		} elsif ($output->stream == 2) {
		    print STDERR $output->data;
		}
	    } elsif ($output->type eq 'error') {
		warn $output->error, "\n";
	    } elsif ($output->type eq 'status') {
		if ($output->status != 0) {
		    warn "Exit status was ".$output->status;
		}
	    } elsif ($output->type eq 'done') {
		#next;
	    } else {
		die "Unknown output token from library: ", $output->type, "\n";
	    }
	} while ($output->type ne 'done');
	my $vmlist = jsonToObj($jsonData);
	foreach my $key (keys %$vmlist) {
	    $vmstate{$key} = $vmlist->{$key};
	    $vmstate{$key}{"host"} = $server;
	}
    }
    return %vmstate;
}

openConnections();

use Data::Dumper;
use Benchmark;
print Dumper({doListVMs()});
timethis(100, sub {doListVMs()});

# vim:et:sw=4:ts=4
