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

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

use strict;
13
use POSIX;
Robert Ricci's avatar
Robert Ricci committed
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";
Robert Ricci's avatar
Robert Ricci committed
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;
Robert Ricci's avatar
Robert Ricci committed
34 35 36 37

#
# Figure out assign args
#
38 39 40
if (@ARGV < 2) {
    die "Usage: $0 [assign args] ptopfile topfile\n";
}
Robert Ricci's avatar
Robert Ricci committed
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;
    }
}
Robert Ricci's avatar
Robert Ricci committed
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
}

Robert Ricci's avatar
Robert Ricci committed
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);
Robert Ricci's avatar
Robert Ricci committed
92 93 94 95 96 97 98

#
# Run assign
#

# Make a filename for our coarsened topfile
my $tmp_topfile = $topfile;
99
$tmp_topfile =~ s/(\.v?top)?$/-coarsened$1/;
Robert Ricci's avatar
Robert Ricci committed
100

101
print "Generating new topfile\n";
Robert Ricci's avatar
Robert Ricci committed
102
my @topfile = generate_topfile($newgraph);
103
print "Running assign\n";
Robert Ricci's avatar
Robert Ricci committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
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) {
136
	    (/^node$/) && do {
Robert Ricci's avatar
Robert Ricci committed
137 138 139 140 141 142 143 144 145 146
		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;
		}

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

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

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

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

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

241 242
   close TOP;

Robert Ricci's avatar
Robert Ricci committed
243 244 245 246 247 248 249 250
   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
#
251 252
sub generate_topfile($;$) {
    my ($nodes,$fixed) = @_;
Robert Ricci's avatar
Robert Ricci committed
253
    my @topfile;
254

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

    # Print out the links
    foreach my $node (values %$nodes) {
	foreach my $link (@{$node->{'slinks'}}) {
274 275
	    push @topfile, "link $link->{name} $link->{src} $link->{dst} " .
		"$link->{bw} $link->{delay} $link->{plr} " . join(" ",@{$link->{flags}}) . "\n";
Robert Ricci's avatar
Robert Ricci committed
276 277 278
	}
    }

279 280 281 282 283 284 285 286 287 288 289 290
    # 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";
	    }
	}
    }
    

Robert Ricci's avatar
Robert Ricci committed
291 292 293
    return @topfile;
}

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
#
# 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) {
322 323 324 325
	    /^set-type-limit$/ && do {
		# Skip these.
		last;
	    };
326 327 328 329 330 331 332 333 334 335
	    /^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;

336 337 338 339 340
                    # 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/^\*//;

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		    # 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);
}

Robert Ricci's avatar
Robert Ricci committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
#
# 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
436
    print "assign completed\n";
Robert Ricci's avatar
Robert Ricci committed
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 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    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>) {
486
	chomp;
Robert Ricci's avatar
Robert Ricci committed
487 488 489 490 491 492 493
	/^End Nodes$/ && last;
	my @info = split;
	my ($virtual,$physical) = @info[0,1];
	push @nodes, [$virtual, $physical];
    }

    #
494
    # Find the edges
Robert Ricci's avatar
Robert Ricci committed
495 496 497 498
    #
    my @edges;
    while (<SOL> !~ /^Edges:/) { }
    while (<SOL>) {
499
	chomp;
Robert Ricci's avatar
Robert Ricci committed
500
	/^End Edges$/ && last;
501
	my ($name, $type, @plinks) = split /\s+/,$_;
502 503 504 505 506 507 508 509 510 511 512
	
	#
	# 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];
Robert Ricci's avatar
Robert Ricci committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    }
    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";

539 540 541 542 543 544 545 546 547 548
    #
    # 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;
	}
    }

Robert Ricci's avatar
Robert Ricci committed
549
    print "Edges:\n";
550
    foreach my $edge (@$edges) {
551 552
	my ($name, $type, $pairs) = @$edge;
	my @pairs = @$pairs;
553 554
	my @real_virtlinks = list_links($links{$name});
	foreach my $real_virtlink (@real_virtlinks) {
555
	    print "$real_virtlink->{name} $type ";
556 557

	    my @ordered_pairs;
558
	    if (!$real_virtlink->{'reversed'}) {
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
		@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";
574 575
	}
    }
Robert Ricci's avatar
Robert Ricci committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
    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;
}

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
#
# 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);
}

