staticroutes.in 21.7 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3 4

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2004 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6 7 8
# All rights reserved.
#

9 10 11 12 13 14 15 16 17 18
use English;
use Getopt::Std;
use Socket;
use IO::Handle;     # thousands of lines just for autoflush :-(

#
# usage: staticroutes <pid> <eid>
#
sub usage()
{
19 20 21 22
    print("Usage: staticroutes [-n [-s|-l|-b]] [-d] [-m] [-f] [-t] <pid> <eid>".
	  "\n".
	  "       staticroutes -j [-n] [-f] [-d] <pid> <eid>\n".
	  "       Use -j to generate linkmap only and exit.\n".
23
	  "       Use -n to print routes, but leave the DB alone.\n".
24 25 26
	  "       Use -s (with -n) to print routes in NS format.\n".
	  "       Use -b (with -n) to print routes in Freebsd format.\n".
	  "       Use -l (with -n) to print routes in Linux format.\n".
27
	  "       Use -d to turn on debugging output.\n".
28
	  "       Use -m to turn on memory debugging output with top.\n".
29 30 31 32
	  "       Use -t to optimize network routes.\n".
	  "       Use -f to force route calculation; ignore 'static' flag.\n");
    exit(-1);
}
33
my  $optlist = "dnftslbmj";
34 35 36 37 38 39

#
# Configure variables
#
my $TB		= "@prefix@";
my $NETMASK	= "255.255.255.0";
40
my $EXPTNETMASK = "255.255.0.0";
41 42

my $debug       = 0;
43
my $memdebug    = 0;
44 45 46
my $routecalc   = "$TB/libexec/routecalc";
my $impotent    = 0;
my $force	= 0;
47 48
my $dolinkmap   = 0;
my $linkmapname = "linkmap";
49
my $optimize    = 1;
50
my $edgeoptimize= 0; # Turned off till netmask problem can be fixed
51
my $format      = "";
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

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

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 2) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
83 84 85
if (defined($options{"m"})) {
    $memdebug = 1;
}
86 87 88 89 90 91 92
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"f"})) {
    $force = 1;
}
if (defined($options{"t"})) {
93
    $optimize = 0;
94
}
95 96 97 98 99 100 101 102 103
if (defined($options{"s"})) {
    $format = "ns";
}
if (defined($options{"b"})) {
    $format = "bsd";
}
if (defined($options{"l"})) {
    $format = "suxs";
}
104 105 106
if (defined($options{"j"})) {
    $dolinkmap = 1;
}
107 108 109
if ($format && !$impotent) {
    usage();
}
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

my $pid = $ARGV[0];
my $eid = $ARGV[1];

#
# Untaint args.
#
if ($pid =~ /^([-\@\w]+)$/) {
    $pid = $1;
}
else {
    die("Bad data in pid: $pid.");
}
if ($eid =~ /^([-\@\w]+)$/) {
    $eid = $1;
}
else {
    die("Bad data in eid: $eid.");
}

#
# Get the list of nodes.
# 
my $query_result =
    DBQueryFatal("select vname,ips,routertype from virt_nodes ".
		 "where pid='$pid' and eid='$eid'");

if (!$query_result->numrows) {
    warn("*** $0:\n".
	 "    No nodes in experiment $pid/$eid!\n");
    exit(0);
}

# A Flag.
my $dostatic = 0;

# A map of ips for each node, indexed by vname:port. 
my %ips      = ();

# A map (and reverse map) of node (vname) to unique index.
my %map      = ();
my %rmap     = ();
my $index    = 0;

# A map of lans, where each is a list of the members, indexed by lan.
my %lans     = ();

157
# A reverse map (sorta). Map a pair of links back to the lan they belong to.
158 159
my %rlans    = ();

160
# The costs, indexed by lan. This is kinda bogus, but since the cost
161 162 163
# is the same for each member of a lan, no big deal.
my %costs    = ();

164 165 166
# Ditto for masks. Need to combine all this to save space.
my %masks    = ();

167 168 169 170 171 172
# Number of links per node, indexed by node (vname). This is strictly
# for generating NS style output. When there is more than one link on
# a node, we *must* generate net routes instead of host routes, or the
# parser will be unhappy.
my %linkcount= ();

