assign_prepass.in 32.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
# Copyright (c) 2004 University of Utah and the Flux Group.
# All rights reserved.
#

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

use strict;
13
use POSIX;
14

15 16 17 18 19 20 21 22 23 24 25
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($$);

26 27
my $TBROOT     = '@prefix@';
my $assign_bin = "$TBROOT/libexec/assign";
28 29 30

$| = 1;

31 32 33
my $MAX_DESIRE_WEIGHT       = 0.99;
my $METIS                   = "/usr/local/bin/kmetis";
my $AVG_NODES_PER_PARTITION = 10;
34 35 36 37

#
# Figure out assign args
#
38 39 40
if (@ARGV < 2) {
    die "Usage: $0 [assign args] ptopfile topfile\n";
}
41
my $topfile = pop @ARGV;
42
my $ptopfile = $ARGV[$#ARGV];
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

#
# 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;
    }
}
59

60 61 62 63 64
# 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";
65
    $::base = $1;
66 67
} else {
    $logfile = "assign_prepass-$$.log";
68
    $::base = $$;
69 70
}

71 72 73 74
#
# Read in and coarsen the virtual graph
#
my ($realnodes, $reallinks) = parse_top($topfile);
75 76 77 78 79 80 81 82 83

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

84
#my $newgraph = combine_lans($realnodes);
85 86
#my $newgraph = do_metis($realnodes);
my $newgraph = factor_out_fixednodes($realnodes,\&do_metis);
87 88 89 90 91
print "Reduced " . scalar(keys %$realnodes) . " nodes down to " .
	scalar(keys %$newgraph) . "\n";

#write_summary($newgraph);
$newgraph = combine_links($newgraph);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

#
# Run assign
#

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


my @topfile = generate_topfile($newgraph);
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) {
135
	    (/^node$/) && do {
136 137 138 139 140 141 142 143 144 145
		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;
		}

146
		my (@flags,%desires);
147 148 149 150 151 152 153 154
		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";
			}
155
			$desires{$desire} = $weight;
156 157 158 159 160 161 162
		    }
		}

		$nodes{$name} = {
		    'name'    => $name,
		    'type'    => $realtype,
		    'count'   => $count,
163
		    'desires' => \%desires,
164 165 166 167 168 169 170 171 172
		    'flags'   => \@flags,
		    'fixed'   => undef,
		    'slinks'  => [],
		    'dlinks'  => [],
		    'nodes'   => []
		};

		last;
	    };
173
	    (/^link$/) && do {
174 175 176 177 178 179
		my $name  = shift @tokens;
		my $src   = shift @tokens;
		my $dst   = shift @tokens;
		my $bw    = shift @tokens;
		my $delay = shift @tokens;
		my $plr   = shift @tokens;
180 181 182 183 184 185 186 187 188
		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";
		}
189 190 191 192 193 194 195 196

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

197
		$links{$name} = {
198 199 200 201 202 203 204 205
		    'name'     => $name,
		    'src'      => $src,
		    'dst'      => $dst,
		    'bw'       => $bw,
		    'delay'    => $delay,
		    'plr'      => $plr,
		    'flags'    => \@tokens,
		    'emulated' => $emulated,
206
		    'reversed' => 0,
207
		    'links'    => []
208 209 210 211 212
		};
		push @{$nodes{$src}{'slinks'}}, $links{$name};
		push @{$nodes{$dst}{'dlinks'}}, $links{$name};
		last;
	    };
213
	    (/^make-vclass$/) && do {
214 215 216
		die "Sorry, vclasses are not yet supported\n";
		last;
	    };
217
	    (/^fix-node$/) && do {
218 219
		my ($vnode, $pnode) = @tokens;;
		if (!$nodes{$vnode}) {
220
		    die "Tried to fix a non existent node: $line\n";
221
		}
222
		$nodes{$vnode}{fixed} = $pnode;
223 224
		last;
	    };
225 226 227 228 229 230
	    (/^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;
231 232 233 234 235 236
		last;
	    };
	    die "Bad line: $line\n";
	}
   }

237 238
   close TOP;

239 240 241 242 243 244 245 246
   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
#
247 248
sub generate_topfile($;$) {
    my ($nodes,$fixed) = @_;
249
    my @topfile;
250

251 252 253 254
    # Print out the nodes
    while (my ($name,$node) = each %$nodes) {
	my $topline = "node $name $node->{type}:$node->{count} ";
	$topline .= join(" ",
255
	    map { "$_:$node->{desires}{$_}"} keys(%{$node->{desires}}),
256 257 258 259 260 261
	    @{$node->{flags}});
	$topline .= "\n";
	push @topfile, $topline;
	if ($node->{fixed}) {
	    push @topfile, "fix-node $name $node->{fixed}\n";
	}
262 263 264
	if ($node->{hint}) {
	    push @topfile, "node-hint $name $node->{hint}\n";
	}
265 266 267 268 269
    }

    # Print out the links
    foreach my $node (values %$nodes) {
	foreach my $link (@{$node->{'slinks'}}) {
270 271
	    push @topfile, "link $link->{name} $link->{src} $link->{dst} " .
		"$link->{bw} $link->{delay} $link->{plr} " . join(" ",@{$link->{flags}}) . "\n";
272 273 274
	}
    }

275 276 277 278 279 280 281 282 283 284 285 286
    # 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";
	    }
	}
    }
    

