mapper.in 22.8 KB
Newer Older
1 2 3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2010 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# All rights reserved.
#
use strict;
use English;
use Getopt::Std;
use POSIX qw(setsid ceil);
use POSIX ":sys_wait_h";

#
# This function as the main assign loop.  It converts the virtual
# topology into a top input including LAN and delay translation.  It
# then snapshots the current testbed physical state and runs assign,
# looping a couple times if assign fails.  When assign successfully
# completes it will interpret the results.  Attempt to match any
# existing portmap entries and then update the delays and vlans table.
#
# XXX Internally created nodes (jailhost,delay,sim) are not treated
#     consistently. Needs more thought.
#
# Return codes: We catch all errors with the END block below, and if
# anyone calls die() (exit value is 255) we add in the CANRECOVER bit.
# Failures in assign always cause the caller to stop retrying. 
#
# The CANRECOVER bit indicates 'recoverability' (no db or physical
29
# state was modified by the time the error occurred). This is relevant
30 31 32 33 34 35 36 37 38 39 40
# to only modify operations (update).
#
my $WRAPPER_SUCCESS		 = 0x00;
my $WRAPPER_FAILED		 = 0x01;	# Failed (Add other values)
my  $WRAPPER_FAILED_CANRECOVER   = 0x40;        # Can recover from update
my  $WRAPPER_FAILED_FATALLY      = 0x80;	# Do not use this.
# Set this once we modify DB state; forces no recover in fatal().
my $NoRecover = 0;

sub usage ()
{
41
    print STDERR "Usage: $0 [-v] [-u [-f] | -n] [-z] pid eid\n";
42 43 44 45
    print STDERR " -v   - Enables verbose output\n";
    print STDERR " -u   - Enables update mode\n";
    print STDERR " -f   - Fix current resources during update mode\n";
    print STDERR " -n   - Run assign, but do not reserve/modify resources.\n";
46
    print STDERR " -r   - Regression mode.\n";
47 48
    print STDERR " -x   - Turn on the prepass\n";
    print STDERR " -m   - Set the multiplex factor; overrides experiment.\n";
49 50
    print STDERR " -p   - Do a precheck for mapability on an empty testbed - ".
		 "implies -n\n";
51
    print STDERR " -l   - Use rspec v2 instead of the text file format\n";
52
    print STDERR " -z   - Randomize node order printed by ptopgen\n";
53 54
    exit($WRAPPER_FAILED);
}
55
my $optlist    = "dvunfprqczxm:ko:altz";
56 57 58 59 60 61
my $verbose    = 0;
my $debug      = 0;
my $fixmode    = 0;
my $updating   = 0;
my $impotent   = 0;
my $precheck   = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
62
my $toponly    = 0;
63
my $prepass    = 0;
64
my $alloconly  = 0;
65
my $outfile;
66
my $mfactor;
67
my $regression = 0;
68
my $noassign   = 0;  # Only with regression mode, use previous solution.
69 70
my $noregfree  = 0;  # Only with regression mode, leave physical state at end.
my $usecurrent = 0;  # Only with regression mode, use current solution.
71 72 73
my $quiet      = 0;
my $clear      = 0;
my $warnings   = 0;
74
my $maxrun     = 3;  # Maximum number of times we run assign.
75
my $gotlock    = 0;
76
my $userspec   = 0;
77
my $randomize  = 0;
78
my $vtop;
79 80 81 82 83

#
# Configure variables
#
my $TB		= "@prefix@";
84
my $DBNAME	= "@TBDBNAME@";
85 86 87 88 89
my $TBOPS       = "@TBOPSEMAIL@";
my $ASSIGN      = "$TB/libexec/assign";
my $WRAPPER2    = "$TB/libexec/assign_wrapper2";
my $PTOPGEN     = "$TB/libexec/ptopgen";
my $VTOPGEN     = "$TB/bin/vtopgen";
90
my $NFREE       = "$TB/bin/nfree";
91 92 93 94 95 96 97 98 99 100

#
# Load the Testbed support stuff. 
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
use libvtop;
use libadminctrl;
101
use User;
102 103 104 105 106 107

# Protos
sub fatal(@);
sub debug($);
sub chat($);
sub RunAssign($$);
108
sub FinalizeRegression($);
109 110
sub AssignLoop();
sub MapperWrapper();
111
sub PrintSolution();
112 113 114 115 116 117

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

