extract_nodeinfo.in 32.1 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2015-2016 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#

#
# Extract node data from the DB for the given date range.
#
# For each node we create a series of records reflecting its allocation
# history over the given time range.
#
31 32
# Each node history record looks like:
#   (nhist_ix,node_ix,start,end,expt_ix,ehist_ix)
33 34
# Each node record look like:
#   (node_ix,name,IP,MAC)
35 36
# Each experiment history record looks like:
#   (ehist_ix,expt_ix,start,end)
37
# Each experiment record looks like:
38
#   (expt_ix,name,proj_ix)
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
# Each user record looks like:
#   (user_ix,name,affil,city,state,country,zip)
# Each project record looks like:
#   (proj_ix,name)
#
# Since each user can be a member of more than one project, we also have
# a user-to-projects table with records:
#   (user_ix,proj_ix)
#
use English;
use Getopt::Std;
use Date::Parse;

sub usage()
{
    print STDERR "Usage: extract_info [-ahdAN] [-n node] -s starttime -e endtime\n";
    print STDERR "   -h         This message\n";
    print STDERR "   -d         Print additional debug info\n";
    print STDERR "   -a		Get info for all nodes\n";
    print STDERR "   -n node    Get info for a specific node\n";
59
    print STDERR "   -t type    Get info for a specific node type\n";
60
    print STDERR "   -A         Anonymize info\n";
61
    print STDERR "   -G         Attempt to assign Lat/Lon info to users\n";
62
    print STDERR "   -N         Print in normalized CSV format\n";
63
    print STDERR "   -R         Report number of experiments, nodes, and node hours\n";
64
    print STDERR "   -S         Print in summary form\n";
65
    print STDERR "   -U         Filter out users not valid/active at the time\n";
66 67
}

68
my $optlist = "adhAGNRSUs:e:n:t:";
69 70 71
my $debug = 0;
my $anonymize = 0;
my $normalize = 0;
72
my $report = 0;
73 74 75 76
my $summary = 0;
my $starttime;
my $endtime;
my $allnodes = 0;
77
my $dogeo = 0;
78
my $noinactive = 0;
79
my $node;
80
my $nodetype;
81

82
sub nodehistory($$;$$);
83 84 85 86
sub nodes($);
sub experiments($);
sub projects($);
sub users($);
87
sub doreport();
88 89 90 91 92 93 94 95 96 97 98 99

#
# Configure variables
#
my $TB		 = "@prefix@";

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use Node;
100
use NodeType;
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
use Interface;
use Group;
use User;

#
# Turn off line buffering on output
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/sbin:/usr/bin:";

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{h})) {
    usage();
}
if (defined($options{d})) {
    $debug++;
}
if (defined($options{a})) {
    $allnodes++;
131 132
    $nodetype = undef;
    $node = undef;
133 134 135 136
}
if (defined($options{A})) {
    $anonymize++;
}
137 138 139
if (defined($options{G})) {
    $dogeo++;
}
140 141 142 143
if (defined($options{N})) {
    $normalize = 1;
    $summary = 0;
}
144 145 146 147
if (defined($options{R})) {
    $report = 1;
    $summary = 0;
}
148 149 150 151
if (defined($options{S})) {
    $summary = 1;
    $normalize = 0;
}
152 153 154
if (defined($options{U})) {
    $noinactive = 1;
}
155 156 157 158 159 160 161 162 163 164
if (defined($options{n})) {
    if ($options{n} =~ /^([-\w]+)$/) {
	$node = $1;
	if (!Node->Lookup($1)) {
	    die("Not a valid node.");
	}
    } else {
       die("Invalid node name.");
    }
    $allnodes = 0;
165 166 167 168 169 170 171 172 173 174 175 176 177
    $nodetype = undef;
}
if (defined($options{t})) {
    if ($options{t} =~ /^([-\w]+)$/) {
	$nodetype = $1;
	if (!NodeType->Lookup($1)) {
	    die("Not a valid node type.");
	}
    } else {
       die("Invalid node type name.");
    }
    $allnodes = 0;
    $node = undef;
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
}
if (defined($options{s})) {
   $starttime = str2time($options{s});
   if (!defined($starttime)) {
       die("Could not parse start date.");
   }
}
if (defined($options{e})) {
   $endtime = str2time($options{e});
   if (!defined($endtime)) {
       die("Could not parse end date.");
   }
}

if (!$starttime || !$endtime) {
    die("Must specify a start and end time.");
}

196 197
if (!$allnodes && !$nodetype && !$node) {
    die("Must specify a node name (-n), node type (-t), or -a.");
198 199 200 201 202
}

#
# Phase 1: build up the node history records
#
203
my $history = nodehistory($starttime, $endtime, $node, $nodetype);
204 205 206 207 208 209 210 211 212 213
if (!$history) {
    die("Could not get node history records.");
}

#
# Phase 2: use history records to build up node list
# 
my $nodes = nodes($history);

#
214 215
# Phase 3: use history records to build up experiment and experiment
# history lists
216
# 
217
my ($expts, $expthistory) = experiments($history);
218 219 220 221 222 223 224 225 226 227 228

