libGeni.pm.in 66.6 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2009-2016 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

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

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

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

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

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

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

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

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

102 103 104 105 106 107 108 109 110
    #
    # 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'}));
	
111
	my $resource;
112 113 114 115
	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
116
	
117 118 119
	#
	# Get the resource object.
	#
120 121
	if (!exists($cmurn2res{$manager_urn})) {
	    $resource = GeniResource->Lookup($experiment->idx(), $manager_urn);
122
	    if (!defined($resource)) {
123
		$resource = GeniResource->Create($experiment, $manager_urn);
124
		if (!defined($resource)) {
125 126
		    print STDERR
			"Could not create GeniResource for $manager_urn\n";
127 128 129
		    return -1;
		}
	    }
130
	    $cmurn2res{$manager_urn} = $resource;
131
	}
132 133
	$resource = $cmurn2res{$manager_urn};
	$vname2res{$virtual_id} = $resource;
134 135 136 137 138 139 140

	#
	# 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.
	#
141 142
	my $fragment;
	if (!exists($cmurn2frags{$manager_urn})) {
143
	    $fragment = CreateNewRspec("request");
144 145 146 147 148 149 150 151 152 153 154
	    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;
155
    }
156

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

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

169 170 171 172 173 174
	    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()};
175

176 177 178 179 180 181 182 183 184 185 186 187 188
	    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));
189 190 191
	    }
	}
    }
192 193
    if ($verbose) {
	print STDERR "Rspec Fragments:\n";
194

195 196 197 198 199 200
	foreach my $fragment (values(%cmurn2frags)) {
	    my $rspecstr = GeniXML::Serialize($fragment, 1);
	    print STDERR "$rspecstr\n";
	}
    }
    
201
    #
202 203
    # Discover resources in parallel and run assign, writing the solution
    # to a file.
204
    #
205 206
    my $coderef   = sub {
	my ($resource, $fragment, $tmp) = @{ $_[0] };
207 208 209 210 211 212 213
	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;
	}
214 215 216 217 218
	#
	# 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()) {
219 220
	    $advertisement = ConvertSFAtoPG($advertisement, "ad",
					    $resource->manager_urn());
221 222 223 224 225
	    return -1
		if (!defined($advertisement));
	    $advertisement = GeniXML::Serialize($advertisement, 1);
	}
	
Leigh Stoller's avatar
Leigh Stoller committed
226 227 228 229
	my $soln = $tmp . ".soln";
	my $log  = $tmp . ".log";
	my $ptop = $tmp . ".ptop";
	my $vtop = $tmp . ".vtop";
230

231
	my $reqstring = GeniXML::Serialize($fragment);
Leigh Stoller's avatar
Leigh Stoller committed
232 233 234 235 236 237 238 239 240 241 242
	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
243 244 245 246 247 248
	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
249
	
250 251
	if ($?) {
	    print STDERR "Could not map to physical resources on $resource\n";
252 253
	    my $logstuff = `cat $log`;
	    print STDERR "\n" . $logstuff . "\n";
254 255
	    my $string = GeniXML::Serialize($fragment, 1);
	    print STDERR "$string\n";
256 257
	    return -1;
	}
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	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";
	
321
	my $solution =
Leigh Stoller's avatar
Leigh Stoller committed
322
	    eval { XMLin($soln, KeyAttr => [],
323
			 ForceArray => ["node", "link", "interface",
324 325
					"interface_ref", "linkendpoints",
					"component_manager"]) };
326
	if ($@) {
Leigh Stoller's avatar
Leigh Stoller committed
327
	    print STDERR "XMLin error reading $soln: $@\n";
328 329
	    return -1;
	}
330 331 332 333
	if ($verbose) {
	    print STDERR "Solution for $resource\n";
	    print STDERR Dumper($solution);
	}
334 335 336

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

Leigh Stoller's avatar
Leigh Stoller committed
341
	    #
342
	    # This writes the solution back into the fragment.
Leigh Stoller's avatar
Leigh Stoller committed
343
	    #
344 345 346 347
	    $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);
348

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

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

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

361 362 363 364 365
		    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);
366 367 368 369 370 371 372
			    last;
			}
		    }
		}
	    }
	}
    }
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
    #
    # 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));
406 407 408 409
	    }
	}
    }

410 411 412 413 414 415 416
    #
    # 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};
417

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
	# 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);
	}