# Turn off line buffering on output
118 119 120 121 122 123 124 125 126 127
$| = 1;

#
# We want warnings to cause assign_wrapper to exit abnormally.
# 
# FIXME: Is this still needed.  "warn" is only used once.  Also this
#  will cause perl internal warnings (such as "Use of uninitialized
#  value ..."  to cause assign_wrapper to fail. -- kevina
#
$SIG{__WARN__} = sub { tbwarn $_[0];$warnings++; };
128 129 130 131 132 133 134 135 136 137 138 139 140

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV < 2) {
    usage();
}
if (defined($options{"v"})) {
141
    TBDebugTimeStampsOn();
142 143
    $verbose++;
}
144 145 146
if (defined($options{"a"})) {
    $alloconly++;
}
147 148 149
if (defined($options{"d"})) {
    $debug++;
}
150 151 152
if (defined($options{"u"})) {
    $updating = 1;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
153 154 155 156
if (defined($options{"t"})) {
    $toponly = 1;
    $quiet   = 1;
}
157 158 159 160 161 162 163 164 165
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"f"})) {
    $fixmode = 1;
}
if (defined($options{"p"})) {
    $precheck = 1;
}
166 167 168
if (defined($options{"x"})) {
    $prepass = 1;
}
169 170 171
if (defined($options{"o"})) {
    $outfile = $options{"o"};
}
172 173 174
if (defined($options{"m"})) {
    $mfactor = $options{"m"};
}
175 176 177 178 179
if (defined($options{"r"})) {
    if ($DBNAME eq "tbdb") {
	fatal("Cannot use regression mode on main DB");
    }
    $regression = 1;
Leigh B Stoller's avatar
Leigh B Stoller committed
180 181
    $clear      = 1
	if (!defined($options{"t"}));
182
    $fixmode    = 1;
183
    TBDebugTimeStampsOn();
184
    $usecurrent = 1
185
	if (defined($options{"z"}));
186 187
    $noregfree = 1
	if (defined($options{"k"}));
188 189 190 191 192 193 194
}
if (defined($options{"q"})) {
    $quiet = 1;
}
if (defined($options{"c"})) {
    $clear = 1;
}
195 196 197
if (defined($options{"l"})) {
    $userspec = 1;
}
198 199 200
if (defined($options{"z"})) {
    $randomize = 1;
}
201 202 203 204 205 206 207

my $pid = $ARGV[0];
my $eid = $ARGV[1];
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    fatal("Could not lookup experiment object $pid,$eid!")
}
208 209 210 211 212 213 214 215 216 217 218
#
# Verify that this person can muck with the experiment.
#
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
}
if (!TBAdmin() &&
    ! $experiment->AccessCheck($this_user, TB_EXPT_DESTROY)) {
    fatal("You do not have permission to map this experiment!");
}
219

220 221 222 223
# multiplex_factor default.
$mfactor = $experiment->multiplex_factor()
    if (!defined($mfactor) && defined($experiment->multiplex_factor()));
    
224 225 226 227 228 229
#
# These are the flags to the vtop creation code. 
#
my $vtopflags = 0;
$vtopflags |= $libvtop::VTOP_FLAGS_VERBOSE
    if ($verbose);
230 231
$vtopflags |= $libvtop::VTOP_FLAGS_QUIET
    if ($quiet);
232 233 234
$vtopflags |= $libvtop::VTOP_FLAGS_UPDATE
    if ($updating);
$vtopflags |= $libvtop::VTOP_FLAGS_FIXNODES
235
    if ($fixmode || $usecurrent);
236 237
$vtopflags |= $libvtop::VTOP_FLAGS_IMPOTENT
    if ($impotent);
238 239
$vtopflags |= $libvtop::VTOP_FLAGS_ALLOCONLY
    if ($alloconly);
240 241
$vtopflags |= $libvtop::VTOP_FLAGS_REGRESSION
    if ($regression);
242

243 244 245 246 247 248 249 250
MapperWrapper();
if ($regression) {
    if (0) {
	$updating   = 1;
	$fixmode    = 1;
	$clear      = 0;
	$vtopflags |=
	    ($libvtop::VTOP_FLAGS_UPDATE|$libvtop::VTOP_FLAGS_FIXNODES);
251

252 253 254
	MapperWrapper();
    }
    FinalizeRegression(0);
255
}
256 257
PrintSolution()
    if ($outfile);