287 288 289
    return @topfile;
}

290 291 292 293 294 295 296 297 298 299 300 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 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
#
# 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) {
	    /^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;

		    # 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);
}

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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
#
# 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
    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>) {
472
	chomp;
473 474 475 476 477 478 479
	/^End Nodes$/ && last;
	my @info = split;
	my ($virtual,$physical) = @info[0,1];
	push @nodes, [$virtual, $physical];
    }

    #
480
    # Find the edges
481 482 483 484
    #
    my @edges;
    while (<SOL> !~ /^Edges:/) { }
    while (<SOL>) {
485
	chomp;
486
	/^End Edges$/ && last;
487
	my ($name, $type, @plinks) = split /\s+/,$_;
488 489 490 491 492 493 494 495 496 497 498
	
	#
	# 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];
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
    }
    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";

525 526 527 528 529 530 531 532 533 534
    #
    # 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;
	}
    }

535
    print "Edges:\n";
536
    foreach my $edge (@$edges) {
537 538
	my ($name, $type, $pairs) = @$edge;
	my @pairs = @$pairs;
539 540
	my @real_virtlinks = list_links($links{$name});
	foreach my $real_virtlink (@real_virtlinks) {
541
	    print "$real_virtlink->{name} $type ";
542 543

	    my @ordered_pairs;
544
	    if (!$real_virtlink->{'reversed'}) {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
		@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";
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
    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;
}

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
#
# 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);
}

652 653 654
#
# More complex coarsener that uses METIS to partition up the graph
#
655 656 657
sub do_metis($) {
    my ($nodes) = @_;

658 659 660 661 662 663 664
    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";
665

666
	my $packing_factor = $::colocate{$type};
667

668 669 670 671
	push @nodelists,
	    run_metis(\@metisfile,$nodelist,$metisfilename,$metislog,
		$packing_factor);
    }
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

    #
    # 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;

}

688 689 690 691 692 693 694 695 696 697 698 699
#
# 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};
}

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
#
# 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;
}

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
#####
##### 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'}}) {
738 739 740 741 742 743
	    #
	    # Ignore links whose other end is not in our set of links
	    #
	    if ($nodes->{$link->{'dst'}}) {
		$link->{'metis_id'} = ++$link_count;
	    }
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
	}
    }

    #
    # 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'}) {
763 764
		# Other end of this link is not in our set of nodes, ignore it
		next;
765 766 767 768 769
	    }
	    push @neighbors, $nodes->{$link->{'dst'}}{'metis_id'};
	}
	foreach my $link (@{$node->{'dlinks'}}) {
	    if (!$link->{'metis_id'}) {
770 771
		# Other end of this link is not in our set of nodes, ignore it
		next;
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
	    }
	    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;
    }
795
    close(FH);
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

    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
#
811 812 813
sub run_metis($$$$;$) {
    my ($metisfile,$nodes,$metisfilename,$metislogfile,$colocate) = @_;
    print "run_metis called with colocate of $colocate\n";
814

815 816
    # Pick a number of partitions such that the average parition size
    # will be $AVG_NODES_PER_PARTITION
817 818 819 820 821 822
    my $npart;
    if ($colocate) {
	$npart = POSIX::ceil(scalar(keys %$nodes) / $colocate);
    } else {
	$npart = POSIX::ceil(scalar(keys %$nodes) /$AVG_NODES_PER_PARTITION);
    }
823 824 825 826
    if ($npart <= 1) {
	# No point in running METIS, just give the list of nodes back
	return [values(%$nodes)];
    }
827 828 829 830 831 832 833

    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";
834 835
    print "$METIS $metisfilename $npart > $metislogfile 2>&1\n";
    if (!system "$METIS $metisfilename $npart > $metislogfile 2>&1") {
836 837 838 839 840 841
	die "kmetis failed!\n";
    }

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

842 843 844 845 846 847 848 849 850 851 852 853
#####
##### 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) {
854
	return @nodes;
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    }

    # 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
878
	    $conglomerate = new_conglomerate($node);
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
	    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
894 895 896 897 898 899 900 901 902 903 904 905 906
	    # 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);
907
		    }
908 909 910 911 912
		    $conglomerate->{'desires'}{$name} = $newweight;
		} else {
		    # If we made it here, we must not have found an existing
		    # desire that matched
		    $conglomerate->{'desires'}{$name} = $weight;
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
		}
	    }
	
	    # 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;

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
	    # 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'};
	    }
	}
