libGeni.pm.in 66.6 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2009, 2010, 2011 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
# Merge internet nodes and links to them. 
#
26 27 28 29 30 31 32 33 34 35 36 37
package libGeni;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw();

# Configure variables
my $TB		= "@prefix@";
my $BOSSNODE    = "@BOSSNODE@";
38 39
my $TBDOCBASE   = "@TBDOCBASE@";
#my $TBDOCBASE   = "http://www.emulab.net";
40
my $ELVIN_COMPAT= @ELVIN_COMPAT@;
41
my $ASSIGN	= "$TB/libexec/assign";
42 43 44 45 46 47 48 49

use libdb;
use libtestbed;
use emutil;
use NodeType;
use Interface;
use Experiment;
use OSinfo;
50
use Lan;
Leigh Stoller's avatar
Leigh Stoller committed
51
use GeniEmulabUtil;
52
use GeniResource;
53
use GeniResponse;
54
use GeniAuthority;
55
use GeniXML;
56 57
use English;
use Socket;
58
use XML::Simple;
59 60
use XML::LibXML;
use XML::SemanticDiff;
61
use Data::Dumper;
62
use File::Temp;
Leigh Stoller's avatar
Leigh Stoller committed
63
use IO::File;
64
use POSIX qw(strftime);
65 66 67 68 69

sub Register($$)
{
    my ($experiment, $user) = @_;

Leigh Stoller's avatar
Leigh Stoller committed
70
    return GeniEmulabUtil::RegisterExperiment($experiment, $user);
71 72 73 74 75 76
}

sub UnRegister($)
{
    my ($experiment) = @_;

Leigh Stoller's avatar
Leigh Stoller committed
77
    return GeniEmulabUtil::UnRegisterExperiment($experiment);
78 79
}

80
sub RenewSlivers($;$)
Leigh Stoller's avatar
Leigh Stoller committed
81
{
82 83 84
    my ($experiment, $force) = @_;

    return GeniResource::RenewExperimentResources($experiment, $force);
Leigh Stoller's avatar
Leigh Stoller committed
85 86
}