258
exit(0);
259

260 261
sub MapperWrapper()
{
Leigh B Stoller's avatar
Leigh B Stoller committed
262 263
    chat("Starting the new and improved mapper wrapper.\n")
	if (!$toponly);
264

Leigh B Stoller's avatar
Leigh B Stoller committed
265 266 267 268 269
    # Need to do this cause libvtop will add them again.
    # Must be done before nodes are released.
    $experiment->DeleteInternalProgramAgents()
	if ($regression);

270
    TBDebugTimeStamp("Create libvtop started");
271
    $vtop = libvtop->Create($experiment, $this_user, $vtopflags);
272 273 274 275
    if (!defined($vtop)) {
	fatal("Could not create vtop structure for $experiment");
    }
    TBDebugTimeStamp("Create libvtop ended");
Leigh B Stoller's avatar
Leigh B Stoller committed
276

Leigh B Stoller's avatar
Leigh B Stoller committed
277 278 279 280 281
    TBDebugTimeStamp("vtopgen started");
    $vtop->CreateVtop() == 0
	or fatal("Could not create vtop for $experiment");
    TBDebugTimeStamp("vtopgen finished");
    
282
    if (!$impotent && !$alloconly && !$toponly && ($updating || $clear)) {
283 284 285 286 287 288 289 290 291 292 293 294
	if ($clear) {
	    chat("Freeing reserved nodes ...\n");
	    system("export NORELOAD=1; $NFREE -x -a $pid $eid") == 0
		or fatal("Could not release nodes.");
	}
	chat("Clearing physical state before updating.\n");
	$experiment->RemovePhysicalState();
	exit(0)
	    if ($clear && !$regression);
    }
    AssignLoop();
    return 0;
295
}
296 297 298 299

#
# The assign loop. 
#
300 301 302 303
sub AssignLoop()
{
    my $currentrun     = 1;
    my $canceled       = 0;
304
    my $noprogress     = 0;
305 306 307
    my $tried_precheck = 0;
    # Admission control counts
    my %admission_control = ();
308

309 310 311 312 313
    # XXX plab hack - only run assign once on plab topologies, since
    # they're easy to map and the physical topology does not change
    # frequently.
    if ($vtop->plabcount() && $vtop->plabcount == $vtop->virtnodecount()) {
	$maxrun = 2;
314 315
    }

316 317 318
    TBDebugTimeStamp("mapper loop started");
    while (1) {
	chat("Assign run $currentrun\n");
319

320
	my $prefix = ($debug || $regression ? "$pid-$eid" : "$pid-$eid-$$");
321 322

	#
323
	# When precheck is on, we only do one run in impotent mode and exit.
324
	#
325 326 327 328 329
	if ($precheck) {
	    $prefix  .= ".empty";
	    $impotent = 1;
	    chat("Trying assign on an empty testbed.\n");
	}
330

331 332 333
	#
	# Serialize with the pool daemon if using shared nodes.
	#
334
	if ((!($impotent || $regression)) && $vtop->sharednodecount()) {
335
	    while (1) {
336 337 338 339
		#
		# Use a countup/countdown counter, so that multiple mappers
		# can run, but not while the pool_daemon is running.
		#
340
		my $lock_result =
341 342 343 344
		    DBQueryFatal("update emulab_locks set value=value+1 ".
				 "where name='pool_daemon' and value>=0");

		$gotlock = $lock_result->affectedrows;
345 346 347 348 349

		last
		    if ($gotlock);
		
		chat("Waiting for pool daemon lock ...\n");
350
		sleep(10);
351 352 353
	    }
	}

354 355 356 357
	#
	# RunAssign returns  0 if successful.
	#           returns -1 if failure, but assign says to stop trying.
	#           returns  1 if failure, but assign says to try again.
358
	#           returns  2 if assign succeeds, but nodes were allocated
359 360 361
	#
	my $retval = RunAssign($precheck, $prefix);

362
	if ($gotlock) {
363 364 365
	    DBQueryFatal("update emulab_locks set value=value-1 ".
			 "where name='pool_daemon'");
	    $gotlock = 0;
366 367
	}

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
	# Success!
	last
	    if ($retval == 0);

	if ($retval < 0 || $regression) {
	    #
	    # Failure in assign.
	    #
	    FinalizeRegression(1)
		if ($regression);

	    fatal({type => 'primary', severity => SEV_ERROR,
		   error => ['unretriable_assign_error']},
		  "Unretriable error. Giving up.");
	}
383
    
384 385 386 387 388 389 390 391 392 393 394
	#
	# When precheck is off, we do a precheck run if the first try fails
	# to find a solution. This avoids looping on an unsolvable topology.
	#
	if (!$precheck && !$tried_precheck) {
	    chat("Trying assign on an empty testbed to verify mapability.\n");
	    my $save_impotent = $impotent;
	    $impotent  = 1;
	    my $retval = RunAssign(1, $prefix . ".empty");
	    if ($retval != 0) {
		fatal({type=>'extra', cause=>'user', severity=>SEV_ERROR,
395 396 397 398 399 400 401 402
	           error=>['infeasible_resource_assignment']}, 
		  "This experiment cannot be instantiated on this ".
                  "testbed. You have most likely asked for hardware ".
                  "this testbed does not have, such as nodes of a type ".
                  "it does not contain, or nodes with too many network ".
                  "interfaces.  You will need to modify this experiment ".
                  "before it can be swapped in - re-submitting the ".
                  "experiment as-is will always result in failure.");
403 404 405 406
	    }
	    chat("Assign succeeded on an empty testbed.\n");
	    $impotent = $save_impotent;
	    $tried_precheck = 1;
407 408
	}

409 410
	# If we made progress, keep trying until no progress twice in a row.
	if ($currentrun >= $maxrun && $noprogress) {
411 412 413 414
	    fatal({type => 'primary', severity => SEV_ERROR,
		   error => ['reached_assign_run_limit']},
		  "Reached run limit. Giving up.");
	}
415 416
	# See if we made progress or not. We try one extra time. See above.
	$noprogress = ($retval == 2);
417

418 419 420 421
	chat("Waiting 5 seconds and trying again...\n");
	sleep(5);
	$currentrun++;
    }
422
    GatherAssignStats($pid, $eid, %{ $vtop->exptstats() })
Leigh B Stoller's avatar
Leigh B Stoller committed
423
	if (! ($impotent || $alloconly || $regression || $toponly));
424 425
    TBDebugTimeStamp("mapper loop finished");
    return 0;
426 427 428 429 430 431 432 433 434
}