#
# Phase 4: use experiment records to build up project list
# 
my $projects = projects($expts);

#
# Phase 5: use projects users list to build up user list
# 
my $users = users($projects);

229 230 231 232 233 234 235 236
#
# Special Emulab annual report info report.
#
if ($report) {
    doreport();
    exit(0);
}

237 238 239 240 241 242 243 244 245
print "History [$starttime-$endtime]:\n";
my $ix = 1;
foreach my $he (@$history) {
    my $node = $he->{'node'};
    my $nix = $he->{'node_idx'};
    my $s = $he->{'start'};
    my $e = $he->{'end'};
    my $eix = $he->{'expt_idx'};
    my $eeix = $he->{'emulab_exptidx'};
246
    my $ehix = $he->{'ehist_idx'};
247 248 249 250 251 252 253 254 255

    #
    # If there was something wrong with a node's DB info, we will not
    # have assigned an index. Skip it.
    #
    if (!$nix) {
	next;
    }

256 257 258 259 260 261 262 263 264 265 266
    #
    # In summary form, just the info that is needed for student project:
    # [time range]: node: user,...
    #
    if ($summary) {
	my $ee = $expts->[$eix-1];
	my $pix = $ee->{'proj_idx'};
	my $pe = $projects->[$pix-1];
	my $ulist = join(',', @{$pe->{'users'}});	
	print "node='$node', start='$s', end='$e', ulist='$ulist'\n";
    } elsif ($normalize) {
267
	print "index,node_index,start,end,expt_index,ehist_index\n"
268
	    if ($ix == 1);
269
	print "$ix,$nix,$s,$e,$eix,$ehix\n";
270
    } else {
271
	print "$ix: node=$nix ($node), time=[$s-$e], expt=$eix ($eeix), ehist=$ehix\n";
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    }
    $ix++;
}

if ($summary) {
    goto dumpusers;
}

print "\nNodes:\n";
foreach my $ne (@$nodes) {
    my $nix = $ne->{'node_idx'};
    my $name = $ne->{'name'};
    my $ip = $ne->{'IP'};
    my $mac = $ne->{'mac'};
    if ($normalize) {
	print "node_index,name,IP,mac\n"
	    if ($nix == 1);
	print "$nix,$name,$ip,$mac\n";
    } else {
	print "$nix: name=$name, IP=$ip, mac=$mac\n";
    }
}

