assign_prepass.in 33.7 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2004-2009 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
#

#
# Pre-pass filter for assign to coarsen the virtual graph
#

use strict;
30
use POSIX;
31

32 33 34 35 36 37 38 39 40 41 42
sub parse_top($);
sub generate_topfile($;$);
sub parse_ptop($);
sub run_assign($$$$$);
sub write_solution($$$);
sub factor_out_fixednodes($$);
sub combine_links($);
sub list_nodes($);
sub list_links($);
sub min($$);

43 44
my $TBROOT     = '@prefix@';
my $assign_bin = "$TBROOT/libexec/assign";
45 46 47

$| = 1;

48 49 50
my $MAX_DESIRE_WEIGHT       = 0.99;
my $METIS                   = "/usr/local/bin/kmetis";
my $AVG_NODES_PER_PARTITION = 10;
51 52 53 54

#
# Figure out assign args
#
55 56 57
if (@ARGV < 2) {
    die "Usage: $0 [assign args] ptopfile topfile\n";
}
58
my $topfile = pop @ARGV;
59
my $ptopfile = $ARGV[$#ARGV];
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

#
# Okay, this is absolutely terrible - look for our own arguments
#
my $max_multiplex_factor = undef;
my @assign_args;
while (my $arg = shift @ARGV) {
    if ($arg eq "-m") {
	# This one's ours
	$max_multiplex_factor    = shift @ARGV;
	$AVG_NODES_PER_PARTITION = $max_multiplex_factor;
    } else {
	# Not one of ours, must be for assign
	push @assign_args, $arg;
    }
}
76

77 78 79 80 81
# Make up a logfile name, which we'll put assign's output into. Try to extract
# a filename from the top file.
my $logfile;
if ($topfile =~ /(.*).top$/) {
    $logfile = "assign_prepass-$1.log";
82
    $::base = $1;
83 84
} else {
    $logfile = "assign_prepass-$$.log";
85
    $::base = $$;
86 87
}

88 89 90 91
#
# Read in and coarsen the virtual graph
#
my ($realnodes, $reallinks) = parse_top($topfile);
92 93 94 95 96 97 98 99 100

#
# Get some information about the physical graph
#
my ($colocate,$addfeatures,$trivialbw) = parse_ptop($ptopfile);
%::colocate = %$colocate;
%::additive_features = %$addfeatures;
%::trivialbw = %$trivialbw;

101
#my $newgraph = combine_lans($realnodes);
102 103
#my $newgraph = do_metis($realnodes);
my $newgraph = factor_out_fixednodes($realnodes,\&do_metis);
104 105 106 107 108
print "Reduced " . scalar(keys %$realnodes) . " nodes down to " .
	scalar(keys %$newgraph) . "\n";

#write_summary($newgraph);
$newgraph = combine_links($newgraph);
109 110 111 112 113 114 115

#
# Run assign
#

# Make a filename for our coarsened topfile
my $tmp_topfile = $topfile;
116
$tmp_topfile =~ s/(\.v?top)?$/-coarsened$1/;
117

118
print "Generating new topfile\n";
119
my @topfile = generate_topfile($newgraph);
120
print "Running assign\n";
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
my ($nodes, $edges) = run_assign($assign_bin, join(" ",@assign_args),
    $tmp_topfile, \@topfile, $logfile);

#
# Write out the solution
#
write_solution($nodes, $edges, $newgraph);

exit 0;

#####
##### Assign input/output functions
#####

#
# Parse up a top file - note: this parser is much more crude and permissive
# than assign's top file parser. Takes a filename, and returns %nodes and
# %links structures
#
sub parse_top($) {
    my ($filename) = @_;

    my %nodes;
    my %links;

    open(TOP,"<$filename") or die "Unable to open topfile $filename\n";

    while (my $line = <TOP>) {
	chomp $line;
	my @tokens = split /\s+/,$line;
	next unless (@tokens); # Skip blank lines
	SWITCH: for (shift @tokens) {
153
	    (/^node$/) && do {
154 155 156 157 158 159 160 161 162 163
		my $name = shift @tokens;
		my $type = shift @tokens;
		if ($nodes{$name}) {
		    die "Node $name declared twice\n";
		}
		my ($realtype,$count) = split(/:/,$type);
		if (!defined $count) {
		    $count = 1;
		}

164
		my (@flags,%desires);
165 166 167 168 169 170 171 172
		foreach my $token (@tokens) {
		    my ($desire,$weight) = split /:/, $token;
		    if (!defined $weight) {
			push @flags, $desire;
		    } else {
			if ($desire eq "subnode_of") {
			    die "Subnodes not supported yet\n";
			}
173
			$desires{$desire} = $weight;
174 175 176 177 178 179 180
		    }
		}

		$nodes{$name} = {
		    'name'    => $name,
		    'type'    => $realtype,
		    'count'   => $count,
181
		    'desires' => \%desires,
182 183 184 185 186 187 188 189 190
		    'flags'   => \@flags,
		    'fixed'   => undef,
		    'slinks'  => [],
		    'dlinks'  => [],
		    'nodes'   => []
		};

		last;
	    };
191
	    (/^link$/) && do {
192 193 194 195 196 197
		my $name  = shift @tokens;
		my $src   = shift @tokens;
		my $dst   = shift @tokens;
		my $bw    = shift @tokens;
		my $delay = shift @tokens;
		my $plr   = shift @tokens;
198 199 200 201 202 203 204 205 206
		if ($links{$name}) {
		    die "Link $name declared twice\n";
		}
		if (!exists($nodes{$src})) {
		    die "Link source $src does not exist\n";
		}
		if (!exists($nodes{$dst})) {
		    die "Link destination $dst does not exist\n";
		}
207 208 209 210 211 212 213 214

		my $emulated;
		if (grep /^emulated$/, @tokens) {
		    $emulated = 1;
		} else {
		    $emulated = 0;
		}

215
		$links{$name} = {
216 217 218 219 220 221 222 223
		    'name'     => $name,
		    'src'      => $src,
		    'dst'      => $dst,
		    'bw'       => $bw,
		    'delay'    => $delay,
		    'plr'      => $plr,
		    'flags'    => \@tokens,
		    'emulated' => $emulated,
224
		    'reversed' => 0,
225
		    'links'    => []
226 227 228 229 230
		};
		push @{$nodes{$src}{'slinks'}}, $links{$name};
		push @{$nodes{$dst}{'dlinks'}}, $links{$name};
		last;
	    };
231
	    (/^make-vclass$/) && do {
232 233 234 235
                # XXX: Hack, all top files now include pclasses, but almost
                # nobody uses the pre-defined ones. Bad Things will happen
                # if they do...
                #die "Sorry, vclasses are not yet supported\n";
236 237
		last;
	    };
238
	    (/^fix-node$/) && do {
239 240
		my ($vnode, $pnode) = @tokens;;
		if (!$nodes{$vnode}) {
241
		    die "Tried to fix a non existent node: $line\n";
242
		}
243
		$nodes{$vnode}{fixed} = $pnode;
244 245
		last;
	    };
246 247 248 249 250 251
	    (/^node-hint$/) && do {
		my ($vnode, $pnode) = @tokens;;
		if (!$nodes{$vnode}) {
		    die "Tried to hint for a non existent node: $line\n";
		}
		$nodes{$vnode}{hint} = $pnode;
252 253 254 255 256 257
		last;
	    };
	    die "Bad line: $line\n";
	}
   }

258 259
   close TOP;

260 261 262 263 264 265 266 267
   return (\%nodes, \%links);

}

#
# Create a top file with the data we've gathered - takes a %nodes structure and
# returns an array of lines for the top file
#
268 269
sub generate_topfile($;$) {
    my ($nodes,$fixed) = @_;
270
    my @topfile;
271

272 273 274 275
    # Print out the nodes
    while (my ($name,$node) = each %$nodes) {
	my $topline = "node $name $node->{type}:$node->{count} ";
	$topline .= join(" ",
276
	    map { "$_:$node->{desires}{$_}"} keys(%{$node->{desires}}),
277 278 279 280 281 282
	    @{$node->{flags}});
	$topline .= "\n";
	push @topfile, $topline;
	if ($node->{fixed}) {
	    push @topfile, "fix-node $name $node->{fixed}\n";
	}
283 284 285
	if ($node->{hint}) {
	    push @topfile, "node-hint $name $node->{hint}\n";
	}
286 287 288 289 290
    }

    # Print out the links
    foreach my $node (values %$nodes) {
	foreach my $link (@{$node->{'slinks'}}) {
291 292
	    push @topfile, "link $link->{name} $link->{src} $link->{dst} " .
		"$link->{bw} $link->{delay} $link->{plr} " . join(" ",@{$link->{flags}}) . "\n";
293 294 295
	}
    }

296 297 298 299 300 301 302 303 304 305 306 307
    # If we were given an old mapping, generate node-hint lines
    if ($fixed) {
	foreach my $nref (@$fixed) {
	    my ($virtual, $physical) = @$nref;
	    my @real_virtnodes = list_nodes($nodes->{$virtual});
	    foreach my $real_virtnode (@real_virtnodes) {
		push @topfile, "node-hint $real_virtnode $physical\n";
	    }
	}
    }
    

308 309 310
    return @topfile;
}

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
#
# Parse up a ptop file to find out what the resources available on various
# nodes are. Takes a filename, and returns three hash references.
# * A hash, indexed by type, of colocation factors
# * A hash of hash refs, indexed by type and feature name, of additive feature
#   values
# * A hash, indexed by type, of trivial bandwidths
#
sub parse_ptop($) {
    my ($filename) = @_;

    open(PTOP,"<$filename") or die "Unable to open $filename for reading\n";

    #
    # We want to find:
    # The minimum packing factor for each type
    # The minimum value for each additive feature, per type
    # The minimum value of the trivial bandwidth for each type
    #
    my %typecounts = ();
    my %addfeatures = ();
    my %trivialbw = ();

    while (my $line = <PTOP>) {
	chomp $line;
	my @tokens = split /\s+/,$line;
	next unless (@tokens); # Skip blank lines
	SWITCH: for (shift @tokens) {
339 340 341 342
	    /^set-type-limit$/ && do {
		# Skip these.
		last;
	    };
343 344 345 346 347 348 349 350 351 352
	    /^node$/ && do {
		my $name = shift @tokens;
		my @types;
		while (my $type = shift @tokens) {
		    #
		    # First, handle the types
		    #
		    last if ($type eq "-");
		    my ($typename, $count) = split /:/, $type;

353 354 355 356 357
                    # Handle types that are 'static' (we mostly use this
                    # for lans and switches) by simply removing the static
                    # qualifier, which will not appear in the top file
                    $typename =~ s/^\*//;

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 425 426 427 428 429 430 431 432 433 434 435 436 437
		    # Handle types with no count or an 'infinite' count
		    if (!$count) {
			$count = 1;
		    }
		    if ($count eq "*") {
			$count = 65535;
		    }

		    push @types, $typename;

		    # Record this count if it's the first or the lowest seen so
		    # far
		    if ($typecounts{$typename}) {
			if ($count < $typecounts{$typename}) {
			    $typecounts{$typename} = $count;
			}
		    } else {
			$typecounts{$typename} = $count;
		    }
		}
		while (my $feature = shift @tokens) {
		    #
		    # Next handle features
		    #
		    last if ($feature eq "-");

		    # Additive features only
		    if ($feature =~ /^\?\+/) {
			my ($name, $value) = split /:/, $feature;
			foreach my $type (@types) {
			    # Apply to all types
			    if ($addfeatures{$type}) {
				if ($addfeatures{$type}{$name}) {
				    if ($value < $addfeatures{$type}{$name}) {
					$addfeatures{$type}{$name} = $value;
				    }
				} else {
				    $addfeatures{$type}{$name} = $value;
				}
			    } else {
				$addfeatures{$type} = {$name => $value};
			    }
			}
		    }
		}
		while (my $flag = shift @tokens) {
		    #
		    # Next, handle flags - trivial bandwidth is the only one we
		    # care about for now
		    #
		    if ($flag =~ /^trivial_bw/) {
			my ($name, $value) = split /:/, $flag;
			foreach my $type (@types) {
			    if ($trivialbw{$type}) {
				if ($value < $trivialbw{$type}) {
				    $trivialbw{$type} = $value;
				}
			    } else {
				$trivialbw{$type} = $value;
			    }
			}
		    }
		}
		last;
	    };
	    /^link$/ && do {
		#
		# May want to grab out bandwidth some day, but right now,
		# nothing we really need to do
		#
		my ($name, $src, $dst, $bw, $delay, $plr, $type) = @tokens;
		last;
	    };
	    die "Bad line: $line\n";
	}
    }

    return (\%typecounts,\%addfeatures,\%trivialbw);
}

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
#
# Actually run assign - takes the name of the assign binary, the arguments to
# it, and a reference to the @topfile structure. Returns a solution data
# structure
#
sub run_assign($$$$$) {
    my ($assignbin,$assignargs,$topfile_name,$topfile_contents, $logfile) = @_;

    open(TOP,">$topfile_name") or die "Unable to open $topfile_name for " .
	    "writing\n";
    print TOP @$topfile_contents;
    close TOP;

    open(ASSIGN,"|$assignbin $assignargs $topfile_name > $logfile");
    close ASSIGN;  # This will wait for the child process to die
453
    print "assign completed\n";
454 455 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 495 496 497 498 499 500 501 502
    if ($?) {
	# Assign failed, just pass through the exit code and the assign output
	warn "Assign failed\n";
	my $exit_status = ($? >> 8);
	open(FH,"<$logfile") or die "Unable to open $logfile\n";
	while (<FH>) {
	    #
	    # Print out assign's results, since assign_wrapper likes to look at
	    # some of them
	    #
	    print;
	}
	exit $exit_status;
    }
    
    return parse_solution($logfile);

}

#
# Given a filename containing an assign logfile, parse the solution. Return a
# list of (virtual, physical) pairs for the nodes, and just return an unparsed
# list of edges
#
sub parse_solution($) {
    my ($assignlog) = @_;
    open SOL, "<$assignlog" or die "Unable to open $assignlog for reading\n";
    #
    # Find the BEST SCORE line
    #
    while (<SOL>) {
	#
	# We print out these lines, assign_wrapper expects to see them
	#
	if (/^[ \t]+BEST SCORE: [ \t]+([0-9]+(\.[0-9]+)?)/) {
	    print;
	}
	if (/^With ([0-9]+) violations$/) {
	    print;
	    last;
	}
    }

    #
    # Find the nodes
    #
    my @nodes;
    while (<SOL> !~ /^Nodes:/) {}
    while (<SOL>) {
503
	chomp;
504 505 506 507 508 509 510
	/^End Nodes$/ && last;
	my @info = split;
	my ($virtual,$physical) = @info[0,1];
	push @nodes, [$virtual, $physical];
    }

    #
511
    # Find the edges
512 513 514 515
    #
    my @edges;
    while (<SOL> !~ /^Edges:/) { }
    while (<SOL>) {
516
	chomp;
517
	/^End Edges$/ && last;
518
	my ($name, $type, @plinks) = split /\s+/,$_;
519 520 521 522 523 524 525 526 527 528 529
	
	#
	# Phsical links are linksted as 'link interface', so part them up as
	# such
	#
	my @pairs;
	while (@plinks) {
	    my ($link, $interface) = (shift @plinks, shift @plinks);
	    push @pairs, [$link, $interface];
	}
	push @edges, [$name, $type, \@pairs];
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
    }
    close(SOL);

    return (\@nodes,\@edges);

}


#
# Given a list of (virtual,physical) pairs from the assign output, a list of
# @edges, and the %nodes structure the mapping was done with, print out an
# assign-style solution.
#
sub write_solution($$$) {
    my ($nodes, $edges, $nodegraph) = @_;

    print "\nNodes:\n";
    foreach my $nref (@$nodes) {
	my ($virtual, $physical) = @$nref;
	my @real_virtnodes = list_nodes($nodegraph->{$virtual});
	foreach my $real_virtnode (@real_virtnodes) {
	    print "$real_virtnode $physical\n";
	}
    }
    print "End Nodes\n";

556 557 558 559 560 561 562 563 564 565
    #
    # Build a hash of all edges by name from the nodegraph
    #
    my %links;
    while (my ($name, $node) = each %$nodegraph) {
	foreach my $link (@{$node->{slinks}}) {
	    $links{$link->{'name'}} = $link;
	}
    }

566
    print "Edges:\n";
567
    foreach my $edge (@$edges) {
568 569
	my ($name, $type, $pairs) = @$edge;
	my @pairs = @$pairs;
570 571
	my @real_virtlinks = list_links($links{$name});
	foreach my $real_virtlink (@real_virtlinks) {
572
	    print "$real_virtlink->{name} $type ";
573 574

	    my @ordered_pairs;
575
	    if (!$real_virtlink->{'reversed'}) {
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
		@ordered_pairs = @pairs;
	    } else {
		# The direction of this link is reversed wrt the conglomerated
		# link it got shoved into - reverse the order of the pairs.
		foreach my $pair (@pairs) {
		    unshift @ordered_pairs, $pair;
		}
	    }

	    foreach my $pair (@ordered_pairs) {
		my ($link, $iface) = @$pair;
		print "$link $iface ";
	    }

	    print "\n";
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
    print "End Edges\n";
}

#####
##### Functions for coarsening the graph
#####

#
# Simple coarsener that conglomerates leaf LANs
#
sub combine_lans($) {
    my ($nodes) = @_;

    #
    # Make groups to coarsen - if a node has exactly one link, and it is to a
    # LAN, put the node in a group named after that LAN
    #
    my %nodegroups;
    while (my ($name,$node) = each %$nodes) {
	my $totallinks = @{$node->{slinks}} + @{$node->{dlinks}};
	if ($totallinks != 1) {
	    $nodegroups{"$node->{name}-own"} = [$node];
	    next;
	}
	foreach my $link (@{$node->{slinks}}) {
	    my $dst = $nodes->{$link->{dst}};
	    if ($dst->{type} =~ /lan/) {
		push @{$nodegroups{$dst->{name}}}, $node;
		next;
	    }
	}
	foreach my $link (@{$node->{dlinks}}) {
	    my $src = $nodes->{$link->{dst}};
	    if ($src->{type} =~ /lan/) {
		push @{$nodegroups{$src->{name}}}, $node;
		next;
	    }
	}
    }

    #
    # Create the new graph by coarsening into the lists we made above
    #
    my %newgraph;
    foreach my $nodelist (values %nodegroups) {
	my @newnodes = make_conglomerates(@$nodelist);
	foreach my $newnode (@newnodes) {
	    $newgraph{$newnode->{name}} = $newnode;
	}
    }

    return \%newgraph;
}

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
#
# Conglomerate sets of nodes that are fixed to the same physical node. Returns
# two hash refs - first the conglomerated fixed nodes, then the left over nodes
# that weren't fixed in place.
#
sub combine_fixed($) {
    my ($nodes) = @_;

    #
    # Buid up lists of nodes that are fixed to the same physical node - put all
    # nodes that aren't fixed anywhere in the 'unfixed' group
    #
    my %fixednodes;
    my %unfixed;
    while (my ($name,$node) = each %$nodes) {
	if ($node->{fixed}) {
	    push @{$fixednodes{$node->{fixed}}}, $node;
	} else {
	    $unfixed{$name} = $node;
	}
    }

    #
    # Create the new graph by coarsening into the lists we made above
    #
    my %newgraph;
    foreach my $nodelist (values %fixednodes) {
	my @newnodes = make_conglomerates(@$nodelist);
	foreach my $newnode (@newnodes) {
	    $newgraph{$newnode->{name}} = $newnode;
	}
    }

    return (\%newgraph,\%unfixed);
}

683 684 685
#
# More complex coarsener that uses METIS to partition up the graph
#
686 687 688
sub do_metis($) {
    my ($nodes) = @_;

689 690 691 692 693 694 695
    my @nodelists;
    my %nodes_by_type = separate_nodes_by_type($nodes);
    while (my ($type,$nodelist) = each(%nodes_by_type)) {
	my @metisfile = generate_metis_graphfile($nodes);

	my $metisfilename = "$::base.$type.metis";
	my $metislog = "metis-$::base.$type.log";
696

697
	my $packing_factor = $::colocate{$type};
698

699 700 701 702
	push @nodelists,
	    run_metis(\@metisfile,$nodelist,$metisfilename,$metislog,
		$packing_factor);
    }
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718

    #
    # Create the new graph by coarsening into the lists we made above
    #
    my %newgraph;
    foreach my $nodelist (@nodelists) {
	my @newnodes = make_conglomerates(@$nodelist);
	foreach my $newnode (@newnodes) {
	    $newgraph{$newnode->{name}} = $newnode;
	}
    }

    return \%newgraph;

}

719 720 721 722 723 724 725 726 727 728 729 730
#
# Front-end to other coarsening functions - 'factor out' fixed nodes and
# conglomerate them seperately, running the passed function pointer on only the
# non-fixed nodes. Takes a node graph and a reference to the function to run.
#
sub factor_out_fixednodes($$) {
    my ($nodes, $func_ref) = @_;
    my ($fixednodes, $unfixed) = combine_fixed($nodes);
    my $newgraph = &$func_ref($unfixed);
    return {%$newgraph, %$fixednodes};
}

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
#
# Return a hash of hashes - each hash contains nodes that all have the same type
#
sub separate_nodes_by_type($) {
    my ($nodes) = @_;

    my %types;
    while (my ($name, $node) = each %$nodes) {
	my $type = $node->{type};
	if ($types{$type}) {
	    $types{$type}{$name} = $node;
	} else {
	    $types{$type} = {$name => $node};
	}
    }

    return %types;
}

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
#####
##### Input/output functions for METIS
#####

#
# Generate a version of the virtual graph suitable for use with METIS
#
sub generate_metis_graphfile($) {
    my ($nodes) = @_;
    my @metisfile;

    #
    # We have to number the nodes and edges for METIS
    #
    my $node_count = 0;
    my $link_count = 0;
    while (my ($name, $node) = each %$nodes) {
	$node->{'metis_id'} = ++$node_count;
	foreach my $link (@{$node->{'slinks'}}) {
769 770 771 772 773 774
	    #
	    # Ignore links whose other end is not in our set of links
	    #
	    if ($nodes->{$link->{'dst'}}) {
		$link->{'metis_id'} = ++$link_count;
	    }
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
	}
    }

    #
    # Construct the magic fist line for METIS
    #
    push @metisfile, "$node_count $link_count 10\n";

    #
    # Go through all nodes
    #
    while (my ($name, $node) = each %$nodes) {
	#
	# Get number of the node on the other end of each link
	#
	push @metisfile, "%$name\n";
	my @neighbors = ();
	foreach my $link (@{$node->{'slinks'}}) {
	    if (!$link->{'metis_id'}) {
794 795
		# Other end of this link is not in our set of nodes, ignore it
		next;
796 797 798 799 800
	    }
	    push @neighbors, $nodes->{$link->{'dst'}}{'metis_id'};
	}
	foreach my $link (@{$node->{'dlinks'}}) {
	    if (!$link->{'metis_id'}) {
801 802
		# Other end of this link is not in our set of nodes, ignore it
		next;
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
	    }
	    push @neighbors, $nodes->{$link->{'src'}}{'metis_id'};
	}

	push @metisfile, "$node->{count} " . join(" ",@neighbors) . "\n";
    }

    return @metisfile;
}

#
# Read in a METIS 'partition file', and return lists of nodes corresponding to
# the partitions.
#
sub read_metis_partfile($$) {
    my ($partfile,$nodes) = @_;
    open(FH,"<$partfile");
    my $lineno = 1;
    my @partitions;
    while (my $partno = <FH>) {
	chomp $partno;
	$partitions[$lineno++] = $partno;
    }
826
    close(FH);
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

    my @nodelists;
    while (my ($name, $node) = each %$nodes) {
	my $partno = $partitions[$node->{'metis_id'}];
	push @{$nodelists[$partno]}, $node;
    }

    #print "Gonna return " . scalar(@nodelists) . " node lists\n";

    return @nodelists;
}

#
# Actually run metis, and return lists of the partitions it came up with
#
842 843
sub run_metis($$$$;$) {
    my ($metisfile,$nodes,$metisfilename,$metislogfile,$colocate) = @_;
844 845 846 847

    if (!$colocate) {
	$colocate = $AVG_NODES_PER_PARTITION;
    }
848
    print "run_metis called with colocate of $colocate\n";
849

850 851
    # Pick a number of partitions such that the average parition size
    # will be $AVG_NODES_PER_PARTITION
852
    my $npart = POSIX::ceil(scalar(keys %$nodes) / $colocate);
853 854 855 856
    if ($npart <= 1) {
	# No point in running METIS, just give the list of nodes back
	return [values(%$nodes)];
    }
857 858 859 860 861 862 863

    open (FH,">$metisfilename") or die "Unable to open $metisfilename for " .
	    "writing\n";
    print FH @$metisfile;
    close FH;

    print "Partitioning with kmets into $npart partitions\n";
864 865
    print "$METIS $metisfilename $npart > $metislogfile 2>&1\n";
    if (!system "$METIS $metisfilename $npart > $metislogfile 2>&1") {
866 867 868 869 870 871
	die "kmetis failed!\n";
    }

    return read_metis_partfile("$metisfilename.part.$npart",$nodes);
}

872 873 874 875 876 877 878 879 880 881 882 883
#####
##### Functions for dealing with conglomerates
#####

#
# Takes a set of nodes and returns a list of 'conglomerates' of them
#
sub make_conglomerates(@) {
    my @nodes = @_;

    # If there is only one node, just give it back
    if (@nodes == 1) {
884
	return @nodes;
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    }

    # Put them in order for our bin-packing approximation algorithm
    @nodes = binpack_sort(@nodes);

    my @conglomerates;

    # Go through the rest of the nodes and add them in
    foreach my $node (@nodes) {

	#
	# Find a conglomerate this node can fit into - we take the first fit
	#
	my $conglomerate = undef;
	foreach my $candidate (@conglomerates) {
	    if (node_fits_in_conglomerate($node,$candidate)) {
		$conglomerate = $candidate;
		last;
	    }
	}
	
	if (!$conglomerate) {
	    # Start a new one if we didn't find one
908
	    $conglomerate = new_conglomerate($node);
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
	    push @conglomerates, $conglomerate;
	} else {
	    # Add it to the existing conglomerate
	    
	    # Check the node type and handle the typecount
	    if ($node->{'type'} ne $conglomerate->{'type'}) {
		die "Cannot add node with type $node->{'type'} to " .
		    "conglomerate with type $conglomerate->{type}\n";
	    }
	    $conglomerate->{'count'} += $node->{'count'};

	    # Handle desires
	    # XXX - for now, we add desires together, but make sure that the
	    # total doesn't go over 1.0, since that changes the meaning of the
	    # desire to assign. This is a defciency in assign that should be
924 925 926 927 928 929 930 931 932 933 934 935 936
	    # fixed.
	    DESIRE: while (my ($name, $weight) = each %{$node->{'desires'}}) {
		if (exists($conglomerate->{'desires'}{$name})) {
		    # Conglomerate already has this desire, just add to it
		    my $existing_weight = $conglomerate->{'desires'}{$name};
		    my $newweight;
		    if (substr($name,0,2) eq "?+") {
			# We treat additive local desire specially - we
			# don't cap them as we do for other desires
			$newweight = $existing_weight + $weight;
		    } else {
			$newweight = min($MAX_DESIRE_WEIGHT,
			    $existing_weight + $weight);
937
		    }
938 939 940 941 942
		    $conglomerate->{'desires'}{$name} = $newweight;
		} else {
		    # If we made it here, we must not have found an existing
		    # desire that matched
		    $conglomerate->{'desires'}{$name} = $weight;
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
		}
	    }
	
	    # XXX - Handle flags
	
	    # Fix up this node's links
	    foreach my $link (@{$node->{'slinks'}}) {
		$link->{'src'} = $conglomerate->{'name'};
		push @{$conglomerate->{'slinks'}}, $link;
	    }
	    foreach my $link (@{$node->{'dlinks'}}) {
		$link->{'dst'} = $conglomerate->{'name'};
		push @{$conglomerate->{'dlinks'}}, $link;
	    }

	    # Add to the nodes list
	    push @{$conglomerate->{'nodes'}}, $node;

961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
	    # Handle fixed nodes
	    if ($conglomerate->{'fixed'}) {
		if ($node->{'fixed'} && ($node->{'fixed'} ne
			$conglomerate->{'fixed'})){
		    die "ERROR - tried to combine two fixed nodes!\n";
		}
	    }
	    if ($node->{'fixed'}) {
		if (!$conglomerate->{'fixed'}) {
		    $conglomerate->{'fixed'} = $node->{'fixed'};
		}
	    }

	    # Handle node hints - we will not put more than one hint on a
	    # conglomerate
	    if ($node->{'hint'} && !$conglomerate->{'hint'}) {
		$conglomerate->{'hint'} = $node->{'hint'};
	    }
	}
980 981 982 983 984 985 986 987 988 989 990 991
    }

    return @conglomerates;
}

#
# Return 1 if the given node will fit into the remaining capacity of the given
# conglomerate, and 0 if it will not
#
sub node_fits_in_conglomerate($$) {
    my ($node, $conglomerate) = @_;

992 993 994 995 996
    # We can conglomerate nodes that are:
    # 1) Not fixed
    # 2) One is fixed, but the other is not
    # 3) Both are fixed to the same place
    if (($node->{'fixed'} && $conglomerate->{'fixed'}) &&
997 998 999 1000
	($node->{'fixed'} ne $conglomerate->{'fixed'})) {
	return 0;
    }

1001 1002
    my $type = $node->{'type'};

1003
    # Can't conglomerate nodes of different types
1004
    if ($type ne $conglomerate->{'type'}) {
1005 1006 1007 1008 1009 1010
	return 0;
    }

    #
    # Can't go over the colocate factor
    #
1011
    my $colocate = $::colocate{$type};
1012
    if (!$colocate) {
1013 1014 1015 1016
	print "Don't know colocate factor for $node->{type}\n";
	return 0;

	#die "Don't know colocate factor for $node->{type}\n";
1017
    }
1018 1019 1020
    if (defined $max_multiplex_factor && ($colocate > $max_multiplex_factor)) {
	$colocate = $max_multiplex_factor;
    }
1021 1022 1023 1024 1025 1026 1027
    if (($node->{'count'} + $conglomerate->{'count'}) > $colocate) {
	return 0;
    }

    #
    # Check to see if we're going over for any additive local features
    #
1028 1029 1030 1031 1032 1033 1034 1035 1036
    
    # This is some astonishingly bad perl magic - somehow the internal iterator
    # for this hash isn't getting reset, so sometimes the each() statement
    # below is starting halfway through the list. Calling keys() resets it.
    keys %{$node->{'desires'}};
    while (my ($name, $new_weight) =
		each %{$node->{'desires'}}) {
	next unless exists $conglomerate->{'desires'}{$name};
	my $old_weight = $conglomerate->{'desires'}{$name};
1037 1038 1039
	if (exists $::additive_features{$type} &&
	    exists $::additive_features{$type}{$name} &&
	    (($old_weight + $new_weight) > $::additive_features{$type}{$name})) {
1040 1041 1042 1043
		return 0;
	}
    }

1044 1045 1046 1047 1048
    #
    # Check for self-links, to see if this would make us go over a limit
    #
    my $self_link_bandwidth = 0;
    foreach my $link (@{$conglomerate->{'slinks'}}) {
1049
	#print "Checking $link->{'dst'} against $conglomerate->{'name'} and $node->{'name'}\n";
1050 1051 1052 1053 1054 1055
	if (($link->{'dst'} eq $conglomerate->{'name'}) ||
	    ($link->{'dst'} eq $node->{'name'})) {
	    $self_link_bandwidth += $link->{'bw'};
	}
    }
    foreach my $link (@{$node->{'slinks'}}) {
1056
	#print "Checking $link->{'dst'} against $conglomerate->{'name'} and $node->{'name'}\n";
1057 1058 1059 1060 1061
	if (($link->{'dst'} eq $conglomerate->{'name'}) ||
	    ($link->{'dst'} eq $node->{'name'})) {
	    $self_link_bandwidth += $link->{'bw'};
	}
    }
1062

1063
    if ($::trivialbw{$type} && $self_link_bandwidth > $::trivialbw{$type}) {
1064 1065 1066 1067 1068
	return 0;
    }


    return 1;
1069 1070 1071 1072 1073 1074
}

#
# Create a new conglomerate, starting from an existing node
#
my $conglomerate_count = 0;
1075
sub new_conglomerate($) {
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    my ($node) = @_;
    my %conglomerate = ();

    # Make up a name
    my $name = "conglomerate_" . $conglomerate_count++;
    $conglomerate{'name'} = $name;

    # Initialize most values from the node
    $conglomerate{'type'}    = $node->{'type'};
    $conglomerate{'count'}   = $node->{'count'};
1086
    $conglomerate{'desires'} = \%{$node->{'desires'}};
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    $conglomerate{'flags'}   = $node->{'flags'};

    $conglomerate{'slinks'}  = [];
    foreach my $link (@{$node->{'slinks'}}) {
	$link->{'src'} = $name;
	push @{$conglomerate{'slinks'}}, $link;
    }

    $conglomerate{'dlinks'}  = [];
    foreach my $link (@{$node->{'dlinks'}}) {
	$link->{'dst'} = $name;
	push @{$conglomerate{'dlinks'}}, $link;
    }

    $conglomerate{'nodes'} = [$node];

    $conglomerate{'fixed'} = $node->{'fixed'};

1105 1106 1107 1108
    if ($node->{'hint'}) {
	$conglomerate{'hint'} = $node->{'hint'};
    }

1109 1110 1111 1112
    return \%conglomerate;

}

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
#
# Find all links in the given graph that have the same source and destination -
# return a new graph that combines these links, so that assign can score them
# much faster.
#
sub combine_links($) {
    my ($nodes) = @_;

    #
    # Make a big ole hash of all of the links in the graph
    #
    my %links;
    my $totallinks = 0;
    while (my ($name, $node) = each %$nodes) {
	foreach my $link (@{$node->{slinks}}) {
	    my $src = $nodes->{$link->{'src'}};
	    my $dst = $nodes->{$link->{'dst'}};

	    # We do this to get a canonical src, dst ordering
1132
	    my ($csrc, $cdst) = sort { $a cmp $b } ($src, $dst);
1133 1134 1135 1136 1137 1138 1139 1140 1141 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
	    push @{$links{$csrc}{$cdst}}, $link;
	    $totallinks++;
	}
    }

    #
    # Okay, now actually make link conglomerates from the groups we found
    #
    my @conglomerates;
    foreach my $src (keys %links) {
	foreach my $dst (keys %{$links{$src}}) {
	    push @conglomerates,
		    make_link_conglomerates(@{$links{$src}{$dst}});
	}
    }

    #
    # Copy all of the nodes, but clear out their links - we'll fix them up
    # below.
    #
    my %new_nodes;
    while (my ($name, $node) = each %$nodes) {
	my %new_node = %$node;
	$new_node{'slinks'} = [];
	$new_node{'dlinks'} = [];
	$new_nodes{$name} = \%new_node;
    }

    #
    # Go through our conglomerated links and hook them up to the right nodes
    #
    foreach my $link (@conglomerates) {
	my $src = $link->{'src'};
	my $dst = $link->{'dst'};

	push @{$new_nodes{$src}{'slinks'}}, $link;
	push @{$new_nodes{$dst}{'dlinks'}}, $link;
    }

    print "Reduced $totallinks links down to " . scalar(@conglomerates) . "\n";

    return \%new_nodes;
}

my $link_conglomerate_count = 0;
sub new_link_conglomerate($) {
    my ($link) = @_;
    my %conglomerate = ();

    # Make up a name
    my $name = "clink_" . $conglomerate_count++;
    $conglomerate{'name'} = $name;

    # Initialize most values from the link
    $conglomerate{'src'}      = $link->{'src'};
    $conglomerate{'dst'}      = $link->{'dst'};
    $conglomerate{'bw'}       = $link->{'bw'};
    $conglomerate{'delay'}    = $link->{'delay'};
    $conglomerate{'plr'}      = $link->{'plr'};
    $conglomerate{'flags'}    = $link->{'flags'};
    $conglomerate{'emulated'} = $link->{'emulated'};
    $conglomerate{'links'}    = [$link];

    return \%conglomerate;

}

sub make_link_conglomerates(@) {
    my @links = binpack_link_sort(@_);
    if (scalar(@links) < 2) {
	return @links;
    }

    my @conglomerates;

    # Go through the rest of the nodes and add them in
    foreach my $link (@links) {

	#
	# Find a conglomerate this node can fit into - we take the first fit
	#
	my $conglomerate = undef;
	foreach my $candidate (@conglomerates) {
	    if (link_fits_in_conglomerate($link,$candidate)) {
		$conglomerate = $candidate;
		last;
	    }
	}

	if (!$conglomerate) {
	    # Start a new one if we didn't find one
	    $conglomerate = new_link_conglomerate($link);
	    push @conglomerates, $conglomerate;
	} else {
	    # Add it to the existing conglomerate
	    $conglomerate->{'bw'} += $link->{'bw'};

1230 1231 1232 1233 1234
	    # Figure out if it points in the same direction as the rest of the
	    # links in the conglomerate
	    if ($link->{'src'} ne $conglomerate->{'src'}) {
		$link->{'reversed'} = 1;
	    }
1235 1236 1237 1238 1239

	    # XXX - Handle flags
	    # Add to the nodes list
	    push @{$conglomerate->{'links'}}, $link;

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
	}
    }

    return @conglomerates;

}

sub link_fits_in_conglomerate($$) {
    my ($newlink, $conglomerate) = @_;
    if (!$conglomerate->{'emulated'} || !$newlink->{'emulated'}) {
	return 0;
    }
    # XXX - 100Mbps hardcoded
    if (($conglomerate->{'bw'}
	    + $newlink->{'bw'}) > 100000) {
	return 0;
    }

    return 1;
}
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

#####
##### Utitility functions
#####

#
# Recurse through a $node structure and return a list of all virtual nodes in
# the original graph that were combined to form this conglomerate
#
sub list_nodes($) {
    my ($virtual) = @_;
    my @nodelist = ();
    if (!@{$virtual->{'nodes'}}) {
	return ($virtual->{name});
    } else {
	foreach my $node (@{$virtual->{'nodes'}}) {
	    push @nodelist, list_nodes($node);
	}
    }
    return @nodelist;
}

1282 1283 1284 1285 1286 1287 1288
#
# Similar to above, but for links.
#
sub list_links($) {
    my ($virtual) = @_;
    my @linklist = ();
    if (!@{$virtual->{'links'}}) {
1289
	return ($virtual);
1290 1291 1292 1293 1294 1295 1296 1297
    } else {
	foreach my $link (@{$virtual->{'links'}}) {
	    push @linklist, list_links($link);
	}
    }
    return @linklist;
}

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
#
# Write out a summary of the current virtual topology
#
sub write_summary($) {
    my ($nodes) = @_;
    while (my ($name,$node) = each %$nodes) {
	my @subnodes = list_nodes($node);
	print "$name " . join(", ",@subnodes) . "\n";
    }
}


#
# Sort a list of nodes for use with the bin-packing algorithm
# XXX - will probably need to take into account features such as mem/cpu needs
# in the future.
#
sub binpack_sort(@) {
    return sort {
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
	# Sort first by CPU (if it's there)
	my $rv;
	if ($b->{'desires'} && $b->{'desires'}{'?+cpu'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+cpu'}) {

	    $rv = ( $b->{'desires'}{'?+cpu'} <=> $a->{'desires'}{'?+cpu'} );
	    if ($rv != 0) {
		return $rv;
	    }
	}

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
	if ($b->{'desires'} && $b->{'desires'}{'?+cpupercent'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+cpupercent'}) {

	    $rv = ( $b->{'desires'}{'?+cpupercent'} <=>
		    $a->{'desires'}{'?+cpupercent'} );
	    if ($rv != 0) {
		return $rv;
	    }
	}

1338
	# Then by memory
1339 1340
	if ($b->{'desires'} && $b->{'desires'}{'?+ram'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+ram'}) {
1341

1342
	    $rv = ( $b->{'desires'}{'?+ram'} <=> $a->{'desires'}{'?+ram'} );
1343 1344 1345 1346 1347
	    if ($rv != 0) {
		return $rv;
	    }
	}
	
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
	if ($b->{'desires'} && $b->{'desires'}{'?+rampercent'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+rampercent'}) {

	    $rv = ( $b->{'desires'}{'?+rampercent'} <=>
		    $a->{'desires'}{'?+rampercent'} );
	    if ($rv != 0) {
		return $rv;
	    }
	}

1358 1359
	# Fall back to count if neither of the others were given
	return $b->{'count'} <=> $a->{'count'};
1360 1361 1362
    } @_;
}

1363 1364 1365 1366 1367 1368
sub binpack_link_sort(@) {
    return sort {
	$b->{'bw'} <=> $a->{'bw'} 
    } @_;
}

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378

# Returns the smaller of two numbers
sub min($$) {
    my ($a,$b) = @_;
    if ($a < $b) {
	return $a;
    } else {
	return $b;
    }
}