#
# The guts of an assign run.
#
sub RunAssign($$)
{
    my ($precheck, $prefix) = @_;

435
    my $typelimitfile = $prefix .".limits";
436 437
    my $ptopfile = $prefix . ".ptop";
    my $vtopfile = $prefix . ".vtop";
438 439 440 441
    if ($userspec) {
	$ptopfile .= ".xml";
	$vtopfile .= ".xml";
    }
442 443
    my $assignexitcode = 0;

Leigh B Stoller's avatar
Leigh B Stoller committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    #
    # Now generate a vtop file and dump it to a file.
    #
    if (! open(VTOPFILE, "> $vtopfile")) {
	tberror("Could not open $vtopfile: $!\n");
	return -1;
    }
    my $reslibvtop;
    if ($userspec == 1) {
	$reslibvtop = $vtop->PrintRspec(*VTOPFILE);
    }
    else {
	$reslibvtop = $vtop->PrintTop(*VTOPFILE);
    }
    if ($reslibvtop != 0) {
	tberror("Could not print vtop file for $experiment\n");
	return -1;
    }
    close(VTOPFILE);
    return 0
	if ($toponly);

466 467 468 469 470 471 472 473 474 475
    # Debugging hack for regression mode. Avoid really long assign runs.
    if ($regression && $noassign) {
	if (! -e "assign.log") {
	    chat("No existing assign results file!\n");
	    return -1;
	}
	chat("Using existing assign results file\n");
	goto skiprun;
    }
    
476 477 478 479
    #
    # Do admission control test, and gather the info.
    #
    my %admission_control;
480 481 482 483 484 485
    if (!$regression) {
	if (!TBAdmissionControlCheck(undef, $experiment, \%admission_control)){
	    tberror("Failed admission control checks!\n");
	    return -1;
	}
    }
486

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    #
    # Append this admission control results to ptopgen.
    #
    if (scalar(keys(%admission_control))) {
	open(TYPELIMIT, ">$typelimitfile") or
	    return -1;

	foreach my $typeclass (keys(%admission_control)) {
	    my $count = $admission_control{$typeclass};

	    print TYPELIMIT "$typeclass $count\n";
	}
	close(TYPELIMIT);
    }


503 504 505 506 507 508 509 510 511 512 513
    #
    # Snapshot physical resources.
    #
    # if updating (-u), include any resources that may already be
    # allocated to experiment in the PTOP results.
    #
    my $ptopargs = "-p $pid ";
    $ptopargs   .= "-e $eid "
	if ($updating);
    $ptopargs   .= "-u "
	if ($updating && $experiment->elabinelab());
514 515
    $ptopargs   .= "-m $mfactor "
	if (defined($mfactor));
516 517 518 519 520 521
    $ptopargs   .= "-v "
	if ($vtop->virtnodecount());
    $ptopargs   .= "-r "
	if ($vtop->remotenodecount());
    $ptopargs   .= "-S "
	if ($vtop->simnodecount());
522 523
    $ptopargs   .= "-h "
	if ($vtop->sharednodecount());
524 525 526 527
    $ptopargs	.= "-a "
    	if ($precheck);
    $ptopargs	.= "-c " . $experiment->delay_capacity() . " "
    	if (defined($experiment->delay_capacity()));
528 529 530
    if ($userspec == 1) {
	$ptopargs .= "-x -g 2 ";
    }
531 532 533
    if ($randomize == 1) {
	$ptopargs .= "-z ";
    }
534 535
    $ptopargs .= "-l $typelimitfile"
	if (scalar(keys(%admission_control)));
536 537 538 539 540

    chat("ptopargs: '$ptopargs'\n");
    TBDebugTimeStamp("ptopgen started");
    system("$PTOPGEN $ptopargs > $ptopfile");
    if ($?) {
541 542
	tberror("Failure in ptopgen\n");
	return -1;
543 544 545
    }
    TBDebugTimeStamp("ptopgen finished");

546
    if (! ($impotent || $regression || $alloconly)) {
547
	if ($experiment->Update({"maximum_nodes" => $vtop->maximum_nodes(),
548 549 550
				 "minimum_nodes" => $vtop->minimum_nodes(),
				 "virtnode_count"=> $vtop->virtnodecount() })){
	    tberror("Could not update min/max/virt nodes for $experiment\n");
551 552
	    return -1;
	}
553 554 555
    }

    # Run assign
556
    my $cmd  = "assign";
557 558 559 560 561 562
    my $args = "";
    $args .= "-f rspec " 
	if ($userspec == 1);
    $args .= "-f text "
	if ($userspec == 0);
    $args .= "$ptopfile $vtopfile";
563 564
    $args = "-P $args"
	if (!$vtop->sharednodecount());
565 566 567 568
    $args = "-uod -c .75 $args"
	if ($vtop->virtnodecount() || $vtop->simnodecount());
    $args = "-n $args"
    	if ($precheck);
569 570
    $args = "-s 123456 $args"
	if ($regression);
571 572 573
    $args .= " PN=1.0"
	if ($vtop->sharednodecount());
    
574
    # The prepass speeds up assign on big topos with virtual nodes.
575 576 577 578 579
    if ($prepass) {
    	$cmd = "assign_prepass";
    	$args = "-m $mfactor $args"
    	    if (defined($mfactor));
    }
580 581 582 583 584 585
    chat("assign command: '$cmd $args'\n");

    #
    # Fork a child to run assign. Parent spins watching the cancel flag
    # and waiting for assign to finish.
    #
586
    TBDebugTimeStamp("assign started");
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    if (my $childpid = fork()) {
	while (1) {
	    sleep(2);

	    if (waitpid($childpid, &WNOHANG) == $childpid) {
		$assignexitcode = $? >> 8;
		last;
	    }

	    # Check cancel flag.
	    if ($experiment->canceled()) {
		if ((my $pgrp = getpgrp($childpid)) > 0) {
		    kill('TERM', -$pgrp);
		    waitpid($childpid, 0);

602 603 604
		    tberror({cause => 'canceled', severity => SEV_IMMEDIATE,
			     error => ['cancel_flag']},
			    "Cancel flag set; aborting assign run!\n");
605 606 607 608 609 610 611 612 613 614 615 616
		    return -1;
		}
		# Loop again to reap child above before exit.
	    }
	}
    }
    else {
	#
	# Change our session so the child can get a killpg without killing
	# the parent. 
	#
        POSIX::setsid();
617
	exec("nice $WRAPPER2 $cmd $args > assign.log 2>&1");
618 619
	die("Could not start assign!\n");
    }
620
    TBDebugTimeStamp("assign finished");
621 622 623

    # Check cancel flag before continuing. 
    if ($experiment->canceled()) {
624 625 626
	tberror({cause => 'canceled', severity => SEV_IMMEDIATE,
		 error => ['cancel_flag']},
		"Cancel flag set; aborting assign run!\n");
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
	return -1;
    }

    # Check for possible full filesystem ...
    if (-z "assign.log") {
	tbnotice("assign.log is zero length! Stopping ...\n");
	return -1;
    }

    #
    # Saving up assign.log coz each swapin/modify is different and it
    # is nice to have every mapping for debugging and archiving
    # purposes We do not call it .log though, since we do not want it
    # copied out to the user directory every swapin. See Experiment.pm
    #
    system("/bin/cp assign.log ${prefix}.assign");

    #
    # We no longer care what assign has to say when it fails.
    # Any relevent info was already sent to stderr so just 
    # tell the caller whether we want to keep trying or not.
    #
    if ($assignexitcode) {
	return (($assignexitcode == 1) ? 1 : -1);
    }
    #
    # If we were doing the precheck, go ahead and exit now - there is no
    # useful information to parse out
    #
    if ($precheck) {
657
	chat("Precheck succeeded.\n");
658 659
	return 0;
    }
660
  skiprun:
661
    chat("Reading assign results.\n");
662 663 664 665
    if (!open(ASSIGNFP, "assign.log")) {
	print("Could not open assign logfile! $!\n");
	return -1;
    }
666 667 668
    # New solution each time.
    $vtop->ClearSolution();

669
    TBDebugTimeStamp("ReadSolution started");
670
    if ($vtop->ReadTextSolution(*ASSIGNFP) != 0) {
671 672 673 674
	print("Could not parse assign logfile! $!\n");
	return -1;
    }
    close(ASSIGNFP);
675 676
    TBDebugTimeStamp("ReadSolution ended");
    
677
    if (defined($vtop->genirspec())) {
678 679 680 681 682 683 684 685
	TBDebugTimeStamp("Map Geni Resources Started");
	if ($vtop->MapResources() != 0) {
	    print("Could not map external resources! $!\n");
	    return -1;
	}
	TBDebugTimeStamp("Map Geni Resources ended");
    }
    TBDebugTimeStamp("InterpNodes Started");
686 687 688 689
    if ($vtop->InterpNodes() != 0) {
	print("Could not interpret nodes.\n");
	return -1;
    }
690
    TBDebugTimeStamp("InterpNodes ended, AllocNodes Started");
691 692
    # Check cancel flag before continuing. 
    if ($experiment->canceled()) {
693 694 695
	tberror({cause => 'canceled', severity => SEV_IMMEDIATE,
		 error => ['cancel_flag']},
		"Cancel flag set; aborting assign run!\n");
696 697
	return -1;
    }
698 699 700
    my $retval = $vtop->AllocNodes();
    if ($retval != 0) {
	if ($retval < 1) {
701 702
	    # Could not allocate any nodes.
	    return 2;
703 704
	}
	return 1;
705
    }
706
    TBDebugTimeStamp("AllocNodes ended, InterpLinks Started");
707 708 709 710
    if ($vtop->InterpLinks() != 0) {
	print("Could not setup links\n");
	return -1;
    }
711
    TBDebugTimeStamp("InterpLinks ended, InitializePhysNodes Started");
712 713 714 715
    if ($vtop->InitializePhysNodes() != 0) {
	print("Could not InitializePhysNodes\n");
	return -1;
    }
716
    TBDebugTimeStamp("InitializePhysNodes ended");
717
    if (! ($impotent || $regression || $alloconly)) {
718 719 720 721 722 723 724
	TBDebugTimeStamp("ReserveSharedBandwidth started");
	if ($experiment->ReserveSharedBandwidth($updating) != 0) {
	    print("Could not reserve shared bandwidth\n");
	    return -1;
	}
	TBDebugTimeStamp("ReserveSharedBandwidth ended");
    }
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    return 0;
}