173 174
# list of ports that a node is connected on. Indexed by node.
my %nodeportlist = ();
175 176
# Map vname:port (member) to the lan its in. 
my %nodeport2lan = ();
177

178 179 180 181 182
#
# Convert list of nodes into a map of $vname:$port to IP. We will need the
# IPs later when filling in the virt_routes table.
# 
while (my ($vname,$ips,$routertype) = $query_result->fetchrow_array) {
183
    if (!$force && $routertype ne "static") {
184 185 186 187
	next;
    }
    $dostatic++;
    
188 189
    $linkcount{$vname} = 0;
    
190 191 192 193
    if (! defined($nodeportlist{$vname}) ) {
      $nodeportlist{$vname} = [];
    }
    
194 195 196 197 198
    if (! defined($map{$vname})) {
	$map{$vname}  = $index;
	$rmap{$index} = $vname;
	$index++;
    }
199 200 201
    foreach my $ipinfo (split(" ", $ips)) {
	my ($port,$ip) = split(":", $ipinfo);
	$ips{"$vname:$port"} = $ip;
202
	push( @{$nodeportlist{$vname}}, $port );
203
	$linkcount{$vname} += 1;
204 205 206 207 208 209 210 211 212 213 214 215
    }
}

if (! $dostatic) {
    warn("No nodes requested static routing in $pid/$eid. This is okay!\n");
    exit(0);
}

#
# Now get the lans. 
#
$query_result =
216
    DBQueryFatal("select vname,member,cost,mask " .
217 218 219 220 221 222 223
		 "from virt_lans where pid='$pid' and eid='$eid'");
if (!$query_result->numrows) {
    warn("*** $0:\n".
	 "    No links or lans in experiment $pid/$eid!\n");
    exit(0);
}

224
while (my ($vname,$member,$cost,$mask) = $query_result->fetchrow_array) {
225 226 227 228
    if (! defined($lans{$vname})) {
	$lans{$vname} = [];
    }
    push(@{$lans{$vname}},$member);
229
    $nodeport2lan{$member} = $vname;
230
    $costs{$vname} = $cost;
231
    $masks{$vname} = $mask;
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
#
# if generating just a linkmap, so that and exit. This format was specified
# by Jon, and is intended to be used as input to his route calculator that
# runs on the nodes.
#
if ($dolinkmap) {
    if (!$impotent) {
	open(MAP, "> $linkmapname") or
	    die("Could not create $linkmapname: $!\n");
    }
    my $edges = 0;
    foreach my $lan (keys(%lans)) {
	my @members = @{$lans{$lan}};
	
	for (my $i = 0; $i < scalar(@members); $i++) {
	    for (my $j = $i; $j < scalar(@members); $j++) {
		my $member1 = $members[$i];
		my $member2 = $members[$j];
	    
		$edges++
		    if ($member1 ne $member2);
	    }
	}
    }
    if ($impotent) {
	print "$index $edges\n";
    }
    else {
	print MAP "$index $edges\n";
    }
    foreach my $lan (keys(%lans)) {
	my @members = @{$lans{$lan}};
	
	for (my $i = 0; $i < scalar(@members); $i++) {
	    for (my $j = $i; $j < scalar(@members); $j++) {
		my $member1 = $members[$i];
		my $member2 = $members[$j];
	    
		if ($member1 ne $member2) {
		    my ($node1,$port1) = split(":", $member1);
		    my ($node2,$port2) = split(":", $member2);
		    my $id1 = $map{$node1};
		    my $id2 = $map{$node2};

		    if ($debug) {
			print STDERR "$member1($id1) $member2($id2)\n";
		    }
		    if ($impotent) {
			print "$node1 " . $ips{$member1} . " " .
			      "$node2 " . $ips{$member2} . " $costs{$lan}\n";
			    
		    }
		    else {
			print MAP "$node1 " . $ips{$member1} . " " .
			          "$node2 " . $ips{$member2} . " $costs{$lan}\n";

		    }
		}
	    }
	}
    }
    close(MAP)
	if (!$impotent);

    exit(0);
}

301 302 303 304 305 306 307 308 309 310 311 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
#
# We use perl IPC goo to create a child we can both write to and read from
# (normal perl I/O provides just unidirectional I/O to a process).
# 
if (! socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC)) {
    die("*** $0:\n".
	"    socketpair failed: $!\n");
}

