plablinkdata.in 16.6 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2000-2003, 2005 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
# 
# {{{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/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#
use English;
use Getopt::Std;
use POSIX;
use IO::Handle;

#
# Age (in seconds) at which we consider metric data stale
#
my $STALEAGE  = 30 * 60;

#
# This is the magic node which is equivalent to the TBDB_WIDEAREA_LOCALNODE.
# This could be moved to a configure variable, but I'm not going to do so
# until there's a need to go to that trouble. It's hacky, no matter where
# you put it.
#
my $MAGICNODE = "planetlab2.flux.utah.edu";

sub usage()
{
    print STDERR
	"Usage: plabmetrics [-d] [-n] [[-l | -b] <datafile>]]\n".
	"       -d       - Turn on debugging\n".
	"       -f       - Do not run in background\n".
	"       -n       - Do not change the DB\n".
	"       -l file  - Process latency info file\n".
        "       -b file  - Process bandwidth info file\n";
    exit(-1);
}
53 54 55 56 57 58 59

sub InsertLinkData();
sub ParseLatency($);
sub ParseBW($);
sub DownLoadURL($$);
sub daemonize();

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
my $optlist = "l:b:dnf";
my $debug   = 0;
my $daemon  = 1;
my $impotent= 0;
my $datafile;
my $selected= 0; # 1 for latency, 2 for bandwidth.

#
# Only real root can call this.
# 
if ($UID != 0) {
    print STDERR "You must be root to run this script!\n";
    exit(-1);
}

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

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

#
# Untaint the path
# 
$ENV{'PATH'} = '/bin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;

# Locals
my $logfile	= "$TB/log/plablinkdata.log";
my $tempfile	= "/tmp/plablink.$$";
102 103
#my $LATURL	= "http://www.pdos.lcs.mit.edu/~strib/pl_app/current.app";
my $LATURL      = "http://ping.ececs.uc.edu/ping/current.app";
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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
my $BWURL	= "http://www.planet-lab.org/logs/iperf/files";
my %linkdata    = (); # Map IP to link data.
my %hostmap	= (); # Map hostname to IP.
my $exitval     = 0;
my $now         = time();
my $LocalIface;

# Be careful not to exit on transient error
$libdb::DBQUERY_MAXTRIES = 10;

#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"f"})) {
    $daemon = 0;
}
if (defined($options{"l"})) {
    $selected = 1;
    $datafile = $options{"l"};
}
if (defined($options{"b"})) {
    $selected = 2;
    $datafile = $options{"b"};
}
if (defined($datafile)) {
    # Note different taint check (allow /).
    if ($datafile =~ /^([-\w.\/]+)$/) {
	$datafile = $1;
    }
    else {
	die("Tainted file name: $datafile");
    }
}

# Disconnect from caller and run in background. Exits after one run.
if ($daemon) {
    daemonize();
}

print "\n=== plablinkdata running at " . `date`;

#
# Find out the interface to use for the TBDB_WIDEAREA_LOCALNODE, since
# we do not want to hardcode it anywhere.
#
my $query_result =
    DBQueryFatal("select iface from interfaces ".
165 166
		 "where node_id='" . TBDB_WIDEAREA_LOCALNODE . "' ".
		 "and role='ctrl'");
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
if ($query_result->num_rows() != 1) {
    fatal("Unable to determine iface for " . TBDB_WIDEAREA_LOCALNODE);
}
($LocalIface) = ($query_result->fetchrow());

#
# Grab the node list from the DB in one query, which we use later to
# map from the IP we get from the link data, to our node_id. 
#
$query_result =
    DBQueryFatal("select i.node_id,i.IP,i.iface,w.hostname from nodes as n ".
		 "left join node_types as nt on n.type=nt.type ".
		 "left join interfaces as i on i.node_id=n.node_id ".
		 "left join widearea_nodeinfo as w on w.node_id=n.node_id ".
		 "where nt.isremotenode=1 and nt.isvirtnode=0 ".
    		 "and nt.class='pcplabphys'");