445
	if ($resource->modified() && $resource->ApiLevel() == 0) {
446 447 448
	    print STDERR "*** Difference to rspec for level 0 $resource. ".
		"Not allowed, aborting\n";
	    return -1;
449
	}
450
    }
451 452 453 454

    #
    # Combine the fragments into final rspec document.
    #
455
    my $rspec = CombineRspecDocs("request", values(%vname2doc));
456 457 458 459 460 461 462 463 464 465 466 467
    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;
468 469 470
    return 0;
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 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
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()) {
592 593
	    $advertisement = ConvertSFAtoPG($advertisement, "ad",
					    $resource->manager_urn());
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 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
	    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
893
	    $proxy = GeniEmulabUtil::CreatePhysNode($cm_urn, $node_urn);
894 895 896 897 898 899 900 901 902 903 904 905 906
	    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;
}

907
sub GetTickets($)
908
{
909 910 911 912 913 914 915
    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();
916 917 918 919

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

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

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

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

939
    #
940 941
    # Before sending off the rspec, add the stuff that we need for
    # full cooked mode to work.
942
    #
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
    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 ".
977
	    "-s $BOSSNODE -k $eventkey,$keyhash -i '$key'";
978 979 980 981 982 983 984
	$cmd .= " -j " . $node->node_id()
	    if ($node->isvirtnode());
	$cmd .= " -e 16509"
	    if ($ELVIN_COMPAT);

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

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

998
	if ($resource->ApiLevel() == 0) {
999
	    print STDERR "Creating sliver on level 0 API $resource\n";
1000 1001 1002 1003
	    if ($resource->IsSFA()) {
		my $tmp = ConvertReqPGtoSFA($rspec);
		$rspecstr = GeniXML::Serialize($tmp);
	    }
1004 1005
	    return 0
		if ($resource->CreateSliver($user, $rspecstr, 0) == 0);
1006
	}
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
	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;
1028
    };
1029
    print STDERR "Getting all tickets/slivers in parallel ...\n";
1030
    
1031
    if (ParRun({'maxwaittime' => 600}, \@results, $coderef, @todo)) {
1032 1033 1034 1035 1036 1037 1038 1039
	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;
1040
    }
1041 1042 1043
    #
    # Check the exit codes. Eventually return specific error info.
    #
1044 1045 1046
    my $errors   = 0;
    my $count    = 0;
    my $progress = 0;
1047
    foreach my $result (@results) {
1048
	my $resource = $todo[$count];
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

	#
	# 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++;
1061 1062 1063 1064 1065 1066 1067 1068 1069

	    # 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++;
1070 1071
	    my $object;

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

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
		#
		# 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;
		    }
		}
		
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
		# 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);
1113 1114

	    #
1115 1116 1117 1118 1119 1120 1121
	    # 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);
1122

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

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

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

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

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

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

1184
    if (ParRun({'maxwaittime' => 600}, \@results, $coderef, @todo)) {
1185 1186 1187 1188 1189 1190 1191 1192
	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;
1193
    }
1194 1195 1196 1197 1198 1199
    #
    # Check the exit codes. Eventually return specific error info.
    #
    my $errors = 0;
    my $count  = 0;
    foreach my $result (@results) {
1200
	my $resource = $todo[$count];
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
	
	#
	# 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++;
	}
1214 1215 1216 1217 1218 1219 1220 1221
	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);
	}
1222 1223 1224
	$count++;
    }
    return $errors;
1225 1226 1227 1228 1229 1230
}

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

    #
    # 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
1249 1250 1251 1252
	my $rspec = $resource->Rspec();
	return -1
	    if (!defined($rspec));
	
1253
	$manifest_string = GeniXML::Serialize($manifest, 1);
1254

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

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

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

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

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

	    # Interface map for loop below.
1295 1296 1297 1298 1299
	    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);
1300 1301 1302 1303 1304

		    $ifacemap{$virtid} = [$node, $compid];
		}
	    }
	}
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	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)) {
1315
		%managers = map { GetLinkManager($_) => $_ } 
1316 1317 1318
		                  GeniXML::FindNodes("n:component_manager",
						     $ref)->get_nodelist();
	    }
1319 1320 1321

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

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