87 88 89
#
# Map rspec to resources using assign. 
#
90
sub MapResources($$$$$)
91
{
92 93 94 95 96 97 98 99
    my ($experiment, $user, $topo, $rspecref, $verbose) = @_;
    my %cmurn2res   = ();
    my %cmurn2nodes = ();
    my %cmurn2links = ();
    my %cmurn2frags = ();
    my %vname2res   = ();
    my %vname2doc   = ();
	
100 101 102
    Register($experiment, $user) == 0
	or return -1;

103 104 105 106 107 108 109 110 111
    #
    # Build up rspec fragments from the "intermediate" representation
    # that libvtop passed in. Ick.
    #
    foreach my $ref (@{ $topo->{'node'} }) {
	# Skip non geni nodes; handled in libvtop
	next
	    if (! (exists($ref->{'isgeninode'}) && $ref->{'isgeninode'}));
	
112
	my $resource;
113 114 115 116
	my $node_urn    = $ref->{'request_urn'};
	my $manager_urn = $ref->{'manager_urn'};
	my $virtual_id  = $ref->{'virtual_id'};
	my (undef,undef,$node_id) = GeniHRN::Parse($node_urn);
Leigh Stoller's avatar
Leigh Stoller committed
117
	
118 119 120
	#
	# Get the resource object.
	#
121 122
	if (!exists($cmurn2res{$manager_urn})) {
	    $resource = GeniResource->Lookup($experiment->idx(), $manager_urn);
123
	    if (!defined($resource)) {
124
		$resource = GeniResource->Create($experiment, $manager_urn);
125
		if (!defined($resource)) {
126 127
		    print STDERR
			"Could not create GeniResource for $manager_urn\n";
128 129 130
		    return -1;
		}
	    }
131
	    $cmurn2res{$manager_urn} = $resource;
132
	}
133 134
	$resource = $cmurn2res{$manager_urn};
	$vname2res{$virtual_id} = $resource;
135 136 137 138 139 140 141

	#
	# The point of this is to split the rspec apart, since at present
	# assign cannot handle multiple advertisements, and it will not work
	# to pass in an rspec that references CMs other then the one
	# advertisement being passed in.
	#
142 143
	my $fragment;
	if (!exists($cmurn2frags{$manager_urn})) {
144
	    $fragment = CreateNewRspec("request");
145 146 147 148 149 150 151 152 153 154 155
	    return -1
		if (!defined($fragment));

	    $cmurn2frags{$manager_urn} = $fragment;
	}
	$fragment = $cmurn2frags{$manager_urn};

	my $rspecdoc = AddNodeToRspec($fragment, $ref);
	return -1
	    if (!defined($rspecdoc));
	$vname2doc{$virtual_id} = $rspecdoc;
156
    }
157

158 159 160
    #
    # As above, need to split the interfaces into the correct fragments.
    #
161 162
    if (exists($topo->{'link'})) {
	foreach my $ref (@{ $topo->{'link'} }) {
163 164
	    my $linkname   = $ref->{'virtual_id'};

165 166 167 168 169
	    # Skip tunnels until rspec stitching in place.
	    next
		if (exists($ref->{'link_type'}) &&
		    $ref->{'link_type'} eq "tunnel");

170 171 172 173 174 175
	    my $ifaceref0 = $ref->{'interface_ref'}->[0];
	    my $ifaceref1 = $ref->{'interface_ref'}->[1];
	    # Do not want to add this twice.
	    my $virtid0   = $ifaceref0->{'virtual_node_id'};
	    my $resource0 = $vname2res{$virtid0};
	    my $fragment0 = $cmurn2frags{$resource0->manager_urn()};
176

177 178 179 180 181 182 183 184 185 186 187 188 189
	    my $rspecdoc = AddLinkToRspec($fragment0, $ref);
	    return -1
		if (!defined($rspecdoc));
	    # Only one of these in the array, for building combined rspec.
	    $vname2doc{$linkname} = $rspecdoc;
	    
	    my $virtid1   = $ifaceref1->{'virtual_node_id'};
	    my $resource1 = $vname2res{$virtid1};
	    my $fragment1 = $cmurn2frags{$resource1->manager_urn()};
	    if ($resource0->manager_urn() ne $resource1->manager_urn()) {
		$rspecdoc = AddLinkToRspec($fragment1, $ref);
		return -1
		    if (!defined($rspecdoc));
190 191 192
	    }
	}
    }
193 194
    if ($verbose) {
	print STDERR "Rspec Fragments:\n";
195

196 197 198 199 200 201
	foreach my $fragment (values(%cmurn2frags)) {
	    my $rspecstr = GeniXML::Serialize($fragment, 1);
	    print STDERR "$rspecstr\n";
	}
    }
    
202
    #
203 204
    # Discover resources in parallel and run assign, writing the solution
    # to a file.
205
    #
206 207
    my $coderef   = sub {
	my ($resource, $fragment, $tmp) = @{ $_[0] };
208 209 210 211 212 213 214
	my $advertisement;

	print STDERR "Asking for resource list from $resource\n";
	if ($resource->Discover($user, \$advertisement)) {
		print STDERR "Could not get resource list for $resource\n";
		return -1;
	}
215 216 217 218 219
	#
	# Is the advertisement from a non-conforming manager, such as the SFA?
	# If so, must convert it to something assign can grok.
	#
	if ($resource->IsSFA()) {
220 221
	    $advertisement = ConvertSFAtoPG($advertisement, "ad",
					    $resource->manager_urn());
222 223 224 225 226
	    return -1
		if (!defined($advertisement));
	    $advertisement = GeniXML::Serialize($advertisement, 1);
	}
	
Leigh Stoller's avatar
Leigh Stoller committed
227 228 229 230
	my $soln = $tmp . ".soln";
	my $log  = $tmp . ".log";
	my $ptop = $tmp . ".ptop";
	my $vtop = $tmp . ".vtop";
231

232
	my $reqstring = GeniXML::Serialize($fragment);
Leigh Stoller's avatar
Leigh Stoller committed
233 234 235 236 237 238 239 240 241 242 243
	my $vtopfh = new IO::File "> $vtop";
	my $ptopfh = new IO::File "> $ptop";
	if (! (defined($vtopfh) && defined($ptopfh))) {
	    print STDERR "Could not create temporary files for ptop/vtop\n";
	    return -1;
	}
	print $vtopfh $reqstring;
	print $ptopfh $advertisement;
	$vtopfh->close();
	$ptopfh->close();

Leigh Stoller's avatar
Leigh Stoller committed
244 245 246 247 248 249
	my $cmd = "nice $ASSIGN -uod -c .75 ".
	    "-f rspec/rspec -W $soln $ptop $vtop > $log 2>&1";
	if ($verbose) {
	    print STDERR "$cmd\n";
	}
	system($cmd);
Leigh Stoller's avatar
Leigh Stoller committed
250
	
251 252
	if ($?) {
	    print STDERR "Could not map to physical resources on $resource\n";
253 254
	    my $logstuff = `cat $log`;
	    print STDERR "\n" . $logstuff . "\n";
255 256
	    my $string = GeniXML::Serialize($fragment, 1);
	    print STDERR "$string\n";
257 258
	    return -1;
	}
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	return 0;
    };

    #
    # Figure out which resources still need to be mapped. 
    #
    my @todo     = ();
    my @results = ();

    foreach my $manager_urn (keys(%cmurn2res)) {
	my $resource = $cmurn2res{$manager_urn};
	my $fragment = $cmurn2frags{$manager_urn};

	#
	# We got the ticket on a previous loop.
	#
	if ($resource->HaveTicket()) {
	    print STDERR "Already have a ticket for $resource; skipping ...\n";
	    next;
	}
	my $tmp  = File::Temp::mktemp("XXXXX");
	push(@todo, [$resource, $fragment, $tmp]);
    }

    print STDERR "Mapping resources in parallel ...\n";
    if (ParRun({'maxwaittime' => 600, 'maxchildren' => 4},
	       \@results, $coderef, @todo)) {
	print STDERR "*** MapResources: Internal error mapping resources\n";
	return -1;
    }
    
    #
    # Check the exit codes. 
    #
    my $errors   = 0;
    my $count    = 0;
    foreach my $result (@results) {
	my ($resource, $fragment, $tmp) = @{ $todo[$count] };

	#
	# ParRun does a fork; so need to refresh the resource object
	# to sync it to the DB.
	#
	if ($resource->Refresh()) {
	    print STDERR "*** MapResources: Error synchronizing $resource\n";
	    $errors++;
	}
	elsif ($result != 0) {
	    print STDERR "*** Error mapping resources for $resource\n";
	    $errors++;
	}
	$count++;
    }
    return -1
	if ($errors);
    
    #
    # Since everything mapped, read the solutions and write back to the rspec
    #
    foreach my $ref (@todo) {
	my ($resource, $fragment, $tmp) = @{ $ref };
	my $soln = $tmp . ".soln";
	
322
	my $solution =
Leigh Stoller's avatar
Leigh Stoller committed
323
	    eval { XMLin($soln, KeyAttr => [],
324
			 ForceArray => ["node", "link", "interface",
325 326
					"interface_ref", "linkendpoints",
					"component_manager"]) };
327
	if ($@) {
Leigh Stoller's avatar
Leigh Stoller committed
328
	    print STDERR "XMLin error reading $soln: $@\n";
329 330
	    return -1;
	}
331 332 333 334
	if ($verbose) {
	    print STDERR "Solution for $resource\n";
	    print STDERR Dumper($solution);
	}
335 336 337

	foreach my $ref (@{ $solution->{'node'} }) {
	    my $virtual_id = $ref->{'virtual_id'};
338
	    my $node_urn   = $ref->{'component_uuid'};
339
	    my $cm_urn     = $ref->{'component_manager_uuid'};
340
	    my $rspecdoc   = $vname2doc{$virtual_id};
341

Leigh Stoller's avatar
Leigh Stoller committed
342
	    #
343
	    # This writes the solution back into the fragment.
Leigh Stoller's avatar
Leigh Stoller committed
344
	    #
345 346 347 348
	    $rspecdoc->setAttribute("component_uuid", $node_urn);
	    $rspecdoc->setAttribute("component_urn", $node_urn);
	    $rspecdoc->setAttribute("component_manager_uuid", $cm_urn);
	    $rspecdoc->setAttribute("component_manager_urn", $cm_urn);
349

350 351 352 353
	    if (exists($ref->{'interface'})) {
		my $interfaces = $ref->{'interface'};

		foreach my $ifaceref (@{ $interfaces }) {
354 355
		    my $virtid = $ifaceref->{'virtual_id'};
		    my $compid = $ifaceref->{'component_id'};
356

357 358 359 360 361
		    # Not supposed to happen, but does cause of issues
		    # with tunnels and rspec stitching. 
		    next
			if (!defined($compid));

362 363 364 365 366
		    foreach my $linkref (GeniXML::FindNodes("n:interface",
						$rspecdoc)->get_nodelist()) {
			my $ovirtid = GeniXML::GetText("virtual_id", $linkref);
			if ($ovirtid eq $virtid) {
			    $linkref->setAttribute("component_id", $compid);
367 368 369 370 371 372 373
			    last;
			}
		    }
		}
	    }
	}
    }
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
    #
    # One last chore; we had to skip tunnels above since assign does
    # not know how to deal with them.
    #
    if (exists($topo->{'link'})) {
	foreach my $ref (@{ $topo->{'link'} }) {
	    my $linkname   = $ref->{'virtual_id'};

	    # Skip non-tunnels.
	    next
		if (! (exists($ref->{'link_type'}) &&
		       $ref->{'link_type'} eq "tunnel"));

	    my $ifaceref0 = $ref->{'interface_ref'}->[0];
	    my $ifaceref1 = $ref->{'interface_ref'}->[1];
	    # Do not want to add this twice.
	    my $virtid0   = $ifaceref0->{'virtual_node_id'};
	    my $resource0 = $vname2res{$virtid0};
	    my $fragment0 = $cmurn2frags{$resource0->manager_urn()};

	    my $rspecdoc = AddLinkToRspec($fragment0, $ref);
	    return -1
		if (!defined($rspecdoc));
	    # Only one of these in the array, for building combined rspec.
	    $vname2doc{$linkname} = $rspecdoc;
	    
	    my $virtid1   = $ifaceref1->{'virtual_node_id'};
	    my $resource1 = $vname2res{$virtid1};
	    my $fragment1 = $cmurn2frags{$resource1->manager_urn()};
	    if ($resource0->manager_urn() ne $resource1->manager_urn()) {
		$rspecdoc = AddLinkToRspec($fragment1, $ref);
		return -1
		    if (!defined($rspecdoc));
407 408 409 410
	    }
	}
    }

411 412 413 414 415 416 417
    #
    # Compare to previous rspec; this tells us if we need to request
    # a new ticket. Easier to use the rspec then the manifest since
    # the CM added a ton of cruft to it.
    #
    foreach my $manager_urn (keys(%cmurn2res)) {
	my $resource = $cmurn2res{$manager_urn};
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
	# We got the ticket on a previous loop.
	next
	    if ($resource->HaveTicket());

	my $fragment    = $cmurn2frags{$manager_urn};
	my $frag_string = GeniXML::Serialize($fragment);
	# Must stash for redeemticket.
	$resource->stashrspec($frag_string);
	
	next
	    if (! $resource->HaveRspec());

	#
	# The idea is to do a diff of the rspec. If there are no
	# meaningful changes, then we can skip trying to get a new
	# ticket.
	#
	my $rspec    = $resource->Rspec();
	my $diff     = XML::SemanticDiff->new();
	my $rspec_string = GeniXML::Serialize($rspec);
	$resource->setmodified(0);

	print STDERR "Comparing old and new rspecs for $resource\n"; 
	foreach my $change ($diff->compare($rspec_string, $frag_string)) {
	    print STDERR " $change->{message} in context $change->{context}\n";
	    $resource->setmodified(1);
	}
446
	if ($resource->modified() && $resource->ApiLevel() == 0) {
447 448 449
	    print STDERR "*** Difference to rspec for level 0 $resource. ".
		"Not allowed, aborting\n";
	    return -1;
450
	}
451
    }
452 453 454 455

    #
    # Combine the fragments into final rspec document.
    #
456
    my $rspec = CombineRspecDocs("request", values(%vname2doc));
457 458 459 460 461 462 463 464 465 466 467 468
    return -1
	if (!defined($rspec));

    # Make sure all that namespace stuff is done correctly. 
    $rspec = GeniXML::Parse(GeniXML::Serialize($rspec));
    
    if ($verbose) {
	print STDERR "Final rspec:\n";
	my $rspecstr = GeniXML::Serialize($rspec, 1);
	print STDERR "$rspecstr\n";
    }
    $$rspecref = $rspec;
469 470 471
    return 0;
}

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 503 504 505 506 507 508 509 510 511 512 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 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 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
sub MapResourcesNew($$$$$)
{
    my ($experiment, $user, $topo, $rspecref, $verbose) = @_;
    my %cmurn2res   = ();
    my %cmurn2links = ();
    my %cmurn2frags = ();
    my %vname2res   = ();
    my %vname2doc   = ();
    my %nodes2cmurn = ();
	
    Register($experiment, $user) == 0
	or return -1;

    #
    # Build up rspec fragments from the "intermediate" representation
    # that libvtop passed in. Ick.
    #
    foreach my $ref (@{ $topo->{'node'} }) {
	# Skip non geni nodes; handled in libvtop
	next
	    if (! (exists($ref->{'isgeninode'}) && $ref->{'isgeninode'}));
	
	my $resource;
	my $node_urn    = $ref->{'request_urn'};
	my $manager_urn = $ref->{'manager_urn'};
	my $virtual_id  = $ref->{'virtual_id'};
	my (undef,undef,$node_id) = GeniHRN::Parse($node_urn);
	
	#
	# Get the resource object.
	#
	if (!exists($cmurn2res{$manager_urn})) {
	    $resource = GeniResource->Lookup($experiment->idx(), $manager_urn);
	    if (!defined($resource)) {
		$resource = GeniResource->Create($experiment, $manager_urn);
		if (!defined($resource)) {
		    print STDERR
			"Could not create GeniResource for $manager_urn\n";
		    return -1;
		}
	    }
	    $cmurn2res{$manager_urn} = $resource;
	}
	$resource = $cmurn2res{$manager_urn};
	$vname2res{$virtual_id} = $resource;

	#
	# The point of this is to split the rspec apart, since at present
	# assign cannot handle multiple advertisements, and it will not work
	# to pass in an rspec that references CMs other then the one
	# advertisement being passed in.
	#
	my $fragment;
	if (!exists($cmurn2frags{$manager_urn})) {
	    $fragment = CreateNewRspec("request");
	    return -1
		if (!defined($fragment));

	    $cmurn2frags{$manager_urn} = $fragment;
	}
	$fragment = $cmurn2frags{$manager_urn};

	my $rspecdoc = AddNodeToRspec($fragment, $ref);
	return -1
	    if (!defined($rspecdoc));
	$vname2doc{$virtual_id} = $rspecdoc;
    }

    #
    # As above, need to split the interfaces into the correct fragments.
    #
    if (exists($topo->{'link'})) {
	foreach my $ref (@{ $topo->{'link'} }) {
	    my $linkname   = $ref->{'virtual_id'};

	    # Skip tunnels until rspec stitching in place.
	    next
		if (exists($ref->{'link_type'}) &&
		    $ref->{'link_type'} eq "tunnel");

	    my $ifaceref0 = $ref->{'interface_ref'}->[0];
	    my $ifaceref1 = $ref->{'interface_ref'}->[1];
	    # Do not want to add this twice.
	    my $virtid0   = $ifaceref0->{'virtual_node_id'};
	    my $resource0 = $vname2res{$virtid0};
	    my $fragment0 = $cmurn2frags{$resource0->manager_urn()};

	    my $rspecdoc = AddLinkToRspec($fragment0, $ref);
	    return -1
		if (!defined($rspecdoc));
	    # Only one of these in the array, for building combined rspec.
	    $vname2doc{$linkname} = $rspecdoc;
	    
	    my $virtid1   = $ifaceref1->{'virtual_node_id'};
	    my $resource1 = $vname2res{$virtid1};
	    my $fragment1 = $cmurn2frags{$resource1->manager_urn()};
	    if ($resource0->manager_urn() ne $resource1->manager_urn()) {
		$rspecdoc = AddLinkToRspec($fragment1, $ref);
		return -1
		    if (!defined($rspecdoc));
	    }
	}
    }

    #
    # Discover resources in parallel, writing the advertisement to a file.
    #
    my $coderef = sub {
	my ($resource, $tmp) = @{ $_[0] };
	my $advertisement;

	print STDERR "Asking for resource list from $resource\n";
	if ($resource->Discover($user, \$advertisement)) {
		print STDERR "Could not get resource list for $resource\n";
		return -1;
	}
	#
	# Is the advertisement from a non-conforming manager, such as the SFA?
	# If so, must convert it to something assign can grok.
	#
	if ($resource->IsSFA()) {
593 594
	    $advertisement = ConvertSFAtoPG($advertisement, "ad",
					    $resource->manager_urn());
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 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 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
	    return -1
		if (!defined($advertisement));
	    $advertisement = GeniXML::Serialize($advertisement, 1);
	}

	my $ptop   = $tmp . ".ad";
	my $ptopfh = new IO::File "> $ptop";
	if (! defined($ptopfh)) {
	    print STDERR "Could not create temporary files for ptop\n";
	    return -1;
	}
	print $ptopfh $advertisement;
	$ptopfh->close();

	return 0;
    };
    
    #
    # Get advertisements in parallel. Need to cache these for the case that the
    # resource request has not changed.
    #
    my @todo    = ();
    my @results = ();
    my $name    = time();
    my $count   = 0;

    foreach my $manager_urn (keys(%cmurn2res)) {
	my $resource = $cmurn2res{$manager_urn};

	my $tmp  = "$name-$count";
	push(@todo, [$resource, $tmp]);
	$count++;
    }
    
    print STDERR "Getting advertisements in parallel ...\n";
    if (ParRun({'maxwaittime' => 600, 'maxchildren' => 4},
	       \@results, $coderef, @todo)) {
	print STDERR "*** MapResources: Internal error mapping resources\n";
	return -1;
    }
    
    #
    # Check the exit codes. 
    #
    my $errors   = 0;
    $count = 0;
    foreach my $result (@results) {
	my ($resource, $tmp) = @{ $todo[$count] };

	#
	# ParRun does a fork; so need to refresh the resource object
	# to sync it to the DB.
	#
	if ($resource->Refresh()) {
	    print STDERR "*** MapResources: Error synchronizing $resource\n";
	    $errors++;
	}
	elsif ($result != 0) {
	    print STDERR "*** Error getting advertisement for $resource\n";
	    $errors++;
	}
	$count++;
    }
    return -1
	if ($errors);
    
    my $soln = $name . ".soln";
    my $log  = $name . ".log";
    my $vtop = $name . ".vtop";
    my $ptop = $name . ".ptop";

    my $vtopfh = new IO::File "> $vtop";
    my $ptopfh = new IO::File "> $ptop";
    if (! (defined($vtopfh) && defined($ptopfh))) {
	print STDERR "Could not create temporary files for ptop/vtop\n";
	return -1;
    }
    # Combine the fragments into a single rspec document.
    my $rspec = CombineRspecDocs("request", values(%vname2doc));
    return -1
	if (!defined($rspec));
    
    my $rspecstr = GeniXML::Serialize($rspec, 1);
    print $vtopfh $rspecstr;
    $vtopfh->close();

    if ($verbose) {
	print STDERR "Initial Request:\n";
	print STDERR "$rspecstr\n";
    }

    #
    # Combine all the advertisements into one big file. Hope assign
    # can handle this.
    #
    my %adfrags = ();
    foreach my $ref (@todo) {
	my ($resource, $tmp) = @{ $ref };

	my $ad = $tmp . ".ad";
	my $frag = GeniXML::ParseFile($ad);
	if (!defined($frag)) {
	    print STDERR "Cannot parse advertisement for $resource\n";
	    return -1;
	}
	$adfrags{$resource->manager_urn()} = $frag;
    }
    my $advertisement = CombineRspecDocs("advertisement",
					 map { $_->childNodes() }
					 values(%adfrags));
    my $adstr = GeniXML::Serialize($advertisement, 1);
    print $ptopfh $adstr;
    $ptopfh->close();

    my $cmd = "nice $ASSIGN -uod -c .75 ".
	"-f rspec/rspec -W $soln $ptop $vtop > $log 2>&1";
    if ($verbose) {
	print STDERR "$cmd\n";
    }
    system($cmd);
	
    if ($?) {
	print STDERR "Could not map to physical resources\n";
	my $logstuff = `cat $log`;
	print STDERR "\n" . $logstuff . "\n";
	print STDERR "$rspecstr\n";
	return -1;
    }

    #
    # Read the solutions and write back to the rspec.
    #
    my $solution =
	eval { XMLin($soln, KeyAttr => [],
		     ForceArray => ["node", "link", "interface",
				    "interface_ref", "linkendpoints",
				    "component_manager"]) };
    if ($@) {
	print STDERR "XMLin error reading $soln: $@\n";
	return -1;
    }
    if ($verbose) {
	print STDERR "Solution:\n";
	print STDERR Dumper($solution);
    }

    foreach my $ref (@{ $solution->{'node'} }) {
	my $virtual_id = $ref->{'virtual_id'};
	my $node_urn   = $ref->{'component_uuid'};
	my $cm_urn     = $ref->{'component_manager_uuid'};
	my $node_name  = $ref->{'component_name'};
	my $rspecdoc   = $vname2doc{$virtual_id};

	$nodes2cmurn{$node_urn} = $cm_urn;
	#
	# This writes the solution back into the fragment.
	#
	$rspecdoc->setAttribute("component_uuid", $node_urn);
	$rspecdoc->setAttribute("component_urn", $node_urn);
	$rspecdoc->setAttribute("component_name", $node_name);
	$rspecdoc->setAttribute("component_manager_uuid", $cm_urn);
	$rspecdoc->setAttribute("component_manager_urn", $cm_urn);

	if (exists($ref->{'interface'})) {
	    my $interfaces = $ref->{'interface'};

	    foreach my $ifaceref (@{ $interfaces }) {
		my $virtid = $ifaceref->{'virtual_id'};
		my $compid = $ifaceref->{'component_id'};

		# Not supposed to happen, but does cause of issues
		# with tunnels and rspec stitching. 
		next
		    if (!defined($compid));

		foreach my $linkref (GeniXML::FindNodes("n:interface",
						$rspecdoc)->get_nodelist()) {
		    my $ovirtid = GeniXML::GetText("virtual_id", $linkref);
		    if ($ovirtid eq $virtid) {
			$linkref->setAttribute("component_id", $compid);
			last;
		    }
		}
	    }
	}
    }

    #
    # One last chore; we had to skip tunnels above since assign does
    # not know how to deal with them.
    #
    if (exists($topo->{'link'})) {
	foreach my $ref (@{ $topo->{'link'} }) {
	    my $linkname   = $ref->{'virtual_id'};

	    # Skip non-tunnels.
	    next
		if (! (exists($ref->{'link_type'}) &&
		       $ref->{'link_type'} eq "tunnel"));

	    my $ifaceref0 = $ref->{'interface_ref'}->[0];
	    my $ifaceref1 = $ref->{'interface_ref'}->[1];
	    # Do not want to add this twice.
	    my $virtid0   = $ifaceref0->{'virtual_node_id'};
	    my $resource0 = $vname2res{$virtid0};
	    my $fragment0 = $cmurn2frags{$resource0->manager_urn()};

	    my $rspecdoc = AddLinkToRspec($fragment0, $ref);
	    return -1
		if (!defined($rspecdoc));
	    # Only one of these in the array, for building combined rspec.
	    $vname2doc{$linkname} = $rspecdoc;
	    
	    my $virtid1   = $ifaceref1->{'virtual_node_id'};
	    my $resource1 = $vname2res{$virtid1};
	    my $fragment1 = $cmurn2frags{$resource1->manager_urn()};
	    if ($resource0->manager_urn() ne $resource1->manager_urn()) {
		$rspecdoc = AddLinkToRspec($fragment1, $ref);
		return -1
		    if (!defined($rspecdoc));
	    }
	}
    }

    #
    # Compare to previous rspec; this tells us if we need to request
    # a new ticket. Easier to use the rspec then the manifest since
    # the CM added a ton of cruft to it.
    #
    foreach my $manager_urn (keys(%cmurn2res)) {
	my $resource = $cmurn2res{$manager_urn};

	# We got the ticket on a previous loop.
	next
	    if ($resource->HaveTicket());

	my $fragment    = $cmurn2frags{$manager_urn};
	my $frag_string = GeniXML::Serialize($fragment);
	# Must stash for redeemticket.
	$resource->stashrspec($frag_string);
	
	next
	    if (! $resource->HaveRspec());

	#
	# The idea is to do a diff of the rspec. If there are no
	# meaningful changes, then we can skip trying to get a new
	# ticket.
	#
	my $rspec    = $resource->Rspec();
	my $diff     = XML::SemanticDiff->new();
	my $rspec_string = GeniXML::Serialize($rspec);
	$resource->setmodified(0);

	print STDERR "Comparing old and new rspecs for $resource\n"; 
	foreach my $change ($diff->compare($rspec_string, $frag_string)) {
	    print STDERR " $change->{message} in context $change->{context}\n";
	    $resource->setmodified(1);
	}
	if ($resource->modified() && $resource->ApiLevel() == 0) {
	    print STDERR "*** Difference to rspec for level 0 $resource. ".
		"Not allowed, aborting\n";
	    return -1;
	}
    }

    #
    # Combine the updated fragments into final rspec document.
    #
    $rspec = CombineRspecDocs("request", values(%vname2doc));
    return -1
	if (!defined($rspec));

    # Make sure all that namespace stuff is done correctly. 
    $rspec = GeniXML::Parse(GeniXML::Serialize($rspec));
    
    if ($verbose) {
	print STDERR "Final rspec:\n";
	my $rspecstr = GeniXML::Serialize($rspec, 1);
	print STDERR "$rspecstr\n";

	my $tmp = ConvertReqPGtoSFA($rspec);
	$rspecstr = GeniXML::Serialize($tmp, 1);

	print STDERR "SFA Version:\n";
	print STDERR "$rspecstr\n";
    }
    $$rspecref = $rspec;

    #
    # Before we return, lets make sure all the proxy nodes exist.
    # This is probably not the best place to do this, but remember
    # that once a proxy node exists, it will be available next time.
    #
    foreach my $node_urn (keys(%nodes2cmurn)) {
	my $cm_urn = $nodes2cmurn{$node_urn};

	my $proxy = LookupProxyNode($node_urn);
	if (!defined($proxy)) {
Leigh Stoller's avatar
Leigh Stoller committed
894
	    $proxy = GeniEmulabUtil::CreatePhysNode($cm_urn, $node_urn);
895 896 897 898 899 900 901 902 903 904 905 906 907
	    if (!defined($proxy)) {
		#
		# It would be nice at this point to drop the node from
		# the set and try again.
		#
		print STDERR "Could not create proxy node $node_urn\n";
		return -1;
	    }
	}
    }
    return 0;
}