#
# In regression mode we want to save  the physical state and then clear
# the physical resources. 
#
sub FinalizeRegression($)
{
    my ($error) = @_;
    my $cwd;

    chomp($cwd = `/bin/pwd`);
    if (!$error) {
	chat("Saving physical state in regression mode\n");
740 741 742 743
	if (system("/bin/rm -rf $pid-$eid.pstate")) {
	    tberror("Could not clean physical state directory\n");
	    return -1;
	}
744 745
	if ($experiment->BackupPhysicalState("$cwd/$pid-$eid.pstate", 1)
	    != 0) {
746 747 748
	    print STDERR "Could not save physical state!\n";
	    exit(1);
	}
749 750 751 752 753 754 755 756 757 758 759 760
    
	# Generate a vtop file with all resources fixed.
	chat("Generating new vtop file with all resources fixed.\n");
	if (! open(VTOPFILE, "> $pid-$eid.fixed")) {
	    tberror("Could not open $pid-$eid.fixed: $!\n");
	    return -1;
	}
	if ($vtop->PrintTop(*VTOPFILE) != 0) {
	    tberror("Could not print fixed vtop file for $experiment\n");
	    return -1;
	}
	close(VTOPFILE);
761
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
762 763 764
    # Must be done before nodes are released.
    $experiment->DeleteInternalProgramAgents();
    
765 766 767
    return 0
	if ($noregfree);
    
768 769 770 771 772 773 774 775 776 777 778 779 780 781
    chat("Removing physical state in regression mode\n");
    if ($experiment->RemovePhysicalState() != 0) {
	print STDERR "Could not remove physical state!\n";
	exit(1);
    }

    if ($vtop->newreservednodes()) {
	my @newreservednodes = $vtop->newreservednodes();
	system("export NORELOAD=1; $NFREE -x $pid $eid @newreservednodes");
	if ($?) {
	    exit(1);
	}
    }
    return 0;
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
#
# Print a solution in rspec format.
#
sub PrintSolution()
{
    my $output = undef;
    
    if ($outfile ne "-") {
	if (! open(OUTFILE, "> $outfile")) {
	    tberror("Could not open $outfile: $!\n");
	    return -1;
	}
	$output = *OUTFILE;
    }
    if ($vtop->PrintSolution($output) != 0) {
	tberror("Could not print solution for $experiment\n");
	return -1;
    }
    close($output)
	if (defined($output));
    return 0;
}

807 808 809 810
# We will come through here no matter how we exit.
END {
    # Watch for getting here cause of a die()/exit() statement someplace.
    my $exitcode = $?;
811

812 813 814 815 816 817 818 819 820
    #
    # Do not want to leave this around, it will lock the pool daemon out.
    #
    if ($gotlock) {
	DBQueryFatal("update emulab_locks set value=value-1 ".
		     "where name='pool_daemon'");
	$gotlock = 0;
    }

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    if ($exitcode && $exitcode != $WRAPPER_FAILED) {
	$exitcode = $WRAPPER_FAILED|$WRAPPER_FAILED_FATALLY;
    }
    
    if ($warnings > 0) {
	tberror("$warnings warnings.\n");

	$exitcode |= $WRAPPER_FAILED;
    }

    # Set recover bit if we are going to fail.
    $exitcode = $exitcode|$WRAPPER_FAILED_CANRECOVER
	if ($exitcode && !$NoRecover);

    # And change the exitcode to be what we want it to be.
    $? = $exitcode;
837 838 839 840
}

sub fatal(@)
{
841 842 843 844 845 846 847 848 849 850 851 852 853
    #
    # Free any newly reserved nodes (in update mode) so that tbswap knows
    # it is safe to recover the experiment. If we bypass this and leave
    # through the END block then NoRecover will still be set and tbswap
    # will know to swap the experiment out. 
    #
    if ($updating) {
	if (defined($vtop)) {
	    my @newreservednodes = $vtop->newreservednodes();
	    my $NoRecover = $vtop->norecover();
	
	    if (@newreservednodes) {
		$NoRecover = 0
Leigh B. Stoller's avatar
Leigh B. Stoller committed
854
		    if (system("$NFREE -x $pid $eid @newreservednodes") == 0);
855 856 857 858 859 860 861 862
	    }
	    else {
		# When not updating this is meaningless to tbswap.
		$NoRecover = 0;
	    }
	}
    }
    
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    tberror(@_);

    # We next go to the END block above.
    exit($WRAPPER_FAILED);
}
sub debug($)
{
    if ($verbose) {
	print $_[0];
    }
}
sub chat($)
{
    if (! $quiet) {
	print $_[0];
    }
}