while (my ($nodeid,$IP,$iface,$hostname) = $query_result->fetchrow_array()) {
    $linkdata{$IP} = {
	NODEID	 => $nodeid,
	IFACE    => $iface,
	HOSTNAME => $hostname,
	INDEX    => undef,
	LATENCY  => {},
	BW       => {},
    };
    $hostmap{$hostname} = $IP;
}

196 197 198 199 200 201 202 203 204 205 206 207
#
# Grab the last known good hostname<->IP map from the db in case we have to 
# resolve hostnames while processing latency data, and the host doesn't resolve
# via gethostbyname.
#
%dbhostipmap = ();
$query_result = DBQueryFatal("select hostname,IP from plab_mapping");

while (my ($hostname,$IP) = $query_result->fetchrow_array()) {
    $dbhostipmap{$hostname} = $IP;
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
#
# If given a datafile, then parse it as the type of file that was specified
# on the command line.
# 
if (defined($datafile)) {
    # Default to a latency file.
    if (!$selected || $selected == 1) {
	$exitval = ParseLatency($datafile);
    }
    else {
	$exitval = ParseBW($datafile);
    }
    $exitval = InsertLinkData()
	if ($exitval == 0 && !$impotent);
}
else {
    if (DownLoadURL($LATURL, $tempfile) == 0) {
	$exitval = ParseLatency($tempfile);
    }
227 228 229
    # don't do bw right now; the plab iperf logs seem to have disappeared.
    # this should be done with flexlab anyway.
    if (0 && !$exitval) {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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
	#
	# What a pain. Need to figure the current BW data set from the date.
	# We go back one week.
	#
	for (my $i = 6; $i >= 0; $i--) {
	    my $bwfile = POSIX::strftime("20%y-%m-%d.log.gz",
					 localtime(time() -
						   ($i * (24 * 60 * 60))));
    
	    unlink($tempfile);
	    if (DownLoadURL("$BWURL/$bwfile", "$tempfile.gz") == 0) {
		$exitval = system("gunzip $tempfile.gz");
		if (!$exitval) {
		    $exitval = ParseBW($tempfile);
		}
		last
		    if ($exitval);
	    }
	}
    }
    $exitval = InsertLinkData()
	if ($exitval == 0 && !$impotent);
}
print "=== plablinkdata done at " . `date`;

unlink($tempfile)
    if (-e $tempfile);
fatal("Failed to bring in plab link data")
    if ($exitval);
exit(0);

#
# Insert Link Data into the DB.
# 
sub InsertLinkData()
{
    foreach my $from_ip (keys(%linkdata)) {
	my $from_nodeid   = $linkdata{$from_ip}->{NODEID};
	my $from_iface    = $linkdata{$from_ip}->{IFACE};
	my $from_hostname = $linkdata{$from_ip}->{HOSTNAME};

	foreach my $to_ip (keys(%linkdata)) {
	    my $to_nodeid   = $linkdata{$to_ip}->{NODEID};
	    my $to_iface    = $linkdata{$to_ip}->{IFACE};
	    my $to_hostname = $linkdata{$to_ip}->{HOSTNAME};
	    my ($latency,$bandwidth);

	    next
		if ($from_ip eq $to_ip);

	    if (exists($linkdata{$from_ip}->{LATENCY}->{$to_nodeid})) {
		$latency = $linkdata{$from_ip}->{LATENCY}->{$to_nodeid};
	    }
	    
	    if (exists($linkdata{$from_ip}->{BW}->{$to_nodeid})) {
		$bandwidth = $linkdata{$from_ip}->{BW}->{$to_nodeid};
	    }

	    next
		if (! (defined($latency) || defined($bandwidth)));

	    if ($debug) {
		print "$from_nodeid $to_nodeid ";
		print "Latency: $latency "
		    if (defined($latency));
		print "BW: $bandwidth "
		    if (defined($bandwidth));
		print "\n";
	    }
	    my $update = "";
	    my $query  = "";
	    
	    $update .= "lossrate=0, ";
	    $update .= "start_time=$now,end_time=start_time ";
	    $update .= ",time=$latency "
		if (defined($latency));
306 307 308 309 310 311
	    if (defined($bandwidth)) {
		$update .= ",bandwidth=$bandwidth ";
	    }
	    else {
		$update .= ",bandwidth=0 ";
	    }
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

	    my $query_result =
		DBQueryFatal("update widearea_recent set ".
			     "$update ".
			     "where node_id1='$from_nodeid' and ".
			     "      iface1='$from_iface' and ".
			     "      node_id2='$to_nodeid' and ".
			     "      iface2='$to_iface'");
	    
	    if (!$query_result->affectedrows &&
		(defined($latency) && defined($bandwidth))) {
		DBQueryFatal("replace into widearea_recent set ".
			     "$update, ".
			     "node_id1='$from_nodeid', ".
			     "iface1='$from_iface', ".
			     "node_id2='$to_nodeid', ".
			     "iface2='$to_iface'");
	    }
	    if (($from_hostname eq $MAGICNODE) ||
		($to_hostname   eq $MAGICNODE)) {
		if ($from_hostname eq $MAGICNODE) {
		    $from_nodeid = TBDB_WIDEAREA_LOCALNODE;
		    $from_iface  = $LocalIface;
		}
		if ($to_hostname eq $MAGICNODE) {
		    $to_nodeid = TBDB_WIDEAREA_LOCALNODE;
		    $to_iface  = $LocalIface;
		}
		$query_result =
		    DBQueryFatal("update widearea_recent set ".
				 "$update ".
				 "where node_id1='$from_nodeid' and ".
				 "      iface1='$from_iface' and ".
				 "      node_id2='$to_nodeid' and ".
				 "      iface2='$to_iface'");
	    
		if (!$query_result->affectedrows &&
		    (defined($latency) && defined($bandwidth))) {
		    DBQueryFatal("replace into widearea_recent set ".
				 "$update, ".
				 "node_id1='$from_nodeid', ".
				 "iface1='$from_iface', ".
				 "node_id2='$to_nodeid', ".
				 "iface2='$to_iface'");
		}
	    }
	}
    }
}

#
# Parse a latency data file.
#
sub ParseLatency($)
{
    my ($file) = @_;
    my ($timestamp, $pingcount);
    my @nodemap = (); # Map index in latency tables 

    if (!open(LAT, $file)) {
	print STDERR "Could not open $file: $!\n";
	return -1;
    }

    #
    # Line 1: The date/time of the data.
    #
    $_ = <LAT>;
    goto nosync
	if (!defined($_));

    if ($_ =~ /^(\d*):(\d*):(\d*) (\d*)\/(\d*)\/(\d*)$/) {
	$timestamp = mktime($3, $2, $1, $5, $4-1, 100 + ($6 - 2000));
	print STDERR
	    "Timestamp is $timestamp: " . POSIX::ctime($timestamp)
		if ($debug);
    }
    else {
	goto nosync;
    }

    #
    # Line 2 is the number of pings in the sample. Not sure what to do
    # with this number?
    # 
    $_ = <LAT>;
    goto nosync
	if (!defined($_));

    if ($_ =~ /^(\d*)$/) {
	$pingcount = $1;
	print STDERR "$pingcount pings in sample size\n"
	    if ($debug);
    }
    else {
	goto nosync;
    }

    #
    # Line 3 is the list of the N PlanetLab nodes for which this file
    # contains information.
    #
    $_ = <LAT>;
    goto nosync
	if (!defined($_));

    my @iplist = split(' ', $_);
    goto nosync
	if (! scalar(@iplist));

    for (my $i = 0; $i < scalar(@iplist); $i++) {
	my $ip = $iplist[$i];
	
425 426
	# all nodes are now listed by hostname, so do lookup if they aren't
	# IPs.
427 428 429 430 431 432 433
	if ($ip =~ /^(\d*\.\d*\.\d*\.\d*)$/) {
	    if (exists($linkdata{$1})) {
		$linkdata{$1}->{INDEX} = $i;
	    }
	    # Map index to the ip for later (its position in the lists).
	    $nodemap[$i] = $1;
	}
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
	elsif ($ip =~ /^([\w\d\-_\.]+)$/) {
	    if (exists($dbhostipmap{$ip})) {
		my $rip = $dbhostipmap{$ip};
		if (exists($linkdata{$rip})) {
		    $linkdata{$rip}->{INDEX} = $i;
		}
		$nodemap[$i] = $rip;
	    }
	    else {
		my $rip = gethostbyname($1);
		if (defined($rip)) {
		    if (exists($linkdata{$rip})) {
			$linkdata{$rip}->{INDEX} = $i;
		    }
		    $nodemap[$i] = $rip;
		}
		else {
		    print STDERR "Could not resolve host '$ip'!\n";
		    goto nosync;
		}
	    }
	}
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
	else {
	    goto nosync;
	}
    }
    print STDERR scalar(@iplist) . " nodes in sample\n"
	if ($debug);

    #
    # Lines 4 through (N+3): The pairwise ping times themselves, as an
    # NxN matrix of min ping/av. ping/max ping tuples. For example,
    # line i includes the pairwise ping times for the node (i-4) as
    # listed in the array on Line 3. The jth entry on line i contains
    # the ping tuple for node (i-4) to node j.
    #
    my $i = 0;

    while (<LAT>) {
	my $from_ip      = $nodemap[$i];
	my $from_nodeid;

	#
	# If this IP is not known to us, skip
	#
	if (!exists($linkdata{$from_ip})) {
	    print STDERR "Skipping line $i ($from_ip); not in DB!\n"
		if ($debug);
	    goto skip;
	}
	$from_nodeid = $linkdata{$from_ip}->{NODEID};	
	
	#
	# If the centralized controller receives no data from node x
	# for a given time period, node x's line will read:
	#     *** no data received for node.x.ip.address ***
	# Note that in the most recently collected data sets, this may
	# appear because node x was just slow or unsynchronized in
	# sending its data back; this line can be replaced with actual
	# data at any point in the future, if node x ever sends it in.
	#
495 496
	if ($_ =~ /^\*\*\* no data received for ([\d\.]*) \*\*\*$/ 
	    || $_ =~ /^\*\*\* no data received for ([\w\d\-_\.]+) \*\*\*$/) {
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 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 590 591 592 593 594 595 596 597 598 599 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 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
	    print STDERR "No data for $1 ($from_nodeid)\n"
		if ($debug);
	    goto skip;
	}

	my @pinglist = split(' ', $_);
	goto nosync
	    if (! scalar(@pinglist));
	goto nosync
	    if (scalar(@pinglist) != scalar(@iplist));

	#
	# Go through the list.
	# 
	for (my $j = 0; $j < scalar(@pinglist); $j++) {
	    my $to_ip     = $nodemap[$j];
	    
	    #
	    # The ping time to itself is actually included! We do not put
	    # that into the DB at this time.
	    #
	    next
		if ($i == $j);

	    #
	    # Skip nodes we do not know about.
	    #
	    next
		if (!exists($linkdata{$to_ip}));

	    my $to_nodeid = $linkdata{$to_ip}->{NODEID};	    
	    my $data      = $pinglist[$j];

	    #
	    # If the pings failed, or if the node sent back no data,
	    # there will be a *** ... *** entry. Skip it for now.
	    #
	    next
		if ($data =~ /^\*\*\*.*\*\*\*/);

	    # Actual ping data.
	    my ($min,$avg,$max) = split('/', $data);

	    $linkdata{$from_ip}->{LATENCY}->{$to_nodeid} = $avg / 1000.0;
	    print STDERR "$from_nodeid --> $to_nodeid: $avg\n"
		if ($debug > 2);
	}
     skip:
	$i++;
    }
    close(LAT);
    return 0;
    
  nosync:
    close(LAT);
    print STDERR "Out of sync parsing latency file.\n";
    print STDERR "Current line: $_\n"
	if (defined($_));
    return 1;
}

sub ParseBW($)
{
    my ($file) = @_;

    if (!open(BW, $file)) {
	print STDERR "Could not open $file: $!\n";
	return -1;
    }

    #
    # Very simple format:
    #
    # yyyy-mm-dd HH:MM:SS,fromhost,tohost,bitspersecond
    #
    # Ignore the timestamps for now since they have no relation to
    # the latency data. 
    #
    while (<BW>) {
	my ($daydate,$fromhost,$tohost,$bits) = split(',', $_);

	if (! (defined($daydate) && defined($fromhost) &&
	       defined($tohost) && defined($bits))) {
	    goto nosync;
	}

	if ($daydate =~ /^(\d*)\-(\d*)\-(\d*) (\d*):(\d*):(\d*)$/) {
	    $timestamp = mktime($6, $5, $4, $3, $2-1, 100 + ($1 - 2000));
	    print STDERR
		"Timestamp is $timestamp: " . POSIX::ctime($timestamp)
		    if ($debug > 2);
	}
	else {
	    goto nosync;
	}
	if ($bits =~ /^(\d*)$/) {
	    $bits = $1;
	}
	else {
	    goto nosync;
	}

	next
	    if (!exists($hostmap{$fromhost}) ||
		!exists($hostmap{$tohost}));

	my $from_ip     = $hostmap{$fromhost};
	my $to_ip       = $hostmap{$tohost};
	my $from_nodeid = $linkdata{$from_ip}->{NODEID};
	my $to_nodeid   = $linkdata{$to_ip}->{NODEID};

	print STDERR "BW: $from_nodeid --> $to_nodeid: $bits\n"
	    if ($debug);

	$linkdata{$from_ip}->{BW}->{$to_nodeid} = $bits / 1000.0;
    }
    close(BW);
    return 0;
    
  nosync:
    close(BW);
    print STDERR "Out of sync parsing bandwidth file.\n";
    print STDERR "Current line: $_\n"
	if (defined($_));
    return 1;
}

#
# Download the datafile from the plab site.
#
sub DownLoadURL($$)
{
    my ($url, $tempfile) = @_;

    print STDERR "Downloading $url to $tempfile ...\n"
	if (1);
    
    #
    # Must prevent hangs ...
    #
    my $syspid = fork();

    if ($syspid) {
	local $SIG{ALRM} = sub { kill("TERM", $syspid); };
	alarm 120;
	waitpid($syspid, 0);
	alarm 0;
	my $exitcode = $?;

	warn("*** Timed out downloading link data from web site!\n")
	    if ($exitcode == 15);
	    
	warn("*** Could not download link data from web site!\n")
	    if ($exitcode);

	return($exitcode >> 8);
    }
    else {
	exec("/usr/local/bin/wget -q -O $tempfile $url");
	exit(1);
    }
}

sub fatal {
    my $msg = $_[0];

    if ($daemon) {
	SENDMAIL($TBOPS, "plablinkdata failed",
		 "$msg\n\n".
		 "Please see $logfile for more info.\n");
    }
    die($msg);
}

#
# Become a daemon.
# 
sub daemonize()
{
    my $mypid = fork();
    if ($mypid) {
	exit(0);
    }

    #
    # We have to disconnect from the caller by redirecting both STDIN and
    # STDOUT away from the pipe. Otherwise the caller will continue to wait
    # even though the parent has exited. 
    #
    open(STDIN, "< /dev/null") or
	die("opening /dev/null for STDIN: $!");

    #
    # Open the batch log and start writing to it. 
    #
    open(STDERR, ">> $logfile") or die("opening $logfile for STDERR: $!");
    open(STDOUT, ">> $logfile") or die("opening $logfile for STDOUT: $!");

    #
    # Turn off line buffering on output
    #
    STDOUT->autoflush(1);
    STDERR->autoflush(1);

    return 0;
}