init-elabnodes.pl 20.8 KB
Newer Older
1
#!/usr/bin/perl
Mike Hibler's avatar
Mike Hibler committed
2
#
3
# Copyright (c) 2006, 2007 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/>.
# 
# }}}
Mike Hibler's avatar
Mike Hibler committed
23 24
#

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#
# Based on pairwise characteristics of planet-* nodes (real planetlab nodes)
# in a pelab experiment, set the delay characteristics for the corresponding
# elab-* nodes.
#
# Elab nodes are in a "cloud" allowing you to set node-to-node characteristics
# for all nodes within the cloud.  To do this for node N to node M:
#
#	tevc -e pid/eid now elabc-elab-N MODIFY DEST=<elab-M-elabc IP> \
#		[ BANDWIDTH=<kbits/sec> ] [ DELAY=<ms> ] [ PLR=<prob> ]
#
# The characteristics are applied to the node->LAN pipe for node N.
# Since this is one-way, you will have to apply the usual tricks to
# convert round-trip delays and PLR.
#

my $TEVC = "/usr/testbed/bin/tevc";
my $NLIST = "/usr/testbed/bin/node_list";
43
my $pprefix = "planet-";
44
my $eprefix = "elab-";
45

46 47 48 49
# XXX Need to configure this stuff!
use lib '/usr/testbed/lib';
use libtbdb;
use Socket;
Mike Hibler's avatar
Mike Hibler committed
50
use Getopt::Std;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
use Class::Struct;
use strict;

my ($initvalLat, $initvalBw);
################
# Define a structure to hold the values used in initial condition reporting
struct( initvalres => {
    srcnode => '$',
    dstnode => '$',
    ave_exp => '$',
    numSamples => '$',
    numErrValSamples => '$',
    numLastSeqErr =>'$',
    tstampLastSample => '$' } );
#'################

Mike Hibler's avatar
Mike Hibler committed
67 68 69 70 71 72
#
# Every source host has a list of <dest-IP,bw,delay,plr> tuples, one
# element per possible destination
#
my %shapeinfo;

73
my $showonly = 0;
74
my $starttime = 0;
75
my $outfile;
76
my $doelabaddrs = 1;
77
my $remote = 0;
78
my $cloudonly = 0;
79
my $lanonly = 0;
80

Mike Hibler's avatar
Mike Hibler committed
81
# Default values.  Note: delay and PLR are round trip values.
Mike Hibler's avatar
Mike Hibler committed
82
my $DEF_BW = 10001;	# Kbits/sec
83 84 85
my $DEF_DEL = 0;	# ms
my $DEF_PLR = 0.0;	# prob.

86
my $PWDFILE = "/usr/testbed/etc/pelabdb.pwd";
87
my $DBHOST  = "localhost";
88 89 90
my $DBNAME  = "pelab";
my $DBUSER  = "pelab";

Mike Hibler's avatar
Mike Hibler committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
# map a "plabXXX" pname to a DB site index
my %site_mapping = ();

# map a "plabXXX" pname to its IP address
my %ip_mapping   = ();

# map an Emulab "planet-N" vname to a pname
my %node_mapping = ();

# map an Emulab vname to its vname index (e.g., "planet-3" -> "3")
my %ix_mapping   = ();

# map an Emulab vname to its inet connectivity (e.g. "planet-3" -> "inet2")
my %inet_mapping = ();

106 107
my $now     = time();

Mike Hibler's avatar
Mike Hibler committed
108 109 110 111
#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
112
my %options = ();
113
if (! getopts("S:no:rCLd", \%options)) {
Mike Hibler's avatar
Mike Hibler committed
114 115 116 117 118
    usage();
}
if (defined($options{"n"})) {
    $showonly = 1;
}
119 120 121
if (defined($options{"o"})) {
    $outfile = $options{"o"};
}
122
if (defined($options{"r"})) {
Mike Hibler's avatar
Mike Hibler committed
123
    $remote = 1;
124 125 126
    $PWDFILE = "/local/pelab/pelabdb.pwd";
    $DBHOST = "users.emulab.net";
}
127
if (defined($options{"d"})) {
128
    $DBHOST = "utah.datapository.net";
129 130 131 132
    $DBNAME = "nodesamples";
    $DBUSER = "flexlabdata";
    $PWDFILE = "";
}
133 134 135
if (defined($options{"C"})) {
    $cloudonly = 1;
}
136 137 138
if (defined($options{"L"})) {
    $lanonly = 1;
}
139 140 141 142 143 144 145 146 147
if (defined($options{"S"})) {
    my $high = time();
    my $low = $high - (23 * 60 * 60); # XXX

    $starttime = $options{"S"};
    if ($starttime && ($starttime < $low || $starttime > $high)) {
	die("Bogus timestamp $starttime, should be in [$low - $high]\n");
    }
}
Mike Hibler's avatar
Mike Hibler committed
148 149 150 151 152 153
if (@ARGV != 2) {
    print STDERR "usage: init-elabnodes pid eid\n";
    exit(1);
}
my ($pid,$eid) = @ARGV;