908
sub GetTickets($)
909
{
910 911 912 913 914 915 916
    my ($vtop) = @_;
    my $experiment = $vtop->experiment();
    my $verbose    = $vtop->verbose();
    my $user       = $vtop->user();
    my $rspec      = $vtop->genirspec();
    my $eventkey   = $experiment->eventkey();
    my $keyhash    = $experiment->keyhash();
917 918 919 920

    Register($experiment, $user) == 0
	or return -1;

921 922 923 924 925 926 927 928 929
    #
    # Get the resource objects.
    #
    my @resources = GeniResource->LookupAll($experiment);
    if (! @resources) {
	print STDERR "RedeemTickets: No resource objects\n";
	return 0;
    }
    my @todo = ();
930

931 932 933 934 935
    foreach my $resource (@resources) {
	next
	    if ($resource->HaveTicket() || !$resource->modified());

	push(@todo, $resource);
936
    }
937
    return 0
938
	if (! @todo);
939

940
    #
941 942
    # Before sending off the rspec, add the stuff that we need for
    # full cooked mode to work.
943
    #
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    foreach my $ref (GeniXML::FindNodes("n:node",
					$rspec)->get_nodelist()) {
	my $vname   = GeniXML::GetVirtualId($ref);
	my $node    = $vtop->VnameToNode($vname);

	# XXX Boot mode; simple vs full. Have not decided the
	# proper interface for this yet.
	my $bootmode = $experiment->GetEnvVariable("${vname}_BOOTMODE");
	next
	    if (defined($bootmode) && lc($bootmode) eq "basic");
	
	if (!defined($node)) {
	    print STDERR "*** GetTickets: No proxy node for $vname\n";
	    return -1;
	}
	
	# Generate a key for the node if not already there. The caller
	# has created and allocated the proxy nodes by now.
	my $key;
	
	if (!defined($node->external_resource_key())) {
	    $key = TBGenSecretKey();
	    $node->ModifyReservation({"external_resource_key" => $key}) == 0
		or return -1;
	}
	else {
	    $key = $node->external_resource_key();
	}

	$ref->setAttribute("tarfiles",
			   "/usr/local/etc/emulab ".
			   "$TBDOCBASE/downloads/geniclient.tar");
	    
	my $cmd = "sudo /usr/local/etc/emulab/rc/rc.pgeni ".
978
	    "-s $BOSSNODE -k $eventkey,$keyhash -i '$key'";
979 980 981 982 983 984 985
	$cmd .= " -j " . $node->node_id()
	    if ($node->isvirtnode());
	$cmd .= " -e 16509"
	    if ($ELVIN_COMPAT);

	$ref->setAttribute("startup_command", "$cmd boot");
    }
986
    if ($verbose) {
987 988
	print STDERR "Rspec for GetTicket():\n";
	print STDERR GeniXML::Serialize($rspec, 1) . "\n";
989
    }
990
    my $rspecstr = GeniXML::Serialize($rspec);
991

992
    #
993
    # Get Tickets in parallel.
994
    #
995 996 997
    my @results   = ();
    my $coderef   = sub {
	my ($resource) = @_;
998

999
	if ($resource->ApiLevel() == 0) {
1000
	    print STDERR "Creating sliver on level 0 API $resource\n";
1001 1002 1003 1004
	    if ($resource->IsSFA()) {
		my $tmp = ConvertReqPGtoSFA($rspec);
		$rspecstr = GeniXML::Serialize($tmp);
	    }
1005 1006
	    return 0
		if ($resource->CreateSliver($user, $rspecstr, 0) == 0);
1007
	}
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	else {
	    print STDERR "Asking for ticket from $resource\n";
	    return 0
		if ($resource->GetTicket($user, $rspecstr, 0) == 0);
	}
	#
	# Print this here since we do not save this in the
	# DB, and the parent side of the fork will not have
	# the error message.
	#
	if ($resource->last_rpc_error() &&
	    defined($resource->last_rpc_value()) &&
	    $resource->last_rpc_value()) {
	    print STDERR $resource->last_rpc_value() . "\n";
	}
	# Return indicator of possible forward progress.
	return 1
	    if (defined($resource->last_rpc_output()) &&
		$resource->last_rpc_output() =~ /Could not map to/i);
	
	return -1;
1029
    };
1030
    print STDERR "Getting all tickets/slivers in parallel ...\n";
1031
    
1032
    if (ParRun({'maxwaittime' => 600}, \@results, $coderef, @todo)) {
1033 1034 1035 1036 1037 1038 1039 1040
	print STDERR "*** GetTickets: Internal error getting tickets\n";
	#
	# Need to be careful here; some of the tickets might have been
	# redeemed, and that happened in the child of a fork. Sync with
	# the DB so the parent sees the current state.
	#
	map { $_->Refresh() } @resources;
	return -1;
1041
    }
1042 1043 1044
    #
    # Check the exit codes. Eventually return specific error info.
    #
1045 1046 1047
    my $errors   = 0;
    my $count    = 0;
    my $progress = 0;
1048
    foreach my $result (@results) {
1049
	my $resource = $todo[$count];
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

	#
	# ParRun does a fork; so need to refresh the resource object
	# to sync it to the DB.
	#
	if ($resource->Refresh()) {
	    print STDERR "*** GetTickets: Error synchronizing $resource\n";
	    $errors++;
	}
	elsif ($result != 0) {
	    print STDERR "*** Error getting ticket for $resource\n";
	    $errors++;
1062 1063 1064 1065 1066 1067 1068 1069 1070

	    # Watch for forward progress. Not being able to map actually
	    # means forward progress since we want to try again with
	    # different resources. The mapper will try a few times before
	    $progress++
		if ($result > 1);
	}
	else {
	    $progress++;
1071 1072
	    my $object;

1073
	    if ($resource->ApiLevel() == 0) {
1074 1075 1076 1077 1078
		#
		# Created the sliver; 
		#
		$object = $resource->Manifest();

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
		#
		# Convert SFA manifest to rspec format.
		#
		if ($object && $resource->IsSFA()) {
		    my $tmp = ConvertSFAtoPG($object, "manifest",
					     $resource->manager_urn());
		    if (!defined($tmp) ||
			$resource->UpdateManifest($tmp)) {
			print STDERR "Could not store manifest for $resource\n";
			$errors++;
			$object = undef;
		    }
		    else {
			# reload.
			$object = $tmp;
		    }
		}
		
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
		# File the rspec away since that is what we have.
		if ($resource->UpdateRspec($resource->stashedrspec())) {
		    print STDERR "Could not store rspec for $resource\n";
		    $errors++;
		}
		$resource->stashrspec(undef);
	    }
	    else {
		#
		# Got a ticket.
		#
		$object = $resource->Ticket();
		$object = $object->rspec()
		    if (defined($object));
	    }
	    return -1
		if (!$object);
1114 1115

	    #
1116 1117 1118 1119 1120 1121 1122
	    # Mark the proxy nodes so that libvtop knows. Failure means we
	    # need to release the node up in libvtop.
	    #	    
	    foreach my $ref (GeniXML::FindNodes("n:node",
						$object)->get_nodelist()) {
		my $vname      = GeniXML::GetVirtualId($ref);
		my $manager_urn= GeniXML::GetManagerId($ref);
1123

1124 1125 1126 1127 1128
		next
		    if (!defined($manager_urn) ||
			$resource->manager_urn() ne $manager_urn);
	    
		my $node = $experiment->VnameToNode($vname);
1129 1130 1131 1132 1133 1134
		if (defined($node)) {
		    $node->ModifyReservation({"external_resource_index" =>
						  $resource->idx()})
			== 0 or return -1;
		}
	    }
1135 1136 1137
	}
	$count++;
    }
1138 1139 1140
    return 0
	if (!$errors);
    
1141
    print STDERR Dumper($rspec) if ($errors);
1142 1143
    # Return indication of forward progress so caller knows to to stop.
    return ($progress ? 1 : -1);
1144 1145 1146 1147 1148
}