print "\nExperiments:\n";
foreach my $ee (@$expts) {
    my $eix = $ee->{'expt_idx'};
    my $name = $ee->{'name'};
    my $proj = $ee->{'proj'};
    my $pix = $ee->{'proj_idx'};
    my $eeix = $ee->{'emulab_exptidx'};
    if ($normalize) {
	print "expt_index,name,proj_index\n"
	    if ($eix == 1);
	print "$eix,$name,$pix\n";
    } else {
	print "$eix: name=$name, proj=$pix ($proj), emulab_idx=$eeix\n";
    }
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
print "\nExperiment History (instances):\n";
foreach my $eh (@$expthistory) {
    my $ehix = $eh->{'ehist_idx'};
    my $eix = $eh->{'expt_idx'};
    my $s = $eh->{'start'};
    my $e = $eh->{'end'};

    if ($normalize) {
	print "ehist_index,expt_index,start,end\n"
	    if ($ehix == 1);
	print "$ehix,$eix,$s,$e\n";
    } else {
	print "$ehix: expt_idx=$eix, start=$s, end=$e\n";
    }
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
print "\nProjects:\n";
foreach my $pe (@$projects) {
    my $pix = $pe->{'proj_idx'};
    my $name = $pe->{'name'};
    my $nusers = @{$pe->{'users'}};
    if ($normalize) {
	print "project_index,name\n"
	    if ($pix == 1);
	print "$pix,$name\n";
    } else {
	my $ulist = join(',', @{$pe->{'users'}});
	print "$pix: name=$name, users=$nusers ($ulist)\n";
    }
}

dumpusers:

print "\nUsers:\n";
foreach my $ue (@$users) {
    my $uix = $ue->{'user_idx'};
    my $name = $ue->{'name'};
    my $affil = $ue->{'affil'};
    my $city = $ue->{'city'};
    my $state = $ue->{'state'};
    my $country = $ue->{'country'};
    my $zip = $ue->{'zip'};
353
    my $last = $ue->{'lastactive'};
Mike Hibler's avatar
Mike Hibler committed
354 355
    $last = $endtime
	if ($last > $endtime);
356 357
    my $lat = $ue->{'latitude'};
    my $lng = $ue->{'longitude'};
358
    my $loc = $ue->{'location'};
359
    if ($summary) {
360 361 362 363 364 365
	$affil =~ s/^\s+//; $affil =~ s/\'//g;
	$city =~ s/^\s+//; $city =~ s/\'//g;
	$state =~ s/^\s+//; $state =~ s/\'//g;
	$country =~ s/^\s+//; $country =~ s/\'//g;
	$zip =~ s/^\s+//; $zip =~ s/\'//g;
	print "index='$uix', name='$name', affil='$affil', city='$city', state='$state', country='$country', zip='$zip', lastactive='$last'";
366
	if ($dogeo) {
367
	    print ", latitude='$lat', longitude='$lng', location='$loc'";
368 369
	}
	print "\n";
370
    } elsif ($normalize) {
371
	if ($uix == 1) {
372
	    print "user_index,name,affil,city,state,country,zip,lastactive";
373
	    if ($dogeo) {
374
		print ",latitude,longitude,location";
375 376 377
	    }
	    print "\n";
	}
378
	print "$uix,$name,$affil,$city,$state,$country,$zip,$last";
379
	if ($dogeo) {
380 381
	    $loc =~ s/,/;/g;
	    print ",$lat,$lng,$loc";
382 383
	}
	print "\n";
384
    } else {
385
	print "$uix: name='$name', affil='$affil', city='$city', state='$state', country='$country', zip='$zip', lastactive='$last'";
386
	if ($dogeo) {
387
	    print ", latitude='$lat', longitude='$lng', location='$loc'";
388 389
	}
	print "\n";
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    }
}

if ($normalize) {
    print "\nUserToProject:\n";
    print "user_index,proj_index\n";
    foreach my $pe (@$projects) {
	my $pix = $pe->{'proj_idx'};
	foreach my $uix (@{$pe->{'users'}}) {
	    print "$uix,$pix\n";
	}
    }
}

exit(0);

406
sub nodehistory($$;$$)
407
{
408
    my ($stime,$etime,$dnode,$dnodetype) = @_;
409 410 411 412 413 414 415 416 417 418 419 420
    my @history = ();
    my %validnode = ();

    #
    # XXX we need to figure out what every node in question was doing at
    # the beginning of the time window.
    #
    my @mynodes = ();
    my $nodelist = "";
    if ($dnode) {
	push(@mynodes, $dnode);
	$nodelist = "node_id='$dnode'";
421 422 423 424 425 426 427 428 429 430 431 432 433 434
    } elsif ($dnodetype) {
	# XXX only look at nodes that existed at the end of the time window
	my $query =
	    DBQueryFatal("SELECT n.node_id FROM nodes AS n ".
			 "WHERE n.type='$nodetype' AND n.role='testnode' ".
			 "  AND UNIX_TIMESTAMP(n.inception)<$etime ".
			 "ORDER BY n.priority");
	if (!$query) {
	    return undef;
	}
	while (my %row = $query->fetchhash()) {
	    push(@mynodes, $row{'node_id'});
	}
	$nodelist = "node_id in ('" . join("','", @mynodes) . "')";
435
    } else {
436
	# XXX only look at nodes that existed at the end of the time window
437 438 439
	my $query =
	    DBQueryFatal("SELECT n.node_id FROM nodes AS n, node_types AS t ".
			 "WHERE n.type=t.type AND n.role='testnode' ".
440 441
			 "  AND t.class='pc' AND UNIX_TIMESTAMP(n.inception)<$etime ".
			 "ORDER BY n.priority");
442 443 444 445 446 447 448 449
	if (!$query) {
	    return undef;
	}
	while (my %row = $query->fetchhash()) {
	    push(@mynodes, $row{'node_id'});
	}
	$nodelist = "node_id in ('" . join("','", @mynodes) . "')";
    }
450 451
    print STDERR "Working with ", scalar(@mynodes), " nodes\n"
	if ($debug); 
452 453 454 455 456 457 458 459 460 461

    my %allocstart = ();
    my %allocexpt = ();

    #
    # Find the most recent node_history record before the start time and
    # see if it was allocated or free.
    #
    foreach my $node (@mynodes) {
	my $query =
462
	    DBQueryFatal("SELECT op,exptidx,stamp FROM node_history ".
463
			 "WHERE stamp<$stime AND node_id='$node' ".
464 465 466 467 468
			 "ORDER BY stamp DESC LIMIT 1");
	if ($query && $query->numrows) {
	    my %row = $query->fetchhash();
	    my $op = $row{'op'};
	    if ($op eq "alloc" || $op eq "move") {
469
		$allocrstart{$node} = $row{'stamp'};
470
		$allocstart{$node} = $stime;
471
		$allocexpt{$node} = $row{'exptidx'};
472 473
	    } elsif ($op ne "free") {
		print STDERR "$node: op=$op for expt=", $row{'exptidx'}, "\n";
474 475 476 477 478 479 480 481 482 483 484
	    }
	}
	$validnode{$node} = 1;
    }

    #
    # Get all the history records that fall into the time range.
    #
    my $query =
	DBQueryFatal("SELECT node_id,op,exptidx,stamp,phys_nodeid ".
		     "FROM node_history ".
485
		     "WHERE stamp>=$stime AND stamp<$etime ".
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
		     "    AND $nodelist ".
		     "ORDER by history_id");
    if (!$query) {
	return undef;
    }

    while (my %row = $query->fetchhash()) {
	my $op = $row{'op'};
	my $node = $row{'node_id'};
	my $exptidx = $row{'exptidx'};
	my $stamp = $row{'stamp'};
	my $pnode = $row{'phys_nodeid'};

	if ($op eq "alloc") {
	    if (exists($allocstart{$node})) {
501 502
		my $ostart = $allocstart{$node};
		my $oexpt = $allocexpt{$node};
503
		print STDERR
504
		    "*** inconsistant data: $node alloc at $stamp to $exptidx: already allocated at $ostart by expt $oexpt\n";
505
	    }
506
	    delete $allocrstart{$node};
507 508 509 510 511 512 513 514 515 516 517 518 519
	    $allocstart{$node} = $stamp;
	    $allocexpt{$node} = $exptidx;
	    next;
	}
	if ($op eq "free" || $op eq "move") {
	    if (!exists($allocstart{$node})) {
		print STDERR
		    "*** inconsistant data: $node already free ($exptidx)\n"
		    if ($exptidx != 3204 && # reloading
			$exptidx != 3210 && # reloadpending
			$exptidx != 3205);  # hwdown
		next;
	    }
520 521 522 523 524 525 526 527 528 529 530 531 532

	    my $inexptidx = $allocexpt{$node};
	    if ($op eq "free" && $exptidx != $inexptidx) {
		print STDERR
		    "*** $node: $op from wrong expt? ".
		    "($exptidx instead of $inexptidx)\n";
	    } elsif ($op eq "move" &&
		     !($exptidx == 3210 || $exptidx == 3204 ||
		       $exptidx == 3205 || $exptidx == 48116)) {
		print STDERR
		    "*** $node: unexpected $op from $inexptidx to $exptidx\n";
	    }

533 534 535 536
	    if ($stamp < $allocstart{$node}) {
		print STDERR
		    "*** inconsistant data: bogus start/stop times\n";
	    }
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	    # don't record entries for system experiments
	    elsif ($inexptidx == 3210 || $inexptidx == 3204 ||
		   $inexptidx == 3205 || $inexptidx == 48116) {
		;
	    }
	    else {
		#
		# XXX argh! We can wind up here with a successful node
		# allocation even if the corresponding swapin failed;
		# i.e., the node was allocated but failed to boot/configue.
		# We attempt to weed those out by checking the testbed_stats
		# table entry in which the node allocation occurred.
		#
		my $doit = 1;
		my $estart = exists($allocrstart{$node}) ?
		    $allocrstart{$node} : $allocstart{$node};
		my $query2 =
		    DBQueryFatal("SELECT action,exitcode FROM testbed_stats ".
				 "WHERE exptidx=$inexptidx AND ".
				 "UNIX_TIMESTAMP(start_time)<=$estart AND ".
				 "UNIX_TIMESTAMP(end_time)>=$estart");
		if ($query2 && $query2->numrows) {
		    my ($act, $ec) = $query2->fetchrow_array();
		    if ($act =~ /^(start|swapin|swapmod)$/) {
			if ($ec != 0) {
			    print STDERR
				localtime($estart) . ": *** $node: ignoring allocation as part of failed start/swapin/swapmod\n"
				if (0);
			    $doit = 0;
			}
		    } else {
			print STDERR
			    "*** $node: testbed_stats entry for expt $inexptidx not an alloc! (action=$act,exitcode=$ec)\n";
		    }
		} else {
		    if (!exists($allocrstart{$node})) {
			print STDERR
			    "*** $node: could not find testbed_stats entry for expt $inexptidx at $estart\n"
			    if (0);
		    }
		}
		    
		if ($doit) {
		    my $he = {
			'node' => $node,
			'start' => $allocstart{$node},
			'end' => $stamp,
			'emulab_exptidx' => $inexptidx
		    };
		    push(@history, $he);
		}
	    }
	    delete $allocrstart{$node};
590 591 592 593 594 595 596 597 598 599
	    delete $allocstart{$node};
	    delete $allocexpt{$node};
	    next;
	}
    }

    #
    # Add records for any node still allocated at the end of the range
    #
    foreach my $node (keys %allocstart) {
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
	#
	# XXX argh! We can wind up here with a successful node
	# allocation even if the corresponding swapin failed;
	# i.e., the node was allocated but failed to boot/configue.
	# We attempt to weed those out by checking the testbed_stats
	# table entry in which the node allocation occurred.
	#
	my $doit = 1;
	my $estart = exists($allocrstart{$node}) ?
	    $allocrstart{$node} : $allocstart{$node};
	my $inexptidx = $allocexpt{$node};
	my $query2 =
	    DBQueryFatal("SELECT action,exitcode FROM testbed_stats ".
			 "WHERE exptidx=$inexptidx AND ".
			 "UNIX_TIMESTAMP(start_time)<=$estart AND ".
			 "UNIX_TIMESTAMP(end_time)>=$estart");
	if ($query2 && $query2->numrows) {
	    my ($act, $ec) = $query2->fetchrow_array();
	    if ($act =~ /^(start|swapin|swapmod)$/) {
		if ($ec != 0) {
		    print STDERR
			localtime($estart) . ": *** $node: ignoring allocation as part of failed start/swapin/swapmod\n"
			if (0);
		    $doit = 0;
		}
	    } else {
		print STDERR
		    "*** $node: testbed_stats entry for expt $inexptidx not an alloc! (action=$act,exitcode=$ec)\n";
	    }
	} else {
	    if (!exists($allocrstart{$node})) {
		print STDERR
		    "*** $node: could not find testbed_stats entry for expt $inexptidx at $estart\n"
		    if (0);
	    }
	}

	if ($doit) {
	    my $he = {
		'node' => $node,
		'start' => $allocstart{$node},
		'end' => $etime,
		'emulab_exptidx' => $allocexpt{$node}
	    };
	    push(@history, $he);
	}	    
646 647
    }

648 649 650 651 652
    # Make sure we are sorted by start time, end time
    @history = sort {
	$a->{'start'} <=> $b->{'start'} || $a->{'end'} <=> $b->{'end'}
    } @history;
    
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    return \@history;
}

sub nodes($)
{
    my ($history) = @_;
    my @nodes = ();
    my $nix = 1;
    my %nodeix = ();

    foreach my $he (@$history) {
	my $n = $he->{'node'};
	my $s = $he->{'start'};
	my $e = $he->{'end'};

	if (!exists($nodeix{$n})) {
	    # make sure the node still exists
	    my $nobj = Node->Lookup($n);
	    if (!$nobj) {
672
		print STDERR "*** bad node: $n: no such node\n";
673 674 675 676
		next;
	    }
	    my $iobj = Interface->LookupControl($nobj);
	    if (!$iobj) {
677
		print STDERR "*** bad node: $n: no control interface\n";
678 679 680 681 682
		next;
	    }
	    my $ip = $iobj->IP();
	    my $mac = $iobj->mac();
	    if (!$ip || !$mac) {
683
		print STDERR "*** bad node: $n: no cnet IP/MAC\n";
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
		next;
	    }
	    my $ne = {
		'node_idx' => $nix,
		'name' => $n,
		'IP' => $ip,
		'mac' => $mac
	    };
	    push(@nodes, $ne);
	    $nodeix{$n} = $nix;
	    $nix++;
	}
	$he->{'node_idx'} = $nodeix{$n};
    }

    return \@nodes;
}

sub experiments($)
{
    my ($history) = @_;
    my @expts = ();
706
    my @ehistory = ();
707
    my $eix = 1;
708
    my $ehix = 1;
709
    my %exptix = ();
710
    my %expthix = ();
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

    foreach my $he (@$history) {
	my $eeix = $he->{'emulab_exptidx'};

	if (!exists($exptix{$eeix})) {
	    my $query =
		DBQueryFatal("SELECT pid,eid FROM experiment_stats ".
			     "WHERE exptidx=$eeix");
	    if (!$query) {
		return undef;
	    }
	    if ($query->numrows == 0) {
		print STDERR "*** bad experiment: no such experiment: $eeix\n";
		next;
	    }
	    my %row = $query->fetchhash();
	    my $pid = $row{'pid'};
	    my $eid = $row{'eid'};
	    if (!$pid || !$eid) {
		print STDERR "*** bad experiment: no pid/eid\n";
		next;
	    }
	    my $ee = {
		'expt_idx' => $eix,
		'name' => $eid,
		'proj' => $pid,
		'emulab_exptidx' => $eeix
	    };
	    push(@expts, $ee);
	    $exptix{$eeix} = $eix;
	    $eix++;
	}
	$he->{'expt_idx'} = $exptix{$eeix};
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

	#
	# Compute experiment instances.
	#
	# Unfortunately, the node [start-end] times do not match exactly
	# with experiment instance [start-end] times, so we cannot just
	# find all node_history records that have the same start time or
	# the same end time to identify an instance and all its nodes.
	#
	# So instead we identify an instance as follows. The first time
	# we see a node_history record for a particular exptidx, we record
	# the start/end times as defining the "current instance". For every
	# subsequent node_history record we see for that exptidx in which
	# the start time is less than the "current instance" end time, we
	# consider it part of the current instance. If we find a record in
	# which the start time exceeds the end time of the current instance,
	# we know we have started a new instance.
	#
	# I tried getting this out of the DB instead but...its complicated.
	#
	my $ix = $he->{'expt_idx'};
	my $s = $he->{'start'};
	my $e = $he->{'end'};
	if (!exists($expthix{$ix})) {
	    $expthix{$ix}{'start'} = $s;
	    $expthix{$ix}{'end'} = $e;
	    @{$expthix{$ix}{'nodes'}} = ();
	} elsif ($s < $expthix{$ix}{'end'}) {
	    if ($s < $expthix{$ix}{'start'}) {
		$expthix{$ix}{'start'} = $s;
	    }
	    if ($e > $expthix{$ix}{'end'}) {
		$expthix{$ix}{'end'} = $e;
	    }
	} else {
	    my $ehe = {
		'ehist_idx' => $ehix,
		'expt_idx' => $ix,
		'start' => $expthix{$ix}{'start'},
		'end' => $expthix{$ix}{'end'}
	    };
	    push(@ehistory, $ehe);
	    my %sawnode = ();
	    foreach my $e (@{$expthix{$ix}{'nodes'}}) {
		my $n = $e->{'node'};

		#
		# XXX sanity check that a node only appears once per instance
		# XXX looks like it can appear multiple times, as the result
		# of a swap modify. Just warn, it does not cause any harm for
		# what we are doing right now (just reporting).
		#
		if (0 && exists($sawnode{$n})) {
		    my $ee = $expts[$ix - 1];
		    my $pid = $ee->{'proj'};
		    my $eid = $ee->{'name'};
		    print STDERR "WARNING: $n already in $pid/$eid ($ix/$eeix)\n";
		} else {
		    $sawnode{$n} = 1;
		}
		$e->{'ehist_idx'} = $ehix;
	    }
	    $ehix++;

	    $expthix{$ix}{'start'} = $s;
	    $expthix{$ix}{'end'} = $e;
	    @{$expthix{$ix}{'nodes'}} = ();
	}
	push(@{$expthix{$ix}{'nodes'}}, $he);
813 814
    }

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    # Dump outstanding instances
    foreach my $ix (keys %expthix) {
	my $ehe = {
	    'ehist_idx' => $ehix,
	    'expt_idx' => $ix,
	    'start' => $expthix{$ix}{'start'},
	    'end' => $expthix{$ix}{'end'}
	};
	push(@ehistory, $ehe);
	my %sawnode = ();
	my $nodestr = "";
	foreach my $e (@{$expthix{$ix}{'nodes'}}) {
	    my $n = $e->{'node'};
	    $nodestr .= " $n";

	    #
	    # XXX sanity check that a node only appears once per instance
	    # XXX looks like it can appear multiple times, as the result
	    # of a swap modify. Just warn, it does not cause any harm for
	    # what we are doing right now (just reporting).
	    #
	    if (0 && exists($sawnode{$n})) {
		my $ee = $expts[$ix - 1];
		my $pid = $ee->{'proj'};
		my $eid = $ee->{'name'};
		my $_eeix = $e->{'emulab_exptidx'};
		print STDERR "WARNING: $n already in $pid/$eid ($ix/$_eeix): $nodestr\n";
	    } else {
		$sawnode{$n} = 1;
	    }
	    $e->{'ehist_idx'} = $ehix;
	}
	$ehix++;
    }

    return (\@expts, \@ehistory);
851 852 853 854 855 856 857 858 859 860 861 862 863
}

sub projects($)
{
    my ($expts) = @_;
    my @projs = ();
    my $pix = 1;
    my %projix = ();

    foreach my $ee (@$expts) {
	my $pid = $ee->{'proj'};
	if (!exists($projix{$pid})) {
	    # Look up the projects main group
864
	    my @users = ();
865 866
	    my $gobj = Group->Lookup($pid, $pid);
	    if (!$gobj) {
867 868 869 870 871 872
		print STDERR
		    "*** $pid: project no longer exists, cannot get users.\n";
	    } else {
		if ($gobj->MemberList(\@users) != 0) {
		    print STDERR "*** $pid: could not get user list.\n";
		}
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
	    }
	    my $pe = {
		'proj_idx' => $pix,
		'name' => $pid,
		'user_objs' => \@users
	    };
	    push(@projs, $pe);
	    $projix{$pid} = $pix;
	    $pix++;
	}
	$ee->{'proj_idx'} = $projix{$pid};
    }

    return \@projs;
}

sub users($)
{
    my ($projs) = @_;
    my @users = ();
    my $uix = 1;
    my %userix = ();
    my %userprojs = ();

    foreach my $pe (@$projs) {
	my $uobjs = $pe->{'user_objs'};
	my @pusers = ();
	foreach my $obj (@$uobjs) {
	    my $name = $obj->uid();
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

	    #
	    # Make sure they existed by the end of the time window.
	    #
	    my $ctime = str2time($obj->created());
	    if ($ctime && $ctime >= $endtime) {
		print STDERR "Skip user '$name' created on " .
		    $obj->created() . "\n"
		    if (0);
		next;
	    }

	    #
	    # Filter web-only or never approved users.
	    #
	    if (!($obj->active() || $obj->frozen() || $obj->archived()) ||
		$obj->webonly()) {
		print STDERR "Skip inactive/webonly user '$name'\n"
		    if (0);
		next;
	    }

	    #
	    # See if they were active since the start of the time window.
	    # XXX since this is inexact, it is an option.
	    #
	    my ($astamp,$atime) = lastactive($name);
	    if ($noinactive && $astamp < $starttime) {
		print STDERR "Skip user '$name' last active on $atime\n"
		    if (1);
932 933 934 935
		next;
	    }

	    if (!exists($userix{$name})) {
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
		my $affil = $obj->affil();
		$affil ="" if !defined($affil);
		$affil =~ tr/,/ /s if ($normalize);
		my $city = $obj->city();
		$city ="" if !defined($city);
		$city =~ tr/,/ /s if ($normalize);
		my $state = $obj->state();
		$state ="" if !defined($state);
		$state =~ tr/,/ /s if ($normalize);
		my $country = $obj->country();
		$country ="" if !defined($country);
		$country =~ tr/,/ /s if ($normalize);
		my $zip = $obj->zip();
		$zip ="" if !defined($zip);
		$zip =~ tr/,/ /s if ($normalize);

952 953 954 955 956 957 958
		my $ue = {
		    'user_idx' => $uix,
		    'name' => $name,
		    'affil' => $affil,
		    'city' => $city,
		    'state' => $state,
		    'country' => $country,
959 960
		    'zip' => $zip,
		    'lastactive' => $astamp
961 962 963 964
		};
		push(@users, $ue);
		$userix{$name} = $uix;
		$uix++;
965 966 967 968 969 970
	    } else {
		# recorded idx is 1-based, array is 0-based
		my $idx = $userix{$name} - 1;
		if ($astamp > $users[$idx]->{'lastactive'}) {
		    $users[$idx]->{'lastactive'} = $astamp;
		}
971 972 973 974 975 976 977
	    }
	    push(@pusers, $userix{$name});
	}
	delete $pe->{'user_objs'};
	$pe->{'users'} = \@pusers;
    }

978 979 980 981
    if ($dogeo) {
	geoize(\@users);
    }

982 983
    return \@users;
}
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
#
# Determine as best we can the last activity of a user.
# 
sub lastactive($)
{
    my ($user) = @_;
    my $last = "";
    my $laststamp = 0;

    # Find the last login
    my $query =
	DBQueryFatal("SELECT date,time FROM uidnodelastlogin ".
		     "WHERE uid='$user'");
    if ($query && $query->numrows > 0) {
	my %row = $query->fetchhash();
	my $tstamp = str2time($row{'date'} . " " . $row{'time'});
	if ($tstamp > $laststamp) {
	    $laststamp = $tstamp;
	    $last = $row{'date'} . " " . $row{'time'};
	}
    }

    # Find last weblogin and activity
    $query =
	DBQueryFatal("SELECT weblogin_last,last_activity FROM ".
		     "users AS u, user_stats AS s ".
		     "WHERE s.uid_idx=u.uid_idx AND u.uid='$user'");
    if ($query && $query->numrows > 0) {
	my %row = $query->fetchhash();
	if ($row{'weblogin_last'}) {
	    my $tstamp = str2time($row{'weblogin_last'});
	    if ($tstamp && $tstamp > $laststamp) {
		$laststamp = $tstamp;
		$last = $row{'weblogin_last'};
	    }
	}
	if ($row{'last_activity'}) {
	    $tstamp = str2time($row{'last_activity'});
	    if ($tstamp && $tstamp > $laststamp) {
		$laststamp = $tstamp;
		$last = $row{'last_activity'};
	    }
	}
    }

    return ($laststamp, $last);
}

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
#
# For geo info we use the intermediate files generated by the process of
# updating our usermap. Part of that process is to generate a filename
# based on the name the user gave and filling that file with the output
# of a Google aps API query (see the emulab-utah repo, gmaps subdir).
# We combine the city/state/country info the same way we did to create
# name of the json intermediate file.
#
sub geoize($)
{
    my ($uref) = @_;
    my $infodir = "/users/mike/emulab-utah/gmaps/json";

    if (!-d $infodir) {
	return;
    }
    my @files = `/bin/ls -1 $infodir`;
    if (@files == 0) {
	return;
    }

    require JSON;

    #
    # Make a hash indexed by the user provided name and providing
    # a canonical name, latitude, and longitude.
    #
    my %cities = ();
    foreach my $file (@files) {
	next
	    if ($file !~ /^(.*)\.json$/);
	my $ename = $1;
	next
	    if (!open(FD, "<$infodir/$file"));
	my $json;
	{
	    local $/;
	    $json = <FD>;
	}
	close(FD);
	my $doc = JSON::decode_json($json);
	next
	    if (!$doc || $doc->{'status'} ne "OK");

	my $res = $doc->{'results'}[0];
	$cities{$ename}{'fname'} = $res->{'formatted_address'};
	$cities{$ename}{'lat'} = $res->{'geometry'}->{'location'}->{'lat'};
	$cities{$ename}{'lng'} = $res->{'geometry'}->{'location'}->{'lng'};
    }

    #require Data::Dumper;
    #print "Info:\n";
    #print Data::Dumper::Dumper(\%cities);

    #
    # Take our user entries, convert the city/state/country into the
    # format used by our usermap files.
    #
    foreach $user (@$uref) {
	my $city = $user->{'city'};
	my $state = $user->{'state'};
	my $country = $user->{'country'};
	$city =~ s/^\s+//;
	$city =~ s/\s+$//;
	$state =~ s/^\s+//;
	$state =~ s/\s+$//;
	$country =~ s/^\s+//;
	$country =~ s/\s+$//;

	$city = lc($city);
	$state = lc($state);
	$country = lc($country);

1106
	my $key;
1107 1108 1109
	if ($country ne "usa" && $country ne "us" &&
	    $country ne "" && $country ne "NULL") {
	    $key = "$city-$country";
Mike Hibler's avatar
Mike Hibler committed
1110 1111 1112 1113 1114 1115
	}
	# XXX Google does not consider Peurto Rico part of the US?
	elsif ($country eq "usa" && $state eq "pr") {
	    $key = "$city-$state";
	}
	else {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
	    $key = "$city-$state-$country";
	}
	$key =~ s/\s+/-/g;
	$key =~ s/[^\w-]//g;

again:
	if (exists($cities{$key})) {
	    $user->{'latitude'} = $cities{$key}{'lat'};
	    $user->{'longitude'} = $cities{$key}{'lng'};
	    $user->{'location'} = $cities{$key}{'fname'};
	} elsif ($key =~ /(.*)-us$/) {
	    $key = "$1-usa";
	    goto again;
	} else {
	    print STDERR "*** user '" . $user->{'name'} .
		"': could not find geo info for '$key' (city='".
		$user->{'city'} . "', state='" .
		$user->{'state'} . "', country='" .
1134 1135
		$user->{'country'} . "')\n"
		if (0);
1136 1137 1138 1139 1140 1141
	    $user->{'latitude'} = "";
	    $user->{'longitude'} = "";
	    $user->{'location'} = "";
	}
    }
}
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

my %pactivity;

sub sortem() {
    return $pactivity{$a}{'projref'}->{'name'} cmp
	$pactivity{$b}{'projref'}->{'name'};
}

#
# Calculate how many projects created how many experiments.
# Calculate node allocations and node hours allocated per project.
# Calculate total node allocations and node hours allocated.
#
# Note that by convention, we have never counted emulab-ops.
#
sub doreport()
{
    my ($pcount, $ecount);
    my %ignoreproj = (
	'emulab-ops' => 1,
    );

    #
    # Calculate how many projects created how many experiments.
    #
    my $total_projects = 0;
    my $total_experiments = 0;
    my $total_instances = 0;

    foreach my $proj (@$projects) {
	if (!$ignoreproj{$proj->{'name'}}) {
	    $total_projects++;
	}
    }
    foreach my $expt (@$expts) {
	my $pix = $expt->{'proj_idx'};
	my $proj = $projects->[$pix-1];
	if (!$ignoreproj{$proj->{'name'}}) {
	    $total_experiments++;
	}
    }
    foreach my $eh (@$expthistory) {
	my $eix = $eh->{'expt_idx'};
	my $expt = $expts->[$eix-1];
	my $pix = $expt->{'proj_idx'};
	my $proj = $projects->[$pix-1];
	if (!$ignoreproj{$proj->{'name'}}) {
	    $total_instances++;
	}
    }

    my $startstr = localtime($starttime);
    my $endstr = localtime($endtime);
    print "$startstr to $endstr:\n";
    print "$total_projects projects started $total_instances instances of $total_experiments experiments\n";

    foreach my $eh (@$expthistory) {
	my $hix = $eh->{'ehist_idx'};
	my $eix = $eh->{'expt_idx'};
	my $expt = $expts->[$eix-1];
	my $pix = $expt->{'proj_idx'};
	my $proj = $projects->[$pix-1];

	if ($expt->{'expt_idx'} != $eix ||
	    $eh->{'ehist_idx'} != $hix ||
	    $eh->{'expt_idx'} != $eix ||
	    $proj->{'proj_idx'} != $pix) {
	    die("Bogons in the data!");
	}

	if (!exists($pactivity{$pix})) {
	    $pactivity{$pix}{'projref'} = $proj;
	    $pactivity{$pix}{'experiments'} = 1;
	} else {
	    $pactivity{$pix}{'experiments'}++;
	}


    }

    #
    # Calculate node allocations and node hours allocated per project.
    #
    my $total_nodes = 0;
    my $total_nodeseconds = 0;

    foreach my $he (@$history) {
	my $node = $he->{'node'};
	my $nix = $he->{'node_idx'};
	my $s = $he->{'start'};
	my $e = $he->{'end'};
	my $eix = $he->{'expt_idx'};
	my $eeix = $he->{'emulab_exptidx'};
	my $hix = $he->{'ehist_idx'};

	#
	# If there was something wrong with a node's DB info, we will not
	# have assigned an index. Skip it.
	#
	if (!$nix) {
	    next;
	}

	# Clip the start and end times. XXX should already be done.
	$s = $starttime if ($s < $starttime);
	$e = $endtime if ($e > $endtime);

	my $ehist = $expthistory->[$hix-1];
	my $expt = $expts->[$eix-1];
	my $pix = $expt->{'proj_idx'};
	my $proj = $projects->[$pix-1];

	if ($ignoreproj{$proj->{'name'}}) {
	    next;
	}

	if (!exists($pactivity{$pix})) {
	    $pactivity{$pix}{'projref'} = $proj;
	    $pactivity{$pix}{'nodes'} = 0;
	    $pactivity{$pix}{'nodeseconds'} = 0;
	}
	$pactivity{$pix}{'nodes'}++;
	$pactivity{$pix}{'nodeseconds'} += ($e - $s);

	$total_nodes++;
	$total_nodeseconds += ($e - $s);
    }

    printf("%d total nodes allocated (%.2f node days)\n",
	   $total_nodes, $total_nodeseconds / (24*3600));
    foreach my $pix (sort sortem keys %pactivity) {
	my $proj = $projects->[$pix-1];
	my $pname = $proj->{'name'};
	if (!$ignoreproj{$proj->{'name'}}) {
	    my $nodes = $pactivity{$pix}{'nodes'};
	    my $nodehours = $pactivity{$pix}{'nodeseconds'} / 3600;

	    printf("  %s: %d nodes (%.2f node days)\n",
		   $pname, $nodes, $nodehours/24);
	}
    }
}