154
# Get DB password and connect.
155 156 157 158 159 160 161 162 163 164 165
my $DBPWD;
if ($PWDFILE) {
    $DBPWD = `cat $PWDFILE`;
    if ($DBPWD =~ /^([\w]*)\s([\w]*)$/) {
        $DBPWD = $1;
    }
    else{
        fatal("Bad chars in password!");
    }
} else {
    $DBPWD = "";
166
}
167
TBDBConnect($DBNAME, $DBUSER, $DBPWD, $DBHOST) == 0
168 169
    or die("Could not connect to pelab database!\n");

170
#
Mike Hibler's avatar
Mike Hibler committed
171 172
# Figure out how many pairs there are, and for each, who the
# corresponding planetlab node is.
173
#
174 175 176
my @nodelist;
if ($remote) {
    @nodelist = split('\s+', `cat /proj/$pid/exp/$eid/tmp/node_list`);
Mike Hibler's avatar
Mike Hibler committed
177
    chomp(@nodelist);
178
} else {
Mike Hibler's avatar
Mike Hibler committed
179 180 181 182 183 184 185 186 187 188
    require libxmlrpc;

    # not needed unless we change the default config
    #libxmlrpc::Config();

    my $rval = libxmlrpc::CallMethod("experiment", "info",
				     { "proj" => "$pid",
				       "exp"  => "$eid",
				       "aspect" => "mapping"});
    if (defined($rval)) {
189 190
	my $gotplab = 0;

Mike Hibler's avatar
Mike Hibler committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
	#
	# Generate vname=pnode pairs.
	# Also record inet/inet2/intl status of plab nodes
	#
	foreach my $node (keys %$rval) {
	    my $str = "$node=" . $rval->{$node}{"pnode"};
	    push(@nodelist, $str);
	    if ($node =~ /^$pprefix/) {
		my $auxtype = $rval->{$node}{"auxtype"};
		if ($auxtype =~ /inet2/) {
		    $auxtype = "inet2";
		} else {
		    $auxtype = "inet";
		}
		$inet_mapping{$node} = $auxtype;
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
		$gotplab++;
	    }
	}

	#
	# No planetlab machines in the experiment.  We might be doing
	# emulation only, so look for a list of plab nodes in the
	# user environment.
	#
	if ($gotplab == 0) {
	    my %plist;

	    my $rval = libxmlrpc::CallMethod("experiment", "metadata",
					     { "proj" => "$pid",
					       "exp"  => "$eid" });
	    if (defined($rval)) {
		my $aref = $rval->{"user_environment"};
		foreach my $env (@$aref) {
		    if ($env->{"name"} =~ /pelab-elab-(\d+)-mapping/) {
			my $node = "planet-$1";
			$plist{$node} = $env->{"value"};
			my $str = "$node=" . $plist{$node};
			push(@nodelist, $str);
		    }
		}

232 233 234
		# build a node string to use in the node.getlist call
		my $nodestr = join(',', values(%plist));

235 236 237
		# sslxmlrpc_client.py -m node getlist class=pcplabphys
		my $rval = libxmlrpc::CallMethod("node", "getlist",
						 { "proj" => "$pid",
238
						   "nodes" => "$nodestr",
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
						   "class"  => "pcplabphys" });
		if (defined($rval)) {
		    while (my ($node,$pnode) = each(%plist)) {
			my $auxtype;
			if (defined($rval->{$pnode})) {
			    $auxtype = $rval->{$pnode}{"auxtypes"};
			    if ($auxtype =~ /inet2/) {
				$auxtype = "inet2";
			    } else {
				$auxtype = "inet";
			    }
			} else {
			    $auxtype = "inet";
			}
			$inet_mapping{$node} = $auxtype;
			$gotplab++;
		    }
		}
Mike Hibler's avatar
Mike Hibler committed
257 258 259
	    }
	}
    }
260
}
Mike Hibler's avatar
Mike Hibler committed
261