666 667 668
#
# More complex coarsener that uses METIS to partition up the graph
#
669 670 671
sub do_metis($) {
    my ($nodes) = @_;

672 673 674 675 676 677 678
    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";
679

680
	my $packing_factor = $::colocate{$type};
681

682 683 684 685
	push @nodelists,
	    run_metis(\@metisfile,$nodelist,$metisfilename,$metislog,
		$packing_factor);
    }
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

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

}

702 703 704 705 706 707 708 709 710 711 712 713
#
# 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};
}

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
#
# 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;
}

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
#####
##### 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'}}) {
752 753 754 755 756 757
	    #
	    # Ignore links whose other end is not in our set of links
	    #
	    if ($nodes->{$link->{'dst'}}) {
		$link->{'metis_id'} = ++$link_count;
	    }
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
	}
    }

    #
    # 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'}) {
777 778
		# Other end of this link is not in our set of nodes, ignore it
		next;
779 780 781 782 783
	    }
	    push @neighbors, $nodes->{$link->{'dst'}}{'metis_id'};
	}
	foreach my $link (@{$node->{'dlinks'}}) {
	    if (!$link->{'metis_id'}) {
784 785
		# Other end of this link is not in our set of nodes, ignore it
		next;
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
	    }
	    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;
    }
809
    close(FH);
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

    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
#
825 826
sub run_metis($$$$;$) {
    my ($metisfile,$nodes,$metisfilename,$metislogfile,$colocate) = @_;
827 828 829 830

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

833 834
    # Pick a number of partitions such that the average parition size
    # will be $AVG_NODES_PER_PARTITION
835
    my $npart = POSIX::ceil(scalar(keys %$nodes) / $colocate);
836 837 838 839
    if ($npart <= 1) {
	# No point in running METIS, just give the list of nodes back
	return [values(%$nodes)];
    }
840 841 842 843 844 845 846

    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";
847 848
    print "$METIS $metisfilename $npart > $metislogfile 2>&1\n";
    if (!system "$METIS $metisfilename $npart > $metislogfile 2>&1") {
849 850 851 852 853 854
	die "kmetis failed!\n";
    }

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

Robert Ricci's avatar
Robert Ricci committed
855 856 857 858 859 860 861 862 863 864 865 866
#####
##### 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) {
867
	return @nodes;
Robert Ricci's avatar
Robert Ricci committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    }

    # 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
891
	    $conglomerate = new_conglomerate($node);
Robert Ricci's avatar
Robert Ricci committed
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
	    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
907 908 909 910 911 912 913 914 915 916 917 918 919
	    # 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);
Robert Ricci's avatar
Robert Ricci committed
920
		    }
921 922 923 924 925
		    $conglomerate->{'desires'}{$name} = $newweight;
		} else {
		    # If we made it here, we must not have found an existing
		    # desire that matched
		    $conglomerate->{'desires'}{$name} = $weight;
Robert Ricci's avatar
Robert Ricci committed
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
		}
	    }
	
	    # 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;

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
	    # 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'};
	    }
	}
Robert Ricci's avatar
Robert Ricci committed
963 964 965 966 967 968 969 970 971 972 973 974
    }

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

975 976 977 978 979
    # 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'}) &&
Robert Ricci's avatar
Robert Ricci committed
980 981 982 983
	($node->{'fixed'} ne $conglomerate->{'fixed'})) {
	return 0;
    }

984 985
    my $type = $node->{'type'};

Robert Ricci's avatar
Robert Ricci committed
986
    # Can't conglomerate nodes of different types
987
    if ($type ne $conglomerate->{'type'}) {
Robert Ricci's avatar
Robert Ricci committed
988 989 990 991 992 993
	return 0;
    }

    #
    # Can't go over the colocate factor
    #
994
    my $colocate = $::colocate{$type};
995
    if (!$colocate) {
996 997 998 999
	print "Don't know colocate factor for $node->{type}\n";
	return 0;

	#die "Don't know colocate factor for $node->{type}\n";
1000
    }
1001 1002 1003
    if (defined $max_multiplex_factor && ($colocate > $max_multiplex_factor)) {
	$colocate = $max_multiplex_factor;
    }
Robert Ricci's avatar
Robert Ricci committed
1004 1005 1006 1007 1008 1009 1010
    if (($node->{'count'} + $conglomerate->{'count'}) > $colocate) {
	return 0;
    }

    #
    # Check to see if we're going over for any additive local features
    #