1331 1332
	    if (defined($vlantag)) {
		my $TAG = $vlantag;
1333 1334 1335 1336
		
		if (defined($TAG)) {
		    if (!($TAG =~ /^[\w]*$/)) {
			print STDERR "Bad vlantag '$TAG' for $linkname\n";
1337
			goto bad;
1338 1339 1340 1341
		    }
		    my $lan = Lan->Lookup($experiment, $linkname, 1);
		    if (!defined($lan)) {
			print STDERR "Could not find vlan for $linkname\n";
1342
			goto bad;
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
		    }
		    #
		    # 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));
		}
	    }

1362 1363 1364 1365 1366 1367
	    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);
1368
		my ($node, $compid) = @{ $ifacemap{$iface_id} };
1369
		my $iface;
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

		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";
1380
		    goto bad;
1381
		}
1382
		#
1383 1384 1385
		# 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.
1386
		#
1387 1388 1389 1390
		if ($node->isvirtnode()) {
		    my $pnode = $node->GetPhysHost();
		    if (!defined($pnode)) {
			print STDERR "Could not physical node for $node\n";
1391
			goto bad;
1392 1393
		    }
		    $node = $pnode;
1394
		}
1395 1396 1397 1398 1399 1400 1401 1402 1403

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

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

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

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

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

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

1491
	if ($resource->Version() >= 2) {
1492
	    #
1493 1494 1495
	    # 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.
1496 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
	    #
	    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";
1522
	while (1) {
1523
	    my $retval = $resource->StartSliver($user);
1524 1525 1526
	    last
		if (!$retval);
	    return -1
1527 1528
		if (!$resource->last_rpc_error() ||
		    $resource->last_rpc_error() != GENIRESPONSE_BUSY());
1529 1530 1531
	    
	    sleep(10);
	}
1532 1533 1534
	#
	# Grab a new manifest;
	#
1535
	if ($resource->Version() == 2.0) {
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
	    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);
	    }

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

1553
    if (ParRun({'maxwaittime' => 600}, \@results, $coderef, @resources)) {
1554 1555 1556 1557 1558 1559 1560 1561 1562
	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    = ();
1563
    my @failed = ();
1564 1565 1566 1567 1568 1569
    foreach my $result (@results) {
	my $resource = $resources[$count];
	
	if ($result != 0) {
	    print STDERR "*** Error starting slivers for $resource\n";
	    $errors++;
1570
	    push(@failed, $resource);
1571 1572
	}
	else {
1573 1574 1575 1576 1577 1578 1579 1580 1581
	    #
	    # 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++;
	    }
1582 1583 1584 1585
	    push(@tmp, $resource);
	}
	$count++;
    }
1586 1587 1588 1589 1590 1591
    #
    # Set the nodes to TBFAILED to avoid waiting in os_setup.
    #
    if (@failed) {
	foreach my $resource (@failed) {
	    my $manager_urn = $resource->manager_urn();
1592
	    my $manifest    = $resource->Manifest();
1593
	    return -1
1594
		if (!defined($manifest));
1595 1596

	    foreach my $ref (GeniXML::FindNodes("n:node",
1597
						$manifest)->get_nodelist()) {
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
		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());
		}
	    }
	}
    }
1615 1616 1617 1618
    # Everything failed, stop now. 
    return -1
	if (!@tmp);
    
1619 1620 1621
    MapNodes($experiment, $verbose);
    
    return WaitForSlivers($experiment, $user, $verbose, @tmp);
1622 1623
}

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

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

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

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

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

	    #
	    # The manifest can include nodes from other CMs. There will not
	    # be a sliver urn in that case.
	    #
1659
	    my $sliver_urn = GeniXML::GetSliverId($ref);
1660 1661 1662 1663
	    next
		if (!defined($sliver_urn));
	    
	    if (!defined($node)) {
1664
		print STDERR "*** WaitForSlivers: ".
1665 1666 1667
		    "Could not locate node $vname in $experiment\n";
		return -1;
	    }
1668
	    if ($resource->Version() == 1.0) {
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
		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();
1681 1682 1683 1684 1685 1686

	    # 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 || "");
1687
	}
1688 1689 1690 1691 1692 1693 1694 1695 1696
    }

    #
    # 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;
1697 1698 1699
	my $failed   = 0;
	my $ready    = 0;
	my $count    = 0;
1700

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

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

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

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

1738 1739 1740 1741 1742 1743
	    if (!defined($node)) {
		print STDERR "No node in map for $key ($resource)\n";
		next;
	    }
	    # State was changed in a another process.
	    $node->Refresh();
1744 1745
	    
	    $count++;
Leigh Stoller's avatar