262 263
print "NODELIST:\n@nodelist\n"
    if (!$outfile);
Mike Hibler's avatar
Mike Hibler committed
264

265 266 267 268 269
my $nnodes = grep(/^${pprefix}/, @nodelist);
if ($nnodes == 0) {
    print STDERR "No planetlab nodes in $pid/$eid?!\n";
    exit(1);
}
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284
foreach my $mapping (@nodelist) {
    if ($mapping =~ /^(${pprefix}[\d]+)=([\w]*)$/) {
	my $vnode = $1;
	my $pnode = $2;

	# Grab the site index.
	my $query_result =
	    DBQueryFatal("select site_idx from site_mapping ".
			 "where node_id='$pnode'");

	if (! $query_result->numrows) {
	    die("Could not map $pnode to its site index!\n");
	}
	my ($site_index) = $query_result->fetchrow_array();
285
	
286 287
	print "Mapping $vnode to $pnode\n"
	    if (!$outfile);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

	$node_mapping{$vnode} = $pnode;
	$site_mapping{$pnode} = $site_index;

	if ($vnode =~ /^${pprefix}(\d+)/) {
	    $ix_mapping{$vnode} = $1;
	}
	else {
	    die("Could not map $vnode to its index!\n");
	}

	# Grab the IP address and save.
	my (undef,undef,undef,undef,@ips) = gethostbyname("$pnode");

	if (!@ips) {
	    die("Could not map $pnode to its ipaddr\n");
	}
	$ip_mapping{$pnode} = inet_ntoa($ips[0]);
    }
}

309 310 311 312 313 314 315
my $msg = "Intializing conditions from time ";
if ($starttime) {
    $msg .= "$starttime (now - " . ($now - $starttime) . " seconds)\n";
} else {
    $msg .= $now . " (now)\n";
    $starttime = $now;
}
316 317
print($msg)
    if (!defined($outfile));
318

319 320 321
#
# Get planetlab info for each planetlab node...
#
322 323
foreach my $vnode (keys(%node_mapping)) {
    get_plabinfo($vnode);
324 325 326
}

#
327
# ...and send events to set the characteristics or output the info to a file.
328
#
329 330 331
if (!$showonly) {
    if (defined($outfile)) {
	write_info($outfile);
332 333
    } elsif ($cloudonly) {
	send_cloud_events();
334 335
    } elsif ($lanonly) {
	send_hybrid_events(1);
336
    } else {
337
	send_hybrid_events(0);
338 339
    }
}
340 341 342

exit(0);

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
sub write_info($)
{
    my $file = shift;
    my $OUT;

    if ($outfile ne "-") {
	open(INFO, ">$file") or die("Cannot open $file");
	$OUT = *INFO;
    } else {
	$OUT = *STDOUT;
    }

    foreach my $src (keys %shapeinfo) {
	foreach my $rec (@{$shapeinfo{$src}}) {
	    my ($dst,$bw,$del,$plr) = @{$rec};

	    # XXX src is an "elab-N" string, dst is a "10.0.0.N" address
360 361 362 363 364 365 366 367
	    if ($doelabaddrs) {
		$src =~ s/$eprefix/10.0.0./;
	    } else {
		$src =~ s/$eprefix/$pprefix/;
		$src = $ip_mapping{$node_mapping{$src}};
		$dst =~ s/10\.0\.0\./$pprefix/;
		$dst = $ip_mapping{$node_mapping{$dst}};
	    }
368 369 370 371 372 373 374 375 376 377 378

	    #
	    # Jon says:
	    #   List of lines, where each line is of the format:
	    #    <source-ip> <dest-ip> <delay> <bandwidth>
	    #   Where source and dest ip addresses are in x.x.x.x format,
	    #   and delay and bandwidth are integral values in milliseconds
	    #   and kilobits per second respectively.
	    # Mike adds:
	    #   include a PLR place holder after bandwidth in the form
	    #   of a probability N.NNNN
379 380 381
	    # Kevin has done something similar but with order:
	    #    <source-ip> <dest-ip> <bandwidth> <delay> <loss>
	    # so that is now the order.
382
	    #
383
	    printf $OUT "%s %s %d %d %6.4f\n", $src, $dst,
384
	           $bw + 0.5, $del + 0.5, $plr;
385 386 387 388
	}
    }
}