1011 1012 1013 1014 1015 1016 1017 1018 1019
    
    # 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};
1020 1021 1022
	if (exists $::additive_features{$type} &&
	    exists $::additive_features{$type}{$name} &&
	    (($old_weight + $new_weight) > $::additive_features{$type}{$name})) {
Robert Ricci's avatar
Robert Ricci committed
1023 1024 1025 1026
		return 0;
	}
    }

1027 1028 1029 1030 1031
    #
    # 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'}}) {
1032
	#print "Checking $link->{'dst'} against $conglomerate->{'name'} and $node->{'name'}\n";
1033 1034 1035 1036 1037 1038
	if (($link->{'dst'} eq $conglomerate->{'name'}) ||
	    ($link->{'dst'} eq $node->{'name'})) {
	    $self_link_bandwidth += $link->{'bw'};
	}
    }
    foreach my $link (@{$node->{'slinks'}}) {
1039
	#print "Checking $link->{'dst'} against $conglomerate->{'name'} and $node->{'name'}\n";
1040 1041 1042 1043 1044
	if (($link->{'dst'} eq $conglomerate->{'name'}) ||
	    ($link->{'dst'} eq $node->{'name'})) {
	    $self_link_bandwidth += $link->{'bw'};
	}
    }
Robert Ricci's avatar
Robert Ricci committed
1045

1046
    if ($::trivialbw{$type} && $self_link_bandwidth > $::trivialbw{$type}) {
1047 1048 1049 1050 1051
	return 0;
    }


    return 1;
Robert Ricci's avatar
Robert Ricci committed
1052 1053 1054 1055 1056 1057
}

#
# Create a new conglomerate, starting from an existing node
#
my $conglomerate_count = 0;
1058
sub new_conglomerate($) {
Robert Ricci's avatar
Robert Ricci committed
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    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'};
1069
    $conglomerate{'desires'} = \%{$node->{'desires'}};
Robert Ricci's avatar
Robert Ricci committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    $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'};

1088 1089 1090 1091
    if ($node->{'hint'}) {
	$conglomerate{'hint'} = $node->{'hint'};
    }

Robert Ricci's avatar
Robert Ricci committed
1092 1093 1094 1095
    return \%conglomerate;

}

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
#
# 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
1115
	    my ($csrc, $cdst) = sort { $a cmp $b } ($src, $dst);
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 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
	    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'};

1213 1214 1215 1216 1217
	    # 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;
	    }
1218 1219 1220 1221 1222

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

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
	}
    }

    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;
}
Robert Ricci's avatar
Robert Ricci committed
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264

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

1265 1266 1267 1268 1269 1270 1271
#
# Similar to above, but for links.
#
sub list_links($) {
    my ($virtual) = @_;
    my @linklist = ();
    if (!@{$virtual->{'links'}}) {
1272
	return ($virtual);
1273 1274 1275 1276 1277 1278 1279 1280
    } else {
	foreach my $link (@{$virtual->{'links'}}) {
	    push @linklist, list_links($link);
	}
    }
    return @linklist;
}

Robert Ricci's avatar
Robert Ricci committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
#
# 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 {
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
	# 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;
	    }
	}

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
	if ($b->{'desires'} && $b->{'desires'}{'?+cpupercent'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+cpupercent'}) {

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

1321
	# Then by memory
1322 1323
	if ($b->{'desires'} && $b->{'desires'}{'?+ram'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+ram'}) {
1324

1325
	    $rv = ( $b->{'desires'}{'?+ram'} <=> $a->{'desires'}{'?+ram'} );
1326 1327 1328 1329 1330
	    if ($rv != 0) {
		return $rv;
	    }
	}
	
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
	if ($b->{'desires'} && $b->{'desires'}{'?+rampercent'} &&
	    $a->{'desires'} && $a->{'desires'}{'?+rampercent'}) {

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

1341 1342
	# Fall back to count if neither of the others were given
	return $b->{'count'} <=> $a->{'count'};
Robert Ricci's avatar
Robert Ricci committed
1343 1344 1345
    } @_;
}

1346 1347 1348 1349 1350 1351
sub binpack_link_sort(@) {
    return sort {
	$b->{'bw'} <=> $a->{'bw'} 
    } @_;
}

Robert Ricci's avatar
Robert Ricci committed
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361

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