#
# Redeem the tickets for an experiment. 
#
1149
sub RedeemTickets($$)
1150
{
1151
    my ($experiment, $user) = @_;
1152 1153 1154 1155 1156 1157 1158 1159 1160

    #
    # Get the resource objects.
    #
    my @resources = GeniResource->LookupAll($experiment);
    if (! @resources) {
	print STDERR "RedeemTickets: No resource objects\n";
	return 0;
    }
1161 1162 1163 1164 1165 1166 1167 1168
    my @todo = ();

    foreach my $resource (@resources) {
	push(@todo, $resource)
	    if ($resource->HaveTicket());
    }
    return 0
	if (! @todo);
1169

1170 1171 1172 1173 1174 1175 1176
    #
    # Redeem Tickets in parallel.
    #
    my @results   = ();
    my $coderef   = sub {
	my ($resource) = @_;

1177 1178 1179 1180
	print STDERR "Redeeming ticket for $resource\n";
	if ($resource->RedeemTicket($user)) {
	    return -1;
	}
1181 1182
	return 0;
    };
1183 1184
    print STDERR "Redeeming all tickets in parallel ...\n";

1185
    if (ParRun({'maxwaittime' => 600}, \@results, $coderef, @todo)) {
1186 1187 1188 1189 1190 1191 1192 1193
	print STDERR "*** RedeemTickets: Internal error getting tickets\n";
	#
	# Need to be careful here; some of the tickets might have been
	# redeemed, and that happened in the child of a fork. Sync with
	# the DB so the parent sees the current state.
	#
	map { $_->Refresh() } @resources;
	return -1;
1194
    }
1195 1196 1197 1198 1199 1200
    #
    # Check the exit codes. Eventually return specific error info.
    #
    my $errors = 0;
    my $count  = 0;
    foreach my $result (@results) {
1201
	my $resource = $todo[$count];
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
	
	#
	# ParRun does a fork; so need to refresh the resource object
	# to sync it to the DB.
	#
	if ($resource->Refresh()) {
	    print STDERR "*** RedeemTicket: Error synchronizing $resource\n";
	    $errors++;
	}
	elsif ($result != 0) {
	    print STDERR "*** Error redeeming ticket for $resource\n";
	    $errors++;
	}
1215 1216 1217 1218 1219 1220 1221 1222
	else {
	    # File the rspec away since that is what we have.
	    if ($resource->UpdateRspec($resource->stashedrspec())) {
		print STDERR "Could not store rspec for $resource\n";
		$errors++;
	    }
	    $resource->stashrspec(undef);
	}
1223 1224 1225
	$count++;
    }
    return $errors;
1226 1227 1228 1229 1230 1231
}