Mike Hibler's avatar
Mike Hibler committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
sub plab_type($)
{
    my ($node) = (@_);
    my $ix;
    my $t;

    if ($node =~ /^$pprefix(\d+)/) {
	$ix = $1;
    } elsif ($node =~ /^$eprefix(\d+)/) {
	$ix = $1;
    } elsif ($node =~ /10\.0\.0\.(\d+)/) {
	$ix = $1;
    }

    $t = $inet_mapping{"$pprefix$ix"};
    if (!defined($t)) {
	warn("*** Could not determine type of $node ($pprefix$ix)");
	$t = "inet";
    }
    return $t;
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
#
# Set up pipes in the "old school" style of one pipe per src-dst pair.
#
sub send_cloud_events()
{
    foreach my $src (keys %shapeinfo) {
  	foreach my $rec (@{$shapeinfo{$src}}) {
  	    my ($dst,$bw,$del,$plr) = @{$rec};
 	    my $cmd = "$TEVC -e $pid/$eid now elabc-$src MODIFY ".
 		"DEST=$dst BANDWIDTH=$bw DELAY=$del PLR=$plr";
 	    print "elabc-$src: DEST=$dst BANDWIDTH=$bw DELAY=$del PLR=$plr...";
  	    if (system("$cmd") != 0) {
  		print "[FAILED]\n";
  	    } else {
		print "[OK]\n";
	    }
	}
    }
}

Mike Hibler's avatar
Mike Hibler committed
431 432 433 434 435 436 437 438 439 440 441 442 443
#
# How we shape the links depends on whether the nodes involved are Internet 2
# (I2) or commodity internet (I1) as follows:
#
# 1. Delay (and eventually PLR) are per-node pair as always
#
# 2. If source is an I1 node, outgoing bandwidth to all nodes is shared
#    and equal to the max BW measured to any one of the nodes.
#
# 3. If source is an I2 node, per-node pair pipes are used for all I2
#    destinations.  For I1 destinations, the computation is as in #2,
#    the max per-path value for any of them.
#
444
sub send_hybrid_events($)
445
{
446
    my ($I1only) = @_;
Mike Hibler's avatar
Mike Hibler committed
447 448
    my %dstmap;

449
    foreach my $src (keys %shapeinfo) {
Mike Hibler's avatar
Mike Hibler committed
450 451 452 453 454 455
	my $stype = plab_type($src);
	my $gotinet = 0;
	my $maxbw = 0;

	#
	# Loop over all destinations forming I2 pipes and keeping track
456 457
	# of the max BW to all I1 nodes.  If I1only is non-zero, we treat
	# everything as I1 (i.e., shared BW to all destinations).
Mike Hibler's avatar
Mike Hibler committed
458 459
	#
	my @cmds;
460 461
	foreach my $rec (@{$shapeinfo{$src}}) {
	    my ($dst,$bw,$del,$plr) = @{$rec};
Mike Hibler's avatar
Mike Hibler committed
462 463 464 465 466 467 468

	    if (!defined($dstmap{$dst})) {
		$dstmap{$dst} = plab_type($dst);
	    }
	    my $dtype = $dstmap{$dst};

	    my $cmd = "DEST=$dst DELAY=$del PLR=$plr";
469
	    if ($I1only || $stype eq "inet" || $dtype eq "inet") {
Mike Hibler's avatar
Mike Hibler committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		$gotinet = 1;
		if ($bw != $DEF_BW && $bw > $maxbw) {
		    $maxbw = $bw;
		}
	    } else {
		$cmd .= " BANDWIDTH=$bw";
	    }
	    push(@cmds, $cmd);
	}

	#
	# Setup the shared BW pipe
	#
	if ($gotinet) {
	    $maxbw = $DEF_BW if ($maxbw == 0);
	    my $cmd = "BANDWIDTH=$maxbw";
	    push(@cmds, $cmd);
	}

	foreach my $cmd (@cmds) {
	    print "elabc-$src ($stype): $cmd...";
	    $cmd = "$TEVC -e $pid/$eid now elabc-$src MODIFY " . $cmd;
492
	    if (system("$cmd") != 0) {
493
		print "[FAILED]\n";
494
	    } else {
495
		print "[OK]\n";
496 497 498 499 500 501
	    }
	}
    }
}

#
502
# Grab data from DB.
503 504 505
#
sub get_plabinfo($)
{
506 507
    my ($srcvnode) = @_;
    my $srcix = $ix_mapping{$srcvnode};
508

509
    @{$shapeinfo{"elab-$srcix"}} = ();
510

511 512 513 514
    foreach my $dstvnode (keys(%node_mapping)) {
	next
	    if ($srcvnode eq $dstvnode);

515 516 517 518 519 520 521 522 523 524 525 526
	#Only need these two for error messages. get_pathInitCond finds them
        # itself.
	my $dst       = $ip_mapping{$node_mapping{$dstvnode}};
	my $src_site  = $site_mapping{$node_mapping{$srcvnode}};
	my $dst_site  = $site_mapping{$node_mapping{$dstvnode}};
	my $dstix  = $ix_mapping{$dstvnode};

	# Get initial conditions
	($initvalLat, $initvalBw) = 
	     get_pathInitCond( $node_mapping{$srcvnode}, 
			       $node_mapping{$dstvnode},
			       24, 0.8 );
527
	bless $initvalLat, "initvalres";
528
#       print "initvalLat=$initvalLat\n";
529
	bless $initvalBw, "initvalres";
530
#       print "initvalBw=$initvalBw\n";
531 532 533 534 535 536
=pod
        print "\nLATENCY\n";
	printInitValResStruct($initvalLat);
	print "\nBW\n";
	printInitValResStruct($initvalBw);
=cut
537 538 539 540 541 542 543 544 545
	#TODO: is this print statement wanted here? Should it be conditional
        #      on available path measurements, like in the original?
	print "elab-$srcix -> elab-$dstix (on behalf of $dst):\n"
	    if ($showonly);

	my ($del,$plr,$bw) = ($initvalLat->ave_exp,
			   undef,  #TODO!!! LOSS RATE!!!
			   $initvalBw->ave_exp);

546 547
#	print "INIT COND: ($del,$plr,$bw)\n";

548 549 550 551 552 553 554 555 556 557
	# handle a path with no available measurements
	if($initvalLat->numSamples == $initvalLat->numErrValSamples){
	    $del = $DEF_DEL;
	    warn("*** Could not get latency ".
		 "$srcvnode ($src_site) --> $dstvnode ($dst_site)\n".
		 "    defaulting to ".
		 "${DEF_DEL}ms\n" );
	}
	if(!defined($plr)){
	    $plr = $DEF_PLR;
558 559
	    # do not complain right now since we do not collect this
	    if (0) {
560 561 562 563
	    warn("*** Could not get lossrate ".
		 "$srcvnode ($src_site) --> $dstvnode ($dst_site)\n".
		 "    defaulting to ".
		 "${DEF_PLR}plr\n" );
564
	    }
565
	}
566
	if($initvalBw->numSamples == $initvalBw->numErrValSamples){	 
567 568 569 570 571 572 573 574 575 576 577
	    $bw = $DEF_BW;
	    warn("*** Could not get bandwidth ".
		 "$srcvnode ($src_site) --> $dstvnode ($dst_site)\n".
		 "    defaulting to ".
		 "${DEF_BW}bps\n" );
	}
	    



=pod
578 579 580 581 582 583 584
	my $dst       = $ip_mapping{$node_mapping{$dstvnode}};
	my $src_site  = $site_mapping{$node_mapping{$srcvnode}};
	my $dst_site  = $site_mapping{$node_mapping{$dstvnode}};

	my $query_result =
	    DBQueryFatal("select latency,loss,bw from pair_data ".
			 "where srcsite_idx='$src_site' and ".
585 586
			 "      dstsite_idx='$dst_site' and ".
			 "      unixstamp <= $starttime ".
587
			 "order by unixstamp desc limit 5");
588 589

	if (!$query_result->numrows) {
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	    warn("*** Could not get pair data for ".
		 "$srcvnode ($src_site) --> $dstvnode ($dst_site)\n".
		 "    defaulting to ".
		 "${DEF_BW}bps, ${DEF_DEL}ms, ${DEF_PLR}plr\n");
	    ($del,$plr,$bw) = ($DEF_DEL, $DEF_PLR, $DEF_BW);
	} else {
	    my @vals;

	    print "elab-$srcix -> elab-$dstix (on behalf of $dst):\n"
		if ($showonly);
	    while (($del,$plr,$bw) = $query_result->fetchrow_array()) {
		print "  ($del, $plr, $bw)\n"
		    if ($showonly);
		push(@vals, [ $del, $plr, $bw ]);
	    }

	    #
	    # XXX This needs to be modified!
	    #
	    ($del,$plr,$bw) = @{$vals[0]};
610 611 612 613
	    $del = $DEF_DEL
		if (!defined($del));
	    $plr = $DEF_PLR
		if (!defined($plr));
614
	    $bw = $DEF_BW
615
		if ($bw == 0);	# undef or zero--zero BW is not very useful
Mike Hibler's avatar
Mike Hibler committed
616 617

	    $del = int($del / 2);
618
	}
619
=cut
620

621 622 623
	printf("elab-%d -> elab-%d: real=%s, bw=%d, del=%d, plr=%4.2f\n",
	       $srcix, $dstix, $dst, int($bw + 0.5), int($del + 0.5), $plr)
	    if (!$outfile);
624

Mike Hibler's avatar
Mike Hibler committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638
	#
	# Convert as necessary:
	# * recorded delay is round-trip, so divide by 2 for one-way
	# * BW is based on TCP payload, so compensate for dummynet's
	#   use of ethernet.  Assuming full-sized ethernet packets
	#   each with 54 bytes of overhead (14 + 20 + 20) that dummynet
	#   will count, that is 1514 bytes for every 1460 that iperf
	#   counts.  So we adjust by a factor of 1.036.
	#
	$del = int($del/2 + 0.5);
	if ($bw != $DEF_BW) {
	    $bw = int($bw * 1.036 + 0.5);
	}

639 640
	# XXX need to lookup "elab-$dstix"
	$dst = "10.0.0.$dstix";
641 642
	
	push(@{$shapeinfo{"elab-$srcix"}}, [ $dst, $bw, $del, $plr ]);
643 644
    }
}
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659




######################################################################
# Grab data from DB to create an initial condition structure
#
#  Notes:
#    + Data used in init cond is from any node at the sites containing
#      the given nodes.
#
sub get_pathInitCond($$$;$)
{
    my ($srcnode, $dstnode, $pasthours, $expAlpha) = @_;
    if( !defined $expAlpha) { $expAlpha = 0.6; }  #default alpha value
660 661 662
    my $lasttime = $starttime;
    #my $firsttime = $lasttime - (60*60*24);
    my $firsttime = $lasttime - (60*60*$pasthours);
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    my $srcsite_idx    = $site_mapping{$srcnode};
    my $dstsite_idx    = $site_mapping{$dstnode};

    my $initvalLat = new initvalres;
    my $initvalBw = new initvalres;

    my @latsamples = ();
    my @bwsamples = ();
    my @latsamples_noerr;
    my @bwsamples_noerr;

    #
    # retreive data for last 24 hours for the given path and
    # populate result structures
    #
    my $sth = DBQuery(
		      "SELECT * ".
		      "FROM pair_data WHERE ".
		      "srcsite_idx = $srcsite_idx and ".
		      "dstsite_idx = $dstsite_idx and ".
		      "(latency IS NOT NULL or bw IS NOT NULL) and ".
684 685
		      "unixstamp > $firsttime and ".
		      "unixstamp <= $lasttime ".
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
		      "order by unixstamp asc ".
		      ";" );
    while( my $hr = $sth->fetchrow_hashref() ){
	my %row = %{$hr};
	if ( defined $row{latency} ){
	    push @latsamples, $row{latency};
	    $initvalLat->tstampLastSample($row{unixstamp});
	    $initvalLat->srcnode($srcnode) if !defined($initvalLat->srcnode);
	    $initvalLat->dstnode($dstnode) if !defined($initvalLat->dstnode);
	}
	if ( defined $row{bw} ){
	    push @bwsamples, $row{bw} ;
	    $initvalBw->tstampLastSample($row{unixstamp});
	    $initvalBw->srcnode($srcnode) if !defined($initvalBw->srcnode);
	    $initvalBw->dstnode($dstnode) if !defined($initvalBw->dstnode);
	}
    }
    #do another query in reverse path if given one doesn't have latency data
    if( scalar @latsamples == 0 ){
	my $sth = DBQuery(
		      "SELECT latency ".
		      "FROM pair_data WHERE ".
		      "srcsite_idx = $dstsite_idx and ".
		      "dstsite_idx = $srcsite_idx and ".
		      "(latency IS NOT NULL) and ".
711 712
		      "unixstamp > $firsttime and ".
		      "unixstamp <= $lasttime ".
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 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
		      "order by unixstamp asc ".
		      ";" );
	while( my $hr = $sth->fetchrow_hashref() ){
	    my %row = %{$hr};
	    if ( defined $row{latency} ){
		push @latsamples, $row{latency};
		$initvalLat->tstampLastSample($row{unixstamp});
		$initvalLat->srcnode($dstnode) 
		    if !defined($initvalLat->srcnode);
		$initvalLat->dstnode($srcnode) 
		    if !defined($initvalLat->dstnode);
	    }
	}
    }
#    print "latsamples = @latsamples\n";
#    print "bwsamples = @bwsamples\n";

    $initvalLat->numSamples(scalar @latsamples);
    $initvalBw->numSamples(scalar @bwsamples);

    
    # Find err vals

    #do for latency
    my $flag_errseriesEnd = 0;
    my $numErrs = 0;
    my $numSeriesErr = 0;
    for( my $i=$#latsamples; $i >=0; $i-- ){
	if( $latsamples[$i] < 0 ){
	    $numErrs++;
	    if( $flag_errseriesEnd == 0 ){
		$numSeriesErr++;
	    }
	}else{
	    $flag_errseriesEnd = 1;
	    unshift @latsamples_noerr, $latsamples[$i];
	}
    }
    $initvalLat->numLastSeqErr($numSeriesErr);
    $initvalLat->numErrValSamples($numErrs);
    #now for bw
    $flag_errseriesEnd = 0;
    $numErrs = 0;
    $numSeriesErr = 0;
    for( my $i=$#bwsamples; $i >=0; $i-- ){
	if( $bwsamples[$i] < 0 ){
	    $numErrs++;
	    if( $flag_errseriesEnd == 0 ){
		$numSeriesErr++;
	    }
	}else{
	    $flag_errseriesEnd = 1;
	    unshift @bwsamples_noerr, $bwsamples[$i];
	}
    }
    $initvalBw->numErrValSamples($numErrs);
    $initvalBw->numLastSeqErr($numSeriesErr);


    # Calculate Exponential average
    # TODO!! Change this called function such that the time between
    #        samples is factored into the weighting.
    $initvalLat->ave_exp( calcExpAve($expAlpha,\@latsamples_noerr) );
    $initvalBw->ave_exp( calcExpAve($expAlpha,\@bwsamples_noerr) );

=pod
    print "\nLatency\n@latsamples\n";
    printInitValResStruct($initvalLat);
    print "\nBW\n@bwsamples\n";
    printInitValResStruct($initvalBw);
=cut

785
    return ($initvalLat, $initvalBw);
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 813
}


sub printInitValResStruct($)
{
    my ($struct) = @_;

    print "printing InitValRes Structure\n";
    foreach my $var (keys %{$struct}){
	print "$var  =   \t".${$struct}{$var} ."\n" 
	    if defined ${$struct}{$var};
    }
}


sub calcExpAve($$\@)
{
    my ($alpha, $aref) = @_;
    my @values = @$aref;

    if( scalar(@values) == 0 ){ return 0; }

    my $lastAve = $values[0];  #start with first sample
    for( my $i=1; $i<@values; $i++ ){
	$lastAve = $alpha*$values[$i] + (1-$alpha)*$lastAve;
    }
    return $lastAve;
}