950 951 952 953 954 955 956 957 958 959 960 961
    }

    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) = @_;

962 963 964 965 966
    # 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'}) &&
967 968 969 970
	($node->{'fixed'} ne $conglomerate->{'fixed'})) {
	return 0;
    }

971 972
    my $type = $node->{'type'};

973
    # Can't conglomerate nodes of different types
974
    if ($type ne $conglomerate->{'type'}) {
975 976 977 978 979 980
	return 0;
    }

    #
    # Can't go over the colocate factor
    #
981
    my $colocate = $::colocate{$type};
982 983 984
    if (!$colocate) {
	die "Don't know colocate factor for $node->{type}\n";
    }
985 986 987
    if (defined $max_multiplex_factor && ($colocate > $max_multiplex_factor)) {
	$colocate = $max_multiplex_factor;
    }
988 989 990 991 992 993 994
    if (($node->{'count'} + $conglomerate->{'count'}) > $colocate) {
	return 0;
    }

    #
    # Check to see if we're going over for any additive local features
    #
995 996 997 998 999 1000 1001 1002 1003
    
    # 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};
1004 1005 1006
	if (exists $::additive_features{$type} &&
	    exists $::additive_features{$type}{$name} &&
	    (($old_weight + $new_weight) > $::additive_features{$type}{$name})) {
1007 1008 1009 1010
		return 0;
	}
    }

1011 1012 1013 1014 1015
    #
    # 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'}}) {
1016
	#print "Checking $link->{'dst'} against $conglomerate->{'name'} and $node->{'name'}\n";
1017 1018 1019 1020 1021 1022
	if (($link->{'dst'} eq $conglomerate->{'name'}) ||
	    ($link->{'dst'} eq $node->{'name'})) {
	    $self_link_bandwidth += $link->{'bw'};
	}
    }
    foreach my $link (@{$node->{'slinks'}}) {
1023
	#print "Checking $link->{'dst'} against $conglomerate->{'name'} and $node->{'name'}\n";
1024 1025 1026 1027 1028
	if (($link->{'dst'} eq $conglomerate->{'name'}) ||
	    ($link->{'dst'} eq $node->{'name'})) {
	    $self_link_bandwidth += $link->{'bw'};
	}
    }
1029

1030
    if ($::trivialbw{$type} && $self_link_bandwidth > $::trivialbw{$type}) {
1031 1032 1033 1034 1035
	return 0;
    }


    return 1;
1036 1037 1038 1039 1040 1041
}

#
# Create a new conglomerate, starting from an existing node
#
my $conglomerate_count = 0;
1042
sub new_conglomerate($) {
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    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'};
1053
    $conglomerate{'desires'} = \%{$node->{'desires'}};
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    $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'};

1072 1073 1074 1075
    if ($node->{'hint'}) {
	$conglomerate{'hint'} = $node->{'hint'};
    }

1076 1077 1078 1079
    return \%conglomerate;

}

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
#
# 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
1099
	    my ($csrc, $cdst) = sort { $a cmp $b } ($src, $dst);
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 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
	    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'};

1197 1198 1199 1200 1201
	    # 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;
	    }
1202 1203 1204 1205 1206

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

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
	}
    }

    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;
}
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

#####
##### 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;
}

1249 1250 1251 1252 1253 1254 1255
#
# Similar to above, but for links.
#
sub list_links($) {
    my ($virtual) = @_;
    my @linklist = ();
    if (!@{$virtual->{'links'}}) {
1256
	return ($virtual);
1257 1258 1259 1260 1261 1262 1263 1264
    } else {
	foreach my $link (@{$virtual->{'links'}}) {
	    push @linklist, list_links($link);
	}
    }
    return @linklist;
}

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
#
# 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 {
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
	# 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;
	    }
	}

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
	if ($b->{'desires'} && $b->{'desires'}{'?+cpupercent'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+cpupercent'}) {

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

1305
	# Then by memory
1306 1307
	if ($b->{'desires'} && $b->{'desires'}{'?+ram'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+ram'}) {
1308

1309
	    $rv = ( $b->{'desires'}{'?+ram'} <=> $a->{'desires'}{'?+ram'} );
1310 1311 1312 1313 1314
	    if ($rv != 0) {
		return $rv;
	    }
	}
	
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
	if ($b->{'desires'} && $b->{'desires'}{'?+rampercent'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+rampercent'}) {

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

1325 1326
	# Fall back to count if neither of the others were given
	return $b->{'count'} <=> $a->{'count'};
1327 1328 1329
    } @_;
}

1330 1331 1332 1333 1334 1335
sub binpack_link_sort(@) {
    return sort {
	$b->{'bw'} <=> $a->{'bw'} 
    } @_;
}

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

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