CHILD->autoflush(1);
PARENT->autoflush(1);

my $childpid = fork();
if (! $childpid) {
    close CHILD;

    #
    # Dup our descriptors to the parent, and exec the program.
    # The parent then talks to it read/write.
    #
    open(STDIN,  "<&PARENT") || die "Can't redirect stdin";
    open(STDOUT, ">&PARENT") || die "Can't redirect stdout";
    open(STDERR, ">&PARENT") || die "Can't redirect stderr";

    exec($routecalc);
    die("*** $0:\n".
	"    exec $routecalc failed: $!\n");
}
close PARENT;

#
# Okay, now send adjacency info for all the nodes on each lan to the child.
#
foreach my $lan (keys(%lans)) {
    my @members = @{$lans{$lan}};

    foreach my $member1 (@members) {
	foreach my $member2 (@members) {
	    if ($member1 ne $member2) {
		my ($node1,$port1) = split(":", $member1);
		my ($node2,$port2) = split(":", $member2);
		my $id1 = $map{$node1};
		my $id2 = $map{$node2};

		# Reverse mapping for later. 
		$rlans{"$node1:$node2"} = $lan;

		if ($debug) {
		    print STDERR "$member1($id1) $member2($id2)\n";
		}

		print CHILD "i $id1 $id2 $costs{$lan}\n";
	    }
	}
    }
}

#
# Parse the routes. Need to map the indices back to nodes, and then form a
# matrix. Why, well you will see in a bit ...
#
362
my @routes	= ();
363 364
my %netroutes   = ();

365 366 367 368 369 370 371
#
# Stores routes that will make it to the DB. Hash is per source node and
# contains an array of routes for each node. This allows for some
# optimizations in a final pass
#
my @dbroutes = ();

372 373
#
# Host route ips for interfaces of a dst node besides the nearest one
374 375 376
# This is indexed by a node (i.e. a "src:srcip-dst:dstip" node) and gives
# of hop:hopips. 
my @hostroutes = ();
377

378 379 380 381
if ( $memdebug ) {
    my $top =`top -n`;
    print STDERR "top output before reading routes\n$top\n";
}
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396
# Tell the child to print the routes.
print CHILD "C\n";

#
# Read back the results from the child.
#
while (<CHILD>) {
    if ($debug) {
	print "$_";
    }
    
    my ($src, $dst, $hop);
    
    if ( /route (\d+) to (\d+) via (\d+)/ ) {
397 398 399
	$src = $rmap{$1};
	$dst = $rmap{$2};
	$hop = $rmap{$3};
400 401 402 403
	if ($debug) {
	    print "src:$src dst:$dst hop:$hop\n";
	}
	$routes[($1 * $index) + $2] = int($3);
404 405 406
    }
    else {
	die("*** $0:\n".
407
	    "    $routecalc returned a bad line: '$_'\n");
408 409 410
    }
}

411 412 413 414 415 416 417 418 419 420
# Tell the child to quit. Then wait for it.
print CHILD "q\n";
waitpid($childpid, 0);
if ($?) {
    die("*** $0:\n".
	"    $routecalc failed with status: $?\n");
}

close(CHILD);