#
# Map the local nodes to the external nodes. This just sets some DB
# state for now.
#
1232
sub MapNodes($$)
1233
{
1234
    my ($experiment, $verbose) = @_;
1235
    my %ifacemap = ();
1236
    my $manifest_string;
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249

    #
    # Get the resource objects.
    #
    my @resources = GeniResource->LookupAll($experiment);
    if (! @resources) {
	return 0;
    }

    foreach my $resource (@resources) {
	my $manifest = $resource->Manifest();
	return -1
	    if (!defined($manifest));
Leigh Stoller's avatar
Leigh Stoller committed
1250 1251 1252 1253
	my $rspec = $resource->Rspec();
	return -1
	    if (!defined($rspec));
	
1254
	$manifest_string = GeniXML::Serialize($manifest, 1);
1255

1256 1257 1258
	if ($verbose) {
	    print STDERR "$manifest_string\n"
	}
1259

1260 1261
	foreach my $ref (GeniXML::FindNodes("n:node",
					    $manifest)->get_nodelist()) {
1262
	    my $sliver_urn = GeniXML::GetText("sliver_urn", $ref);
1263 1264
	    my $vname      = GeniXML::GetVirtualId($ref);
	    my $sshdport   = GeniXML::GetText("sshdport", $ref);
1265
	    my $manager_urn= GeniXML::GetText("component_manager_urn", $ref);
1266

1267 1268 1269 1270 1271
	    #
	    # The manifest can include nodes from other CMs. There will not
	    # be a sliver urn in that case.
	    #
	    next
1272 1273 1274 1275 1276 1277
		if (!defined($sliver_urn));

	    # Hmm, still need to check this. 
	    next
		if (!defined($manager_urn) ||
		    $manager_urn ne $resource->manager_urn());
1278 1279
	    
	    my $node = $experiment->VnameToNode($vname);
1280 1281 1282
	    if (!defined($node)) {
		print STDERR
		    "MapNodes: Could not locate node $vname in $experiment\n";
1283
		goto bad;
1284 1285 1286 1287 1288 1289 1290
	    }
	    $node->ModifyReservation({"external_resource_index" =>
					  $resource->idx(),
				      "external_resource_id"    =>
				          $sliver_urn})
		== 0 or return -1;

1291
	    if (defined($sshdport)) {
1292 1293
		$node->Update({'sshdport' => $sshdport});
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1294 1295

	    # Interface map for loop below.
1296 1297 1298 1299 1300
	    if (defined(GeniXML::FindFirst("n:interface", $ref))) {
		foreach my $ifaceref (GeniXML::FindNodes("n:interface",
						$ref)->get_nodelist()) {
		    my $virtid = GeniXML::GetText("virtual_id", $ifaceref);
		    my $compid = GeniXML::GetText("component_id", $ifaceref);
1301 1302 1303 1304 1305

		    $ifacemap{$virtid} = [$node, $compid];
		}
	    }
	}
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
	foreach my $ref (GeniXML::FindNodes("n:link",
					    $manifest)->get_nodelist()) {
	    my $linkname   = GeniXML::GetVirtualId($ref);
	    my $link_type  = GeniXML::GetText("link_type", $ref);
	    my $vlantag    = GeniXML::GetText("vlantag", $ref);
	    my @ifacerefs  = GeniXML::FindNodes("n:interface_ref",
						$ref)->get_nodelist();
	    my %managers   = ();

	    if (GeniXML::FindNodes("n:component_manager", $ref)) {
1316
		%managers = map { GetLinkManager($_) => $_ } 
1317 1318 1319
		                  GeniXML::FindNodes("n:component_manager",
						     $ref)->get_nodelist();
	    }
1320 1321 1322

	    # Skip tunnels in this loop for now.
	    next
1323
		if (defined($link_type) && $link_type eq "tunnel");
1324 1325 1326 1327 1328 1329 1330

	    #
	    # The manifest can include links for other CMs. Skip those
	    # for now.
	    #
	    next 
		if (!exists($managers{$resource->manager_urn()}));
1331

1332 1333
	    if (defined($vlantag)) {
		my $TAG = $vlantag;
1334 1335 1336 1337
		
		if (defined($TAG)) {
		    if (!($TAG =~ /^[\w]*$/)) {
			print STDERR "Bad vlantag '$TAG' for $linkname\n";
1338
			goto bad;
1339 1340 1341 1342
		    }
		    my $lan = Lan->Lookup($experiment, $linkname, 1);
		    if (!defined($lan)) {
			print STDERR "Could not find vlan for $linkname\n";
1343
			goto bad;
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
		    }
		    #
		    # XXX This seems backwards. If the lan is pointing
		    # to another lan, then we really want to change that
		    # one. 
		    #
		    if ($lan->type() eq "emulated" && defined($lan->link())) {
			$lan = Lan->Lookup($lan->link());
			if (!defined($lan)) {
			    print STDERR 
				"Could not find linked vlan for $linkname\n";
			    return -1;
			}
		    }
		    return -1
			if ($lan->SetAttribute("vlantag", $TAG));
		}
	    }

1363 1364 1365 1366 1367 1368
	    foreach my $ifaceref (@ifacerefs) {
		my $vname    = GeniXML::GetText("virtual_node_id", $ifaceref);
		my $iface_id = GeniXML::GetText("virtual_interface_id",
						$ifaceref);
		my $MAC      = GeniXML::GetText("MAC", $ifaceref);
		my $VMAC     = GeniXML::GetText("VMAC", $ifaceref);
1369
		my ($node, $compid) = @{ $ifacemap{$iface_id} };
1370
		my $iface;
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

		if (GeniHRN::IsValid($compid)) {
		    (undef,undef,$iface) = GeniHRN::ParseInterface($compid);
		}
		else {
		    $iface = $compid;
		}
		if (!defined($iface)) {
		    print STDERR "Could not determine iface for" .
			"$vname,$iface_id\n";
1381
		    goto bad;
1382
		}
1383
		#
1384 1385 1386
		# If this is a virtual node, then we want to set the
		# MACs of the underlying physical node. The vinterface
		# (VMAC) will be handled below.
1387
		#
1388 1389 1390 1391
		if ($node->isvirtnode()) {
		    my $pnode = $node->GetPhysHost();
		    if (!defined($pnode)) {
			print STDERR "Could not physical node for $node\n";
1392
			goto bad;
1393 1394
		    }
		    $node = $pnode;
1395
		}
1396 1397 1398 1399 1400 1401 1402 1403 1404

		#
		# If the interface is the loopback, then we do not need
		# to do this.
		#
		if ($iface ne "lo0" && $iface ne "loopback") {
		    my $interface = Interface->LookupByIface($node,$iface);
		    if (!defined($interface)) {
			print STDERR "Could not map iface for $node,$iface\n";
1405
			goto bad;
1406 1407 1408
		    }
		    if (!defined($MAC)) {
			print STDERR "No mac (or vmac) for $node,$iface\n";
1409
			goto bad;
1410 1411 1412
		    }
		    if (! ($MAC =~ /^[\w]*$/)) {
			print STDERR "Bad mac '$MAC' for $node,$iface\n";
1413
			goto bad;
1414 1415 1416
		    }
		    if ($interface->Update({"mac" => "$MAC"})) {
			print STDERR "Could not update $node,$iface\n";
1417
			goto bad;
1418
		    }
1419
		}
1420 1421 1422 1423 1424 1425 1426 1427
		if (defined($VMAC)) {
		    my $vinterface =
			Interface::VInterface->LookupByVirtLan($experiment,
							       $linkname,
							       $vname);
		    if (!defined($vinterface)) {
			print STDERR
			    "Could not map vinterface for $linkname,$vname\n";
1428
			goto bad;
1429 1430 1431
		    }
		    if (! ($VMAC =~ /^[\w]*$/)) {
			print STDERR "Bad vmac '$VMAC' for $linkname,$vname\n";
1432
			goto bad;
1433 1434 1435
		    }
		    if ($vinterface->Update({"mac" => "$VMAC"})) {
			print STDERR "Could not update $linkname,$vname\n";
1436
			goto bad;
1437 1438
		    }
		}
1439
	    }
1440
	}
1441 1442 1443 1444
	if ($verbose) {
	    my $string = GeniXML::Serialize($manifest, 1);
	    print STDERR "$string\n";
	}
1445
	
1446 1447 1448 1449 1450
	# The manifest was changed above.
	if ($resource->UpdateManifest($manifest)) {
	    print STDERR "Could not store manifest for $resource\n";
	    return -1;
	}
1451 1452
    }
    return 0;
1453 1454 1455 1456 1457 1458

  bad:
    if ($manifest_string) {
	print STDERR "$manifest_string\n";
    }
    return -1;
1459 1460 1461 1462
}

#
# Boot (Start) all of the slivers. This does the entire set, and blocks
1463
# till done. Expressly for use from os_setup.
1464
#
1465
sub StartSlivers($$$)
1466
{
1467
    my ($experiment, $user, $verbose) = @_;
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483

    #
    # Get the resource objects.
    #
    my @resources = GeniResource->LookupAll($experiment);
    if (! @resources) {
	return 0;
    }

    #
    # Start slivers in parallel.
    # 
    my @results = ();
    my $coderef = sub {
	my ($resource) = @_;

1484
	# The sliver was auto started. We just need to wait for it.
1485 1486
	if ($resource->Api() eq "AM" ||
	    $resource->ApiLevel() == 0) {
1487 1488 1489 1490 1491
	    print STDERR
		"Skipping start sliver on level 0 resource $resource\n";
	    return 0;
	}

1492
	if ($resource->Version() >= 2) {
1493
	    #
1494 1495 1496
	    # First get the state; we might not need to start it
	    # (would be wrong) if the sliver is in the started
	    # start. We deal with restart later.
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
	    #
	    print STDERR "Getting current sliver status for $resource\n";
	    my $status;
	
	    while (1) {
		my $retval = $resource->SliverStatus($user, \$status);
		last
		    if ($retval == 0);

		if ($resource->last_rpc_error() &&
		    $resource->last_rpc_error() == GENIRESPONSE_BUSY()) {
		    sleep(10);
		    next;
		}
		else {
		    print STDERR "Error getting sliver status for $resource\n";
		    # Tell the parent error.
		    return -1;
		}
	    }
	    if ($status->{'state'} eq "started") {
		print STDERR "Skipping start on already started $resource.\n";
		return 0;
	    }
	}
	print STDERR "Starting sliver $resource\n";
1523
	while (1) {
1524
	    my $retval = $resource->StartSliver($user);
1525 1526 1527
	    last
		if (!$retval);
	    return -1
1528 1529
		if (!$resource->last_rpc_error() ||
		    $resource->last_rpc_error() != GENIRESPONSE_BUSY());
1530 1531 1532
	    
	    sleep(10);
	}
1533 1534 1535
	#
	# Grab a new manifest;
	#
1536
	if ($resource->Version() == 2.0) {
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
	    while (1) {
		print STDERR "Getting ($$) new manifest for $resource\n";
		my $retval = $resource->GetManifest($user);
		last
		    if (!$retval);
		return -1
		    if (!$resource->last_rpc_error() ||
			$resource->last_rpc_error() != GENIRESPONSE_BUSY());
	    
		sleep(10);
	    }

	}
1550
	return 0;
1551
    };
1552 1553
    print STDERR "Starting all slivers in parallel ...\n";

1554
    if (ParRun({'maxwaittime' => 600}, \@results, $coderef, @resources)) {
1555 1556 1557 1558 1559 1560 1561 1562 1563
	print STDERR "*** StartSlivers: Internal error starting slivers.\n";
	return -1;
    }
    #
    # Check the exit codes. Eventually return specific error info.
    #
    my $errors = 0;
    my $count  = 0;
    my @tmp    = ();
1564
    my @failed = ();
1565 1566 1567 1568 1569 1570
    foreach my $result (@results) {
	my $resource = $resources[$count];
	
	if ($result != 0) {
	    print STDERR "*** Error starting slivers for $resource\n";
	    $errors++;
1571
	    push(@failed, $resource);
1572 1573
	}
	else {
1574 1575 1576 1577 1578 1579 1580 1581 1582
	    #
	    # ParRun does a fork; so need to refresh the resource object
	    # to sync it to the DB.
	    #
	    if ($resource->Refresh()) {
		print STDERR
		    "*** StartSlivers: Error synchronizing $resource\n";
		$errors++;
	    }
1583 1584 1585 1586
	    push(@tmp, $resource);
	}
	$count++;
    }
1587 1588 1589 1590 1591 1592
    #
    # Set the nodes to TBFAILED to avoid waiting in os_setup.
    #
    if (@failed) {
	foreach my $resource (@failed) {
	    my $manager_urn = $resource->manager_urn();
1593
	    my $manifest    = $resource->Manifest();
1594
	    return -1
1595
		if (!defined($manifest));
1596 1597

	    foreach my $ref (GeniXML::FindNodes("n:node",
1598
						$manifest)->get_nodelist()) {
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
		my $vname            = GeniXML::GetVirtualId($ref);
		my $this_manager_urn = GeniXML::GetManagerId($ref);

		next
		    if (!defined($this_manager_urn) ||
			$manager_urn ne $this_manager_urn);
		
		my $node = $experiment->VnameToNode($vname);
		next
		    if (!defined($node));

		if ($node->eventstate() ne TBDB_NODESTATE_TBFAILED()) {
		    $node->SetEventState(TBDB_NODESTATE_TBFAILED());
		}
	    }
	}
    }
1616 1617 1618 1619
    # Everything failed, stop now. 
    return -1
	if (!@tmp);
    
1620 1621 1622
    MapNodes($experiment, $verbose);
    
    return WaitForSlivers($experiment, $user, $verbose, @tmp);
1623 1624
}

1625
sub WaitForSlivers($$$@)
1626
{
1627
    my ($experiment, $user, $verbose, @resources) = @_;
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    my %nodemap = ();

    #
    # Get the resource objects.
    #
    @resources = GeniResource->LookupAll($experiment)
	if (!@resources);
    
    if (! @resources) {
	return 0;
    }

1640 1641
    print STDERR "Waiting for slivers ...\n";

1642
    #
1643
    # Build a map of the nodes. I made a real mess of this in Version 1.
1644
    #
1645 1646 1647 1648 1649
    foreach my $resource (@resources) {
	my $manifest = $resource->Manifest();
	return -1
	    if (!defined($manifest));

1650 1651 1652 1653
	foreach my $ref (GeniXML::FindNodes("n:node",
					    $manifest)->get_nodelist()) {
	    my $vname      = GeniXML::GetVirtualId($ref);
	    my $urn        = GeniXML::GetNodeId($ref);
1654 1655 1656 1657 1658 1659
	    my $node       = $experiment->VnameToNode($vname);

	    #
	    # The manifest can include nodes from other CMs. There will not
	    # be a sliver urn in that case.
	    #
1660
	    my $sliver_urn = GeniXML::GetSliverId($ref);
1661 1662 1663 1664
	    next
		if (!defined($sliver_urn));
	    
	    if (!defined($node)) {
1665
		print STDERR "*** WaitForSlivers: ".
1666 1667 1668
		    "Could not locate node $vname in $experiment\n";
		return -1;
	    }
1669
	    if ($resource->Version() == 1.0) {
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
		my ($domain,undef,$node_id) = GeniHRN::Parse($urn);
		$urn = GeniHRN::Generate($domain, "sliver", $node_id);
		$nodemap{$urn} = $node;
	    }
	    else {
		next
		    if (!defined($node->external_resource_id()) ||
			$node->external_resource_id() eq "");

		$nodemap{$node->external_resource_id()} = $node;
	    }
	    $node->Refresh();
1682 1683 1684 1685 1686 1687

	    # XXX Boot mode; simple vs full. Have not decided on the
	    # proper interface for this yet.
	    my $bootmode = $experiment->GetEnvVariable("${vname}_BOOTMODE");
	    # Stash it in the node object.
	    $node->_bootmode($bootmode || "");
1688
	}
1689 1690 1691 1692 1693 1694 1695 1696 1697
    }

    #
    # Now we use parrun again to get the sliver status. We are waiting
    # for them to become ready so we can send them into ISUP. 
    #
    my $coderef = sub {
	my ($resource) = @_;
	my $ref;
1698 1699 1700
	my $failed   = 0;
	my $ready    = 0;
	my $count    = 0;
1701

1702
	print STDERR "Getting ($$) sliver status for $resource\n";
1703 1704

	if ($resource->SliverStatus($user, \$ref) != 0) {
1705
	    # Tell the parent to keep trying.
1706
	    return 1
1707 1708
		if ($resource->last_rpc_error() &&
		    $resource->last_rpc_error() == GENIRESPONSE_BUSY());
1709
	    
1710 1711 1712 1713
	    print STDERR "Error getting sliver status for $resource\n";
	    # Tell the parent error.
	    return -1;
	}
1714 1715
	print STDERR Dumper($ref)
	    if ($verbose);
1716

1717 1718 1719 1720
	foreach my $key (keys(%{ $ref->{'details'} })) {
	    my $val  = $ref->{'details'}->{$key};
	    my ($status, $node);

1721
	    if ($resource->Api() eq "AM") {
1722 1723 1724
		$node   = $nodemap{$key};
		$status = $val->{'status'};
	    }
1725
	    elsif ($resource->Version() == 1.0) {
1726 1727 1728
		$node   = $nodemap{$key};
		$status = $val;
	    }
1729
	    elsif ($resource->Version() == 2.0) {
1730 1731 1732 1733 1734 1735 1736 1737
		$node   = $nodemap{$key};
		$status = $val->{'status'};
	    }
	    else {
		print STDERR
		    "*** WaitForSlivers: Unknown version on $resource\n";
		next;
	    }
1738