421 422 423
#
# Clean the routes.
#
424 425 426 427
if (! $impotent) {
    DBQueryFatal("delete from virt_routes where ".
		 "pid='$pid' and eid='$eid'");
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
if( $memdebug ) {
    $top =`top -n`;
    print STDERR "top output after reading routes\n$top\n";
}

sub type2bin($) {
    my ($type) = @_;
    if ($type eq "net") {
	return 0;
    } elsif ($type eq "host") {
	return 1;
    }
    die("*** $0:\n".
	"    type2bin passed invalid type: $type\n");
}

sub bin2type($) {
    my ($bin) = @_;
    if ($bin == 0) {
	return "net";
    } elsif ($bin == 1) {
	return "host";
    }
    die("*** $0:\n".
	"    bin2type passed invalid bintype: $bin\n");
}

456 457 458 459 460 461 462 463 464 465
#
# Now it gets fun. We have to go through each src:dst pair in the route
# list. The problem is that the dst could be multihomed and multiple hops
# away, and so we have no idea what interface (IP) we are actually routing
# to. We have to know the IP, or else we won't be able to insert the route!
# So, we use the matrix to recurse through and find our way to the
# destination. When we get to the last hop, we can use the src:dst of that
# last hop to index into rlans, which gives the full lanlink list. Then we
# search that to find the IP.
#
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
for( my $srcid = 0 ; $srcid < $index ; $srcid++ ) {
    for( my $dstid = 0 ; $dstid < $index ; $dstid++ ) {
	my $i = ($srcid * $index) + $dstid;
	if ( ! defined($routes[$i]) ) {
	    next;
	}

	my $src = $rmap{$srcid};
	my $dst = $rmap{$dstid};
	my $hopid = $routes[$i];
	my $hop = $rmap{$hopid};
	my $type = 'host';
	my $directlyconn = 0;
	my $netroutedefined = 0;
	my ($srcip,$dstip,$hopip);
	my ($srcipbin,$dstipbin,$hopipbin);
	
	# remember the port for which we have dstip
	my $dstport;
485

486 487

	#
488 489 490 491
	# In the case of printing NS format, we don't need to print routes
	# for different interfaces since NS supports only a single node
	# address. Also routes for directly connected neighbors in NS
	# is necessary.
492
	#
493 494
	if ($impotent && $format eq "ns") {
	    print "\$$src add-route \$$dst \$$hop\n";
495 496
	}
	
497 498 499
	#
	# This is the lan that contains the src and hop. (the link). 
	#
500 501
	my $srclan  = $rlans{"$src:$hop"};
	my $srcmask = $masks{$srclan};
502
	
503 504 505 506
	#
	# This is the lan that contains the node one hop before dst and dst
	# 
	my $dstlan;
507
	my $dstmask;
508
	
509 510 511 512 513
	#
	# Members in the srclan and dstlan respectively
	#
	my @srcmembers;
	my @dstmembers;
514
	
515 516 517 518 519 520
	#
	# If directly connected, skip adding the route into the DB
	# However, we still need to add a route for other interfaces
	# of the directly connected node
	if ($dst eq $hop) {
	    $directlyconn = 1;
521 522
	    $dstlan  = $rlans{"$src:$dst"};
	    $dstmask = $masks{$dstlan};
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
	    @dstmembers = @{$lans{$dstlan}};
	    @srcmembers = @{$lans{$srclan}};
	    #
	    # Scan dstmembers till we find the dst. This is the IP we want.
	    #
	    foreach my $member (@dstmembers) {
		my ($node,$port) = split(":", $member);
		
		if ($node eq $dst) {
		    $dstport = $port;
		    last;
		}
	    }
	    
	    #
	    # goto HOSTROUTES;
	    # Removed the above goto since using it with the for loop
	    # tickles a perl bug. Look at 
	    # http://archive.develooper.com/perl5-porters@perl.org/msg97631.html
	    # for details
	    #
	} else {
545

546
	    #
547 548
	    # Now we need to find the destination lan (link) by
	    # stepping through each hop till we get to it.
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
	    #
	    my $nhop = $hop;
	    while (1) {
		# Next hop to destination.
		my $j = ($map{$nhop} * $index) + $map{$dst};
		if (!defined($routes[$j])) {
		    die("*** $0:\n".
			"    Failed to find route: $nhop:$dst!\n");
		}
		my $nnhop = $rmap{$routes[$j]};
		
		# Last hop to destination.
		if ($nnhop eq $dst) {
		    last;
		}
		$nhop = $nnhop;
	    }
566 567
	    $dstlan  = $rlans{"$nhop:$dst"};
	    $dstmask = $masks{$dstlan};
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
	    
	    if ($debug) {
		print "$src --> $dst : $nhop:$dst\n";
	    }
	    
	    #
	    # The members of the lan are used to map back to the IPs of the
	    # interfaces (since we need IPs to insert route entries).
	    #
	    @srcmembers = @{$lans{$srclan}};
	    @dstmembers = @{$lans{$dstlan}};
	    
	    #
	    # Scan dstmembers till we find the dst. This is the IP we want.
	    #
	    foreach my $member (@dstmembers) {
		my ($node,$port) = split(":", $member);
		
		if ($node eq $dst) {
		    $dstip = $ips{$member};
		    $dstipbin = inet_aton($dstip);
		    $dstport = $port;
		    last;
		}
592
	    }
593 594
	    
	    #
595 596 597
	    # If optimzing create a net route and avoid a per-host
	    # entry for each pair. Convert the route, but remember we
	    # did it so we can skip similar routes in the future.
598 599
	    #
	    if ($optimize) {
600
		my $newip = inet_ntoa(inet_aton($dstip) & inet_aton($dstmask));
601 602 603 604 605 606 607 608 609 610 611 612 613
		
		if (defined($netroutes{"$src:$newip"})) {
		    if ($netroutes{"$src:$newip"} ne $hop) {
			die("*** $0:\n".
			    "    network route mismatch: $src:$dst:$hop!\n");
		    }
		    $netroutedefined = 1;
		} else {
		    $netroutes{"$src:$newip"} = $hop;
		    $type  = "net";
		    $dstip = $newip;
		    $dstipbin = inet_aton($dstip);
		}
614 615
	    }
	}
616 617 618 619 620 621 622 623 624 625 626
	
	#
	# Scan srcmembers to find the IPs for the src and hop.
	#
	foreach my $member (@srcmembers) {
	    my ($node,$port) = split(":", $member);
	    
	    if ($node eq $src) {
		$srcip   = $ips{$member};
		$srcipbin = inet_aton($srcip);
		next;
627
	    }
628 629 630 631
	    if ($node eq $hop) {
		$hopip = $ips{$member};
		$hopipbin = inet_aton($hopip);
		next;
632
	    }
633
	}
634 635 636 637 638 639 640
	
	# Construct host routes for the other interfaces of dst
	foreach my $port (@{$nodeportlist{$dst}}) {
	    
	    # We already have a route for the ip on dstport
	    if ( $port eq $dstport ) {
		next;
641
	    }
642
	    
643 644 645 646 647
	    my $newip   = $ips{"$dst:$port"};
	    my $newmask = $masks{$nodeport2lan{"$dst:$port"}};
	    
	    my $newipsubnet = inet_ntoa(inet_aton($newip) &
					inet_aton($newmask));
648 649 650 651 652 653 654 655 656 657 658
	    
	    # If we already have a route to newipsubnet via the same hop,
	    # we don't need the host route
	    if ( defined($netroutes{"$src:$newipsubnet"}) &&
		 $netroutes{"$src:$newipsubnet"} eq $hop ) {
		next;
	    } else {
		if ( ! defined($hostroutes[$srcid]) ) {
		    $hostroutes[$srcid] = [];
		}
		my $newipbin = inet_aton($newip);
659
		
660
		push( @{$hostroutes[$srcid]}, 
661 662 663
		      pack( "a4Ia4a4Ia4", $srcipbin, $dstid,
			    inet_aton($newmask),
			    $newipbin, $hopid, $hopipbin) );
664
		      
665
	    }
666
	}
667 668 669 670 671 672 673 674 675 676 677 678 679
	
	# We had to run till here to store hostroutes
	# that may have to be added later. However,
	# we can skip for directly connected neighbors
	# or if net route was already defined
	if ($directlyconn || $netroutedefined) {
	    next;
	}
	
	if ( !defined($dbroutes[$srcid]) ) {
	    $dbroutes[$srcid] = [];
	}
	push( @{$dbroutes[$srcid]}, 
680 681 682
	      pack( "a4Ia4a4Ia4s", $srcipbin, $dstid,
		    inet_aton($dstmask), $dstipbin, $hopid,
		    $hopipbin, type2bin($type)) );
683 684 685
    }
}

686 687 688 689 690 691 692 693 694
# release memory used by the routes hash
@routes = ();
undef @routes;

if( $memdebug ) {
    $top =`top -n`;
    print STDERR "top output after finding net routes\n$top\n";
}

695 696 697 698
# This part adds host routes for subnets that don't have a route.
# However, the first route will be added as a net route
# and if subsequent host routes are different from the first
# route we added, only then will the host routes get added.
699 700 701 702 703 704
for( my $srcid = 0 ; $srcid < $index ; $srcid++ ) {
    if (! defined($hostroutes[$srcid]) ) {
	next;
    }
    my $src = $rmap{$srcid};
    foreach my $hostroute (@{$hostroutes[$srcid]}) {
705 706
	my ($srcipbin, $dstid, $dstmaskbin, $dstipbin, $hopid, $hopipbin) =
	    unpack( "a4Ia4a4Ia4", $hostroute );
707 708 709 710 711
	my $dstip;
	my $dst = $rmap{$dstid};
	my $hop = $rmap{$hopid};
	my $type = 'host';
	
712
	my $dstipsubnet = inet_ntoa($dstipbin & $dstmaskbin);
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
	
	# If we already have a net route to dstipsubnet via the same hop,
	# we don't need the host route
	if ( defined($netroutes{"$src:$dstipsubnet"}) ) {
	    if ($netroutes{"$src:$dstipsubnet"} eq $hop ) {
		next;
	    }
	} else {
	    
	    # We do the following optimization only for
	    # hosts that are _not_ directly connected
	    # neighbors. Otherwise, adding interface 
	    # subnet routes fail. Even with this, certain
	    # redundant links might be unused since the
	    # route calculator will choose one of
	    # the redundant routes over the other(s)
	    if ($optimize && ($dst ne $hop)) {
		$netroutes{"$src:$dstipsubnet"} = $hop;
		$type = "net";
		$dstip = $dstipsubnet;
		$dstipbin = inet_aton($dstip);
	    }
735
	}
736 737 738
	
	if ( !defined($dbroutes[$srcid]) ) {
	    $dbroutes[$srcid] = [];
739
	}
740
	push( @{$dbroutes[$srcid]}, 
741 742
	      pack( "a4Ia4a4Ia4s", $srcipbin, $dstid, $dstmaskbin,
		    $dstipbin, $hopid, $hopipbin, type2bin($type)) );
743
    }
744 745 746 747 748 749 750 751 752 753 754 755
}

# release memory used by all these hashes.
# Not much use doing this at this stage though
%netroutes = ();
undef %netroutes;
@hostroutes = ();
undef @hostroutes;
%lans = ();
undef %lans;
%rlans = ();
undef %rlans;
756 757
%nodeport2lan = ();
undef %nodeport2lan;
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

if( $memdebug ) {
    $top =`top -n`;
    print STDERR "top output before final pass\n$top\n";
}

# In the final pass, for some source nodes that are "edge" 
# nodes (i.e. with degree 1), we can replace all routes with
# one route with a smaller IP prefix since the nexthop is
# the same for all routes
for( my $srcid = 0 ; $srcid < $index ; $srcid++ ) {
    if ( ! defined($dbroutes[$srcid]) ) {	
	next;
    }
    my $src = $rmap{$srcid};
    my ($dst, $hop);
    my ($srcip, $dstip, $hopip, $type, $prevhopip, $prevdstip);
    my ($srcipbin, $dstid, $dstipbin, $hopid, $hopipbin, $typebin);
    my ($prevdstipprefix, $dstipprefix);
    my $oneroute = 0;
    $prevhopip = $prevdstip = 0;
    $prevdstipprefix = $dstipprefix = 0;
    if ( $optimize && $edgeoptimize ) {
	$oneroute = 1;
	foreach my $route (@{$dbroutes[$srcid]}) {
783 784 785
	    ($srcipbin, $dstid, $dstmaskbin, $dstipbin, $hopid, $hopipbin,
	     $typebin) =
		 unpack( "a4Ia4a4Ia4s", $route);
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 814 815 816
	    $srcip = inet_ntoa($srcipbin);
	    $dst = $rmap{$dstid};
	    $dstip = inet_ntoa($dstipbin);
	    $hop = $rmap{$hopid};
	    $hopip = inet_ntoa($hopipbin);
	    $type = bin2type($typebin);
	    if (! $prevhopip || ! $prevdstip) {
		$prevhopip = $hopip;
		$prevdstip = $dstip;
	    } else {
		# This can happen when a node has a degree > 1
		if ($prevhopip ne $hopip) {
		    $oneroute = 0;
		    last;
		}
		
		# This can happen if we have both widearea nodes
		# and local nodes in an experiment. In that case,
		# the widearea nodes all have 10.* addresses while
		# the local ones have 192.168.* 
		$prevdstipprefix = 
		    inet_ntoa(inet_aton($prevdstip) & inet_aton($EXPTNETMASK));
		$dstipprefix = 
		    inet_ntoa(inet_aton($dstip) & inet_aton($EXPTNETMASK));
		if ($dstipprefix ne $prevdstipprefix) {
		    $oneroute = 0;
		    last;
		}
		$prevhopip = $hopip;
		$prevdstip = $dstip;
	    }
817
	}
818 819 820 821 822 823 824
    }
    if( $optimize && $edgeoptimize && $oneroute ) {
	if ($impotent) {
	    if ($debug) {
		printf(STDERR "%s: %-23s --> %-23s - %s\n",
		       ($type eq "net" ? "n" : "h"),
		       "$src:$srcip", "ANY:$dstipprefix", "$hop:$hopip");
825
	    }
826 827
	    if ($format eq "bsd") {
		print "route add -net $dstipprefix $hopip $EXPTNETMASK\n";
828
	    }
829 830
	    elsif ($format eq "suxs") {
		print "route add -net $dstipprefix netmask $EXPTNETMASK gw $hopip\n";
831
	    }
832 833 834 835 836 837 838 839
	} else {
	    DBQueryFatal("insert into virt_routes ".
			 " (pid,eid,vname,src,dst,nexthop,dst_type,dst_mask) ".
			 " values ('$pid', '$eid', '$src', '$srcip', '$dstipprefix', ".
			 "         '$hopip', 'net', '$EXPTNETMASK')");		
	}
    } else {
	foreach my $route (@{$dbroutes[$srcid]}) {
840 841 842
	    ($srcipbin, $dstid, $dstmaskbin, $dstipbin, $hopid, $hopipbin,
	     $typebin) =
		unpack( "a4Ia4a4Ia4s", $route);
843 844 845 846 847 848
	    $srcip = inet_ntoa($srcipbin);
	    $dst = $rmap{$dstid};
	    $dstip = inet_ntoa($dstipbin);
	    $hop = $rmap{$hopid};
	    $hopip = inet_ntoa($hopipbin);
	    $type = bin2type($typebin);
849
	    $mask = inet_ntoa($dstmaskbin);
850 851 852 853 854 855 856 857 858 859 860 861

	    if ($impotent) {
		if ($debug) {
		    printf(STDERR "%s: %-23s --> %-23s - %s\n",
			   ($type eq "net" ? "n" : "h"),
			   "$src:$srcip", "$dst:$dstip", "$hop:$hopip");
		}
		if ($format eq "bsd") {
		    if ($type eq "host") {
			print "route add -host $dstip $hopip\n";
		    }
		    else {
862
			print "route add -net $dstip $hopip $mask\n";
863 864 865 866 867 868 869
		    }
		}
		elsif ($format eq "suxs") {
		    if ($type eq "host") {
			print "route add -host $dstip gw $hopip\n";
		    }
		    else {
870 871
			print "route add -net $dstip netmask ".
			    "$mask gw $hopip\n";
872 873 874 875
		    }
		}
	    } else {
		DBQueryFatal("insert into virt_routes ".
876 877 878 879
			     " (pid,eid,vname,src,dst,nexthop,dst_type,".
			     "  dst_mask) ".
			     " values ('$pid', '$eid', '$src', '$srcip', ".
			     "         '$dstip', '$hopip', '$type', '$mask')");
880 881 882
	    }
	}
    }
883 884
}

885 886 887 888
if( $memdebug ) {
    $top =`top -n`;
    print STDERR "top output just before exit\n$top\n";
}
889

890
exit 0;