tbswap.in 44.5 KB
Newer Older
1 2 3 4
#!/usr/bin/perl -w

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2009 University of Utah and the Flux Group.
6 7 8 9
# All rights reserved.
#
use English;

10 11 12
# Returns 0 on success.
# Returns 1 on non-assign_wrapper failure.
# Returns (1 | assign_wrapper's errorcode) on assign_wrapper failure.
13 14
# Returns |0x40 if update caused a swapout. Icky.
# Returns -1 on uncontrolled error (die called).
15

16 17 18 19 20
# XXX: handle error cases for update? (backup the db?)
# XXX: Shouldn't do idempotent stuff twice for update.
# XXX: repush/calc routing for update??? (tbprerun)
# XXX: previz for update???              (tbprerun)
# XXX: make snmpit faster for update.
Chad Barb's avatar
Chad Barb committed
21 22 23
#
# XXX: for update, expt is swapped out on os_setup fail.
#      (we only recover if assign fails)
24 25 26

sub usage()
{
27 28 29
    print STDERR
	"Usage: $0 {in|out|modify [-reboot] [-eventsys_restart]} ".
	"[-noswapout] [-genimode] pid eid\n";
30 31 32 33 34 35 36
    exit(-1);
}

#
# Configure variables
#
my $TBROOT         = "@prefix@";
37
my $TBOPS          = "@TBOPSEMAIL@";
Timothy Stack's avatar
Timothy Stack committed
38
my $TBLOGS         = "@TBLOGSEMAIL@";
39
my $MAINSITE	   = @TBMAINSITE@;
40
my $ELABINELAB     = @ELABINELAB@;
41
my $THISHOMEBASE   = "@THISHOMEBASE@";
42 43
my $TESTMODE       = @TESTMODE@;
my $DISABLE_EVENTS = "@DISABLE_EVENT_SCHED@";
44
my $piper          = "$TBROOT/sbin/locpiper";
45 46
my $mapper         = "$TBROOT/bin/mapper";
my $wrapper        = "$TBROOT/libexec/assign_wrapper";
Timothy Stack's avatar
Timothy Stack committed
47
my $NFSTRACESUPPORT= @NFSTRACESUPPORT@;
48 49 50 51 52 53 54 55 56 57 58

# Untaint the path
$ENV{'PATH'} = "/usr/bin:$TBROOT/libexec:$TBROOT/libexec/ns2ir" . 
    ":$TBROOT/sbin:$TBROOT/bin";

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
59
use libadminctrl;
60
use libadminmfs;
61
use libtblog;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
62
use libArchive;
63
use Experiment;
64
use User;
65
use Lan;
66
use Firewall;
67

68
#require exitonwarn; # exitonwarn isn't really a module, so just require it
69 70 71 72

#
# Actual swap-in and swap-out functions, defined below.
#
73 74 75
sub doSwapout($);
sub doSwapin($);

76
# XXX fixme: should not be hardwired!
77
my $cnetstack = "-S Control";
78 79 80
my $cnetvlanname = "Control";


81 82 83 84
sub REAL()    { return 5; }
sub CLEANUP() { return 4; }
sub RETRY()   { return 3; }
sub MODIFY()  { return 2; }
85
sub UPDATE()  { return 1; }
86
sub MODIFY_RECOVER()  { return 0; }
87

88 89 90
#
# Grab global enable of linkdelays.
#
91
my $enablelinkdelays = TBGetSiteVar("general/linux_endnodeshaping");
92

93 94 95 96 97 98
#
# Turn off line buffering on output
#

$| = 1;

99 100
my $updateReboot   = 0;
my $updateReconfig = 1;
101 102
my $update_Eventsys_restart = 0;
my $elabinelab     = 0;
103
my $plabinelab     = 0;
104 105 106 107 108
my $force          = 0;
my $noswapout      = 0;
my $genimode       = 0;
my $errors         = 0;
my $updatehosed    = 0;
109
my $state;
110
my $canceled;
111
my $os_setup_pid;
112
my $nextState;
113 114

#
115
# First argument is either "in", "out", or "update";
116 117 118 119 120
# this value goes into $swapop.
#

my $swapop = shift;	

121 122 123
if (!$swapop || 
    (($swapop ne "in") && 
     ($swapop ne "out") &&
124
     ($swapop ne "modify") &&
125
     ($swapop ne "update"))) {
126 127 128 129 130 131 132 133 134 135 136
    usage();
}

#
# Get other arguments.
#

while ($#ARGV > 1) {
    $arg = shift;
    if ($arg eq "-force") {
	$force = 1;
Chad Barb's avatar
Chad Barb committed
137 138
    } elsif ($arg eq "-reboot") {
	$updateReboot = 1;
139
	$updateReconfig = 0;
140 141 142
    } elsif ($arg eq "-noreconfig") {
	$updateReboot   = 0;
	$updateReconfig = 0;
143
    } elsif ($arg eq "-eventsys_restart" && $swapop eq "modify") {
144
	$update_Eventsys_restart = 1;
145
    } elsif ($arg eq "-noswapout") {
146
	$noswapout = 1;
147 148 149 150 151 152 153 154 155
    } else {
	usage();
    }
}
if ($#ARGV < 1) {
    usage();
}
my ($pid,$eid) = @ARGV;

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
#
# Untaint the arguments.
#
if ($pid =~ /^([-\@\w.]+)$/) {
    $pid = $1;
}
else {
    die("Tainted argument $pid!\n");
}
if ($eid =~ /^([-\@\w.]+)$/) {
    $eid = $1;
}
else {
    die("Tainted argument $eid!\n");
}

172 173 174 175 176 177
#
# Set Error reporting info
# 
tblog_set_info($pid,$eid,$UID);

#
178
# Turn on timestamps
179
#
180 181
TBDebugTimeStampsOn();

182 183 184 185 186 187
#
# Verify user and get his DB uid and other info for later.
#
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
188
}
189 190 191
my $user_uid   = $this_user->uid();
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
192

193 194 195 196 197
# Slowly convert to using Experiment module.
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    tbdie("Could not lookup experiment object!")
}
198
my $special = ($pid eq "testbed" || $pid eq "tbres" || $pid eq "emulab-ops");
199

200 201 202
#
# Print starting message.
#
203 204
my $exptidx;
TBExptIDX($pid, $eid, \$exptidx);
205

206 207
print "Beginning swap-$swapop for $pid/$eid ($exptidx). " .
    TBTimeStampWithDate() . "\n";
208 209 210 211 212 213
TBDebugTimeStamp("tbswap $swapop started");

#
# Get experiment state; verify that experiment exists.
#
if (! ($state = ExpState($pid, $eid))) {
214
    tbdie "No such experiment $pid/$eid";
215
}
216 217 218
# Sanity check the current state. 
if (!$force) {
    if ($swapop eq "in") {
219
	tbdie("Experiment should be ACTIVATING. Currently $state.")
220
	    if ($state ne EXPTSTATE_ACTIVATING);
221
    }
222
    elsif ($swapop eq "out") {
223
	tbdie("Experiment should be SWAPPING. Currently $state.")
224
	    if ($state ne EXPTSTATE_SWAPPING);
225
    }
226
    elsif ($swapop eq "modify" || $swapop eq "update") {
227
	tbdie("Experiment should be MODIFY_RESWAP. Currently $state.")
228
	    if ($state ne EXPTSTATE_MODIFY_RESWAP);
229 230
    }
}
231 232
# Get elabinelab status. See below.
if (! TBExptIsElabInElab($pid, $eid, \$elabinelab)) {
233
    tbdie("Could not get elabinelab status for experiment $pid/$eid");
234
}
235 236 237 238 239 240 241 242 243 244 245
# and plabinelab status.
if (! TBExptIsPlabInElab($pid, $eid, \$plabinelab)) {
    tbdie("Could not get plabinelab status for experiment $pid/$eid");
}
if ($elabinelab && $plabinelab) {
    tberror "Cannot get my head around Plab in Elab in Elab!\n";
    print "Failingly finished swap-$swapop for $pid/$eid. " .
	TBTimeStamp() . "\n";
    TBDebugTimeStamp("tbswap $swapop finished (failed)");
    exit(1);
}
246

247 248 249 250 251
#
# See if the experiment is firewalled
#
my $firewalled = TBExptFirewall($pid, $eid);

252 253 254
#
# Do actual swapping
#
255 256 257 258
if ($swapop eq "out") {
    #
    # Swap out
    #
259
    tblog_set_attempt(1);
260
    $errors = doSwapout(REAL);
261
}
262
elsif ($swapop eq "update" || $swapop eq "modify") {
263 264 265 266 267 268
    #
    # Before swapout, do cursory admission control to see if the
    # modified experiment will be swappable. assign_wrapper does a
    # more stringent check using assign.
    #
    print STDERR "Checking with Admission Control ...\n";
269
    if (! TBAdmissionControlCheck(undef, $experiment, undef)) {
270 271 272
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['admission_control_failure']},
		"Admission control failure!\n");
273 274 275 276 277 278
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
    
279 280
    #
    # Update.
281 282 283
    #
    tblog_set_attempt(1);

284 285 286 287
    #
    # Phase One -- swap experiment partially out.
    #
    print STDERR "Backing up physical state...\n";
288
    $experiment->BackupPhysicalState();
289

290 291 292 293 294
    #
    # Actually, in update mode this is not done cause we are anticipating
    # adding nodes only.
    #
    $errors = ($swapop eq "modify" ? doSwapout(MODIFY) : 0);
Chad Barb's avatar
Chad Barb committed
295

296 297 298 299 300 301
    if (0) {
	print STDERR "Doing a swapmodswapout on the experiment archive ...\n";
	if (libArchive::TBExperimentArchiveSwapModSwapOut($pid, $eid) < 0) {
	    tberror("Failed swapmodswapout on the experiment archive!");
	    $errors = 1;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
302 303
    }

304
    if ($errors) {
305
	#
306
	# Clean up the mess, leaving the experiment in the SWAPPED state,
307 308 309 310 311 312 313 314
	#
	if ($noswapout) {
	    print STDERR "Leaving experiment swapped in as directed.\n";
	}
	else {
	    print STDERR "Cleaning up after errors.\n";
	    doSwapout(CLEANUP);
	}
315
	$updatehosed = 1;
316
    }
317
    else {
318
	#
319
	# Phase Two -- swap experiment back in.
320
	#
321
	$errors = doSwapin(MODIFY);
Chad Barb's avatar
Chad Barb committed
322

323
	if ($errors) {
Chad Barb's avatar
Chad Barb committed
324 325 326
	    #
	    # There were errors; see if we can recover.
	    #
327
	    my $CanRecover = 1;
Chad Barb's avatar
Chad Barb committed
328 329 330

	    if ($errors != 7) {
		print STDERR "Update failure occurred _after_ assign phase; ";
331
		$CanRecover = 0;
Chad Barb's avatar
Chad Barb committed
332 333
	    }

334 335 336
	    if ($CanRecover) {
		print STDERR "Recovering virtual and physical state.\n";

337 338 339
		# It is safe to remove the phystate since we know it was
		# backed up above, and cause we do not know if assign_wrapper
		# made it to that point before it failed. 
340 341 342 343 344
		if ($experiment->RemoveVirtualState() ||
		    $experiment->RestoreVirtualState() ||
		    $experiment->ReserveSharedBandwidth(1, 1) ||
		    $experiment->RemovePhysicalState() ||
		    $experiment->RestorePhysicalState()) {
345 346
		    print STDERR "Could not restore backed-up state; ";
		    $CanRecover = 0;
Chad Barb's avatar
Chad Barb committed
347
		}
348 349 350
		else {
		    print STDERR "Doing a recovery swap-in of old state.\n";

351
		    if (doSwapin(MODIFY_RECOVER)) {
352 353 354
			print STDERR "Could not swap in old physical state; ";
			$CanRecover = 0;
		    }
Chad Barb's avatar
Chad Barb committed
355 356
		}
	    }
357 358 359 360 361 362

	    #
	    # Some part of the recovery failed; must swap it out. swapexp
	    # (caller) will then have to do more clean up, hence the special
	    # exit status indicated by $updatehosed.
	    # 
363 364 365 366 367 368 369 370 371 372 373
	    if (!$CanRecover) {
		if ($noswapout) {
		    print STDERR
			"No Recovery, but leaving experiment swapped in.\n";
		}
		else {
		    print STDERR
			"Recovery aborted! Swapping experiment out.\n";
		    doSwapout(CLEANUP);
		    $updatehosed = 1;
		}
374 375 376
	    }
	    else {
		print STDERR "Update recovery successful.\n";
Chad Barb's avatar
Chad Barb committed
377
	    }
378
	}
Chad Barb's avatar
Chad Barb committed
379 380
    }
}
381 382 383 384 385
elsif ($swapop eq "in") {
    #
    # Swap in
    #
    my $retries = 2;
386 387 388 389 390 391

    #
    # Before real swapin, do cursory admission control. assign_wrapper does
    # a more stringent check using assign.
    #
    print STDERR "Checking with Admission Control ...\n";
392
    if (! TBAdmissionControlCheck(undef, $experiment, undef)) {
393 394 395
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['admission_control_failure']},
		"Admission control failure!\n");
396 397 398 399 400
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
401 402

    tblog_set_attempt(1);
403
    $errors = doSwapin(REAL);
Chad Barb's avatar
Chad Barb committed
404

405 406 407 408 409 410 411 412 413 414
    #
    # Attempt a retry if: 
    #   a) there were errors, 
    #   b) doswapin() indicated (via return code 3) a retry is appropriate,
    #   c) we haven't tried too many times already.
    #   d) The cancelflag has not been set.
    #   e) $TESTMODE == 0.
    #
    while ($errors == 3 && $retries && !$canceled && !$TESTMODE) {
	$retries--;
415
	tblog_inc_attempt();
416

417 418
	print STDERR "Cleaning up after errors; will try again.\n";
	doSwapout(RETRY);
419

420 421
	print STDERR "Trying again...\n";
	$errors = doSwapin(RETRY);
422
    }
423 424
    if ($errors || $canceled) {
	print STDERR "Cleaning up after " .
425
	    ($canceled ? "cancelation" : "errors") . ".\n";
426
	doSwapout(CLEANUP);
427 428 429
    }
}

430 431 432 433
tblog_set_attempt(0);

TBGetCancelFlag($pid, $eid, \$canceled);
if ($canceled) {
434 435
    tberror ({type=>'summary', cause=>'canceled', 
	      severity=>SEV_IMMEDIATE, error=>['cancel_flag']},
436 437 438
	     "Experiment swap-$swapop canceled by user.");
}

439 440 441 442
#
# Write appropriate message and exit.
#
if ($errors) {
443
    print "Failingly finished swap-$swapop for $pid/$eid. ".TBTimeStamp()."\n";
444
    TBDebugTimeStamp("tbswap $swapop finished (failed)");
Chad Barb's avatar
Chad Barb committed
445

446 447
    # Pass out magic value to indicate that update failed!
    exit(1 | ($updatehosed ? 0x40 : 0));
448
}
449
print "Successfully finished swap-$swapop for $pid/$eid. " .TBTimeStamp()."\n";
450 451
TBDebugTimeStamp("tbswap $swapop finished (succeeded)");
exit(0);
452 453 454 455

#################################

##
Chad Barb's avatar
Chad Barb committed
456
#
457 458
# doSwapout - Swaps experiment out.
#
Chad Barb's avatar
Chad Barb committed
459
#             If in REAL or CLEANUP,
460 461 462
#             this function will free all nodes for the 
#             experiment.
#
Chad Barb's avatar
Chad Barb committed
463
#             If in RETRY or UDPATE,
464 465 466 467 468 469
#             only nodes not in RES_READY will be freed.
#
#             Returns 0 on success, >0 on failure.
#
##

470
sub doSwapout($) {
471
    my $type = shift;
472 473
    my $swapout_errors = 0;

474 475
    tblog_set_cleanup(1) if $type == CLEANUP;

476 477 478 479 480 481 482 483 484
    #
    # wait for os_setup;
    # this only applies if called after a failed doswapin.
    #
    if ($os_setup_pid) {
	print "Waiting for os_setup to finish\n";
	waitpid($os_setup_pid, 0);
	undef $os_setup_pid;
    }
Chad Barb's avatar
Chad Barb committed
485

486
    if (0 && $NFSTRACESUPPORT && $type == REAL) {
Timothy Stack's avatar
Timothy Stack committed
487 488
	print "Getting files accessed via NFS.\n";
	TBDebugTimeStamp("nfstrace started");
489
	system("nfstrace transfer $pid $eid");
Timothy Stack's avatar
Timothy Stack committed
490
	TBDebugTimeStamp("nfstrace finished");
491
    }
492

493
    if (! $TESTMODE) { 
494 495
	if (! ($DISABLE_EVENTS || $elabinelab)) {
	    if ($type >= RETRY ||
496
		($update_Eventsys_restart && $type == MODIFY) ) {
497
		print "Stopping the event system\n";
498
		if (system("eventsys_control stop $pid,$eid")) {
499 500 501
		    tberror({type => 'secondary', severity => SEV_SECONDARY,
			     error => ['eventsys_stop_failed']},
			    "Failed to stop the event system.");
502 503
		    $swapout_errors = 1;
		}
504 505 506 507 508 509 510

		#
		# Stop the location piper.
		#
		if (-x $piper) {
		    print "Stopping the location piper\n";
		    if (system("$piper -k $pid $eid")) {
511 512 513
			tberror({type => 'secondary', severity => SEV_SECONDARY,
				 error => ['piper_stop_failed']},
				"Failed to stop location piper.");
514 515 516
			$swapout_errors = 1;
		    }
		}
517 518
	    }
	}
519 520 521 522 523 524
	
	#
	# Do teardown of inner elab. We must do this before we teardown the
	# vlans since the inner control network is a vlan, and we want that
	# active so inner boss can reboot the inner nodes (avoid power cycle).
	#
525
	if ($elabinelab && $type >= CLEANUP) {
526 527
	    print "Tearing down elabinelab. This could take a while.\n";
	    if (system("elabinelab -k $pid $eid")) {
528 529 530
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['elabinelab_tear_down_failed']},
			"Failed to teardown elabinelab!");
531 532 533 534
		$swapout_errors = 1;
	    }
	}

535
	#
Chad Barb's avatar
Chad Barb committed
536
	# Clean up any VLANs in experiment.
537
	#
538
	# When modifying an elabinelab experiment, leave the vlans intact
539
	# so that the inner networks are not suddenly disconnected.
540
	#
541 542
	if ($type != MODIFY ||
	    ($type == MODIFY && $ELABINELAB && Lan->GotTrunks($experiment))) {
543 544 545
	    TBDebugTimeStamp("snmpit started");
	    print STDERR "Removing VLANs.\n";
	    if (system("snmpit -r $pid $eid")) {
546 547 548
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vlan_reset_failed']},
			"Failed to reset VLANs");
549 550 551
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("snmpit finished");
552
	}
553 554 555 556 557 558 559 560 561 562 563 564 565 566
	#
	# Must check for stale vlans that we kept around in the above clause
	# since they will not be in the lans table anymore.
	#
	if ($type == CLEANUP) {
	    my @stale;
	    if (VLan->StaleVlanList($experiment, \@stale) != 0) {
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vlan_reset_failed']},
			"Failed to get stale VLANs");
		$swapout_errors = 1;
	    }
	    if (@stale) {
		print "Removing stale vlans @stale\n";
567
		system("snmpit -f ". join(" ", map("-o $_", @stale)));
568 569 570 571 572 573 574 575
		if ($?) {
		    tberror({type => 'summary', severity => SEV_SECONDARY,
			     error => ['vlan_reset_failed']},
			    "Failed to remove stale vlans");
		    $swapout_errors = 1;
		}
	    }
	}
576
    }
577
	
578
    if ($type >= CLEANUP) {
579 580 581 582 583 584 585 586
	#
	# Undo plab in elab specialness.
	# No need to worry about VLANs here, as all the special abilities
	# involve the control network.
	#
	if (! $TESTMODE && $plabinelab) {
	    print "Tearing down plabinelab.\n";
	    if (system("plabinelab -k $pid $eid")) {
587 588 589
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['plabinelab_tear_down_failed']},
			"Failed to teardown plabinelab!");
590 591 592 593
		$swapout_errors = 1;
	    }
	}

594 595
	#
	# We're not attempting a retry;
596
	#
597
	# Stop all of the vnodes.
598
	#
599
	if (! $TESTMODE) { 	
600 601 602
	    print "Tearing down virtual nodes.\n";
	    TBDebugTimeStamp("vnode_setup -k started");
	    if (system("vnode_setup -d -k $pid $eid")) {
603 604 605
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vnode_tear_down_failed']},
			"Failed to tear down vnodes.");
606 607 608
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup finished");
609 610
	}

611 612 613 614
	#
	# Nodes behind a firewall are treated special.
	# See undoFWNodes for details.
	#
615
	if ($firewalled && undoFWNodes($experiment)) {
616
	    tblog_set_cleanup(0);
617 618
	    return 1;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
619

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
	#
	# Perform swapout time admin actions.  Right now there is at most
	# one of these.  It isn't really a general mechanism, just a hook
	# for state saving or data collection during swapout.
	# A couple of important "fer now" notes:
	#
	#	We don't do this for firewalled experiments.  We need a way
	#	to "tag" the saved disk state to ensure it doesn't get
	#	instantiated outside of a firewall.
	#
	#	We only do this on REAL swapouts, and not on CLEANUPs.
	#	There are some types of CLEANUPs where we may want to
	#	do this, in particular an invocation caused by a failed
	#	modify operation, where the admin action is to save the
	#	experiment state.  So we will need to revisit this.
	#
	my %soaction = ();
	if ($type == REAL && !$firewalled) {
	    TBExptGetSwapoutAction($pid, $eid, \%soaction);
	}
640
	if ($soaction{'command'} && doSwapoutAction($pid, $eid, %soaction)) {
641
	    tblog_set_cleanup(0);
642
	    return 1;
643 644
	}

645 646
	#
	# remove all nodes from the experiment.
Chad Barb's avatar
Chad Barb committed
647
	# (nfree will send them to RES_FREE_DIRTY)
648 649 650
	#
	print STDERR "Freeing nodes.\n";
	TBDebugTimeStamp("nfree started");
651
	if (system("nfree -a $pid $eid")) {
652 653 654
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['nfree_failed']},
		    "Could not free nodes.");
655 656 657
	    $swapout_errors = 1;
	}
	TBDebugTimeStamp("nfree finished");
658 659 660 661 662

	#
	# Since this is an actual swapout, 
	# reset our count of swap out nag emails sent.
	#
663 664
	DBQueryWarn("update experiments set swap_requests='', ".
		    "   sim_reswap_count='0' ".
665
		    "where eid='$eid' and pid='$pid'");
666 667
    } else {
	#
668
	# $type == RETRY or $type == MODIFY.
669 670
	# Therefore, don't deallocate nodes which have been successfully
	# incorporated into the experiment (i.e., are RES_READY).
Chad Barb's avatar
Chad Barb committed
671
	# (nfree will send deallocated nodes to RES_FREE_DIRTY)
672
	#
673 674 675 676 677 678 679 680
	my @failedpnodes = ();
	my @failedvnodes = ();
	
	my $db_result =
	    DBQueryFatal("select rv.node_id,n.allocstate,nt.isvirtnode ".
                         "  from reserved as rv ".
			 "left join nodes as n on n.node_id = rv.node_id ".
			 "left join node_types as nt on nt.type=n.type ".
681 682
			 "where rv.pid='$pid' and rv.eid='$eid' and ".
			 "      rv.genisliver_idx is null");
683

684
	while (my ($node,$allocstate,$isvirt) = $db_result->fetchrow_array) {
685
	    if ($allocstate ne TBDB_ALLOCSTATE_RES_READY()) {
686 687 688 689 690 691
		if ($isvirt) {
		    push(@failedvnodes, $node);
		}
		else {
		    push(@failedpnodes, $node);
		}
692 693 694
	    }
	}

695 696 697 698 699 700 701
	#
	# Tear down failed vnodes. Perhaps not needed?
	# 
	if (!$TESTMODE && @failedvnodes > 0) {
	    print "Tearing down failed virtual nodes.\n";
	    TBDebugTimeStamp("vnode_setup -k started");
	    if (system("vnode_setup -d -k $pid $eid @failedvnodes")) {
702 703 704
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vnode_tear_down_failed']},
			"Failed to tear down vnodes.");
705 706 707 708
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup -k finished");
	}
709

710 711 712 713 714 715 716 717 718 719 720
	#
	# Undo plabinelab setup
	#
	if (!$TESTMODE && $plabinelab && @failedpnodes > 0) {
	    print "Removing failed nodes from inner plab.\n";
	    if (system("plabinelab -r $pid $eid @failedpnodes")) {
		tberror "Failed to remove inner nodes!";
		$swapout_errors = 1;
	    }
	}

721 722 723 724
	#
	# Release all failed nodes.
	# 
	if (@failedpnodes > 0 || @failedvnodes > 0) {
725 726
	    print STDERR "Freeing failed nodes.\n";
	    
727
	    TBDebugTimeStamp("nfree started");
Chad Barb's avatar
Chad Barb committed
728 729 730 731 732
	    #
	    # Specify -x switch so when a physical node gets freed,
	    # any virtual nodes (owned by this experiment)
	    # sitting on top of it are freed as well.
	    #
733 734
	    if (system("nfree -x $pid $eid " .
		       join(" ", (@failedpnodes, @failedvnodes)))) {
735 736 737
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['nfree_failed']},
			"Could not free nodes.");
738 739 740 741 742 743
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("nfree finished");
	}
    }

744 745 746 747 748 749 750 751 752 753 754 755
    if (! $TESTMODE) {
	#
	# If the experiment has no Plab dslice nodes left, but still has
	# a Plab slice, destroy the slice
	#

	# Does the slice exist?
	$db_result =
	    DBQueryFatal("select slicename from plab_slices ".
			 "where pid='$pid' and eid='$eid'");

	if ($db_result->numrows) {
756
	    # Are there any nodes left in the slice?
757
	    $db_result =
758 759 760 761 762 763 764 765 766
		DBQueryFatal("select r.node_id ".
			     " from plab_slices as ps".
			     " left join plab_slice_nodes as psn ".
			     "   on (ps.slicename=psn.slicename ".
			     "       and ps.plc_idx=psn.plc_idx) ".
			     " left join reserved as r ".
			     "   on psn.node_id=r.node_id ".
			     " where ps.pid='$pid' and ps.eid='$eid'".
			     "   and r.node_id is not NULL");
767 768

	    if (!$db_result->numrows) {
769
		print "Tearing down Slices.\n";
770
		TBDebugTimeStamp("plabslice destroy started");
771
		if (system("plabslice destroy $pid $eid")) {
772
		    tberror "Failed to tear down Slices.";
773 774 775 776 777 778 779
		    $swapout_errors = 1;
		}
		TBDebugTimeStamp("plabslice destroy finished");
	    }
	}
    }

780 781 782 783 784 785 786 787
    if (! $TESTMODE) {
	#
	# All of these errors are non-fatal on swapout. We find out about them
	# via email sent from the individual scripts.
	#

	#
	# Only reset mountpoints if this is an actual swapout, and
788
	# not a failed swapin(cleanup), update, or retry.
789
	#
790
	if ($type == REAL) {
791 792 793
	    print "Resetting mountpoints.\n";
	    TBDebugTimeStamp("exports started");
	    if (system("exports_setup")) {
794 795 796
		tberror({severity => SEV_WARNING,
			 error => ['mountpoint_reset_failed']},
			"Failed to reset mountpoints.");
797 798
	    }
	    TBDebugTimeStamp("exports finished");
Chad Barb's avatar
Chad Barb committed
799

800 801 802 803 804 805 806 807 808
	    #
	    # Ditto these two. 
	    #
	    print "Resetting named maps.\n";
	    TBDebugTimeStamp("named started");
	    if (system("named_setup")) {
		tbwarn "Failed to reset named map.";
	    }
	    TBDebugTimeStamp("named finished");
Chad Barb's avatar
Chad Barb committed
809

810 811 812 813 814 815
	    print "Resetting email lists.\n";
	    TBDebugTimeStamp("genelists started");
	    if (system("genelists -t")) {
		tbwarn "Failed to reset email lists.";
	    }
	    TBDebugTimeStamp("genelists finished");
816 817 818
	}
    }

819
    #
820
    # Wipe the DB clean except during MODIFY or RETRY. In those
821 822
    #    cases, assign_wrapper will reset the DB after reading
    #    the info.
823
    #
824 825
    if ( $type >= CLEANUP ) {
	print STDERR "Resetting DB.\n";
826 827 828
	$experiment->RemovePhysicalState();
	# Special. 
	$experiment->ClearPortRegistration();
829
	$experiment->DeleteInternalProgramAgents();
830
    }
831

832
    tblog_set_cleanup(0);
833 834 835 836
    return $swapout_errors;
}

##
Chad Barb's avatar
Chad Barb committed
837
#
838 839
# doSwapin - Swaps experiment in.
#
Chad Barb's avatar
Chad Barb committed
840 841 842 843 844
#            Returns:
#              0 - successful swapin
#              1 - failed swapin; cleanup required.
#              3 - failed swapin; cleanup required; can retry.
#              7 - failed swapin; assign failed; no cleanup.
845 846
##

847
sub doSwapin($) {
848
    my $type = shift; 
849 850
    # Just the physnodes ...
    my @deleted_pnodes = ();
851

852 853 854 855
    #
    # assign_wrapper does all the virtual to physical mapping 
    # and updating the DB state.
    #
856
    
857
    if ($type > MODIFY_RECOVER) {
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
        #
        # Hacky test to allow disabling of linkdelays if the node is going
        # to run Linux. See sitevar above.
        #
	if (! $enablelinkdelays) {
	    $db_result =
		DBQueryFatal("select distinct e.pid,e.eid,vl.vnode,vn.osname ".
			 "  from experiments as e ".
			 "left join virt_lans as vl on vl.pid=e.pid and ".
			 "     vl.eid=e.eid ".
			 "left join virt_nodes as vn on vn.pid=e.pid and ".
			 "     vn.eid=e.eid and vn.vname=vl.vnode ".
			 "left join os_info as o on o.osname=vn.osname and ".
			 "  (o.pid=vl.pid or o.pid='" . TBOPSPID() . "') ".
			 "where (vl.uselinkdelay!=0 or e.uselinkdelays!=0 or ".
			 "       e.forcelinkdelays!=0) and ".
874 875
			 "     (o.os is NULL or o.os='Linux' or ".
			 "      o.os='Fedora') and ".
876 877 878
			 "     e.pid='$pid' and e.eid='$eid'");

	    if ($db_result->numrows) {
879 880
		tberror "Endnodeshaping is disabled on Linux Images!";
		tberror "You must modify your experiment to swap it in.";
881 882 883 884
		return 1;
	    }
	}
	
Chad Barb's avatar
Chad Barb committed
885
	print "Mapping to physical reality ...\n";
886
	TBDebugTimeStamp("mapper wrapper started");
Chad Barb's avatar
Chad Barb committed
887 888

	#
889 890 891 892
	# Pass the -u (update) switch into assign_wrapper, which turns on
	# update mode. When doing a retry, must also fix the current nodes
	# to avoid stuff jumping around when simply trying to replace a node
	# that did not boot.
Chad Barb's avatar
Chad Barb committed
893 894
	#
	my $exitcode;
895 896
	my $cmd = "$wrapper";
	if ($pid eq "testbed" || $pid eq "tbres" || $pid eq "emulab-ops" ||
897
	    $this_user->stud() || $experiment->virtnode_count()) {
898 899 900
	    $cmd = "$mapper";
	}
	$cmd .= " -f"
901
	    if ($type == RETRY);
902
	
903
	if (system("$cmd -u $pid $eid")) {
904 905
	    $exitcode = $? >> 8;

906
	    tberror "Failed ($exitcode) to map to reality.";
907

908 909
	    # Wrapper sets this bit when recovery is possible.
	    if ($exitcode & 64) {
910
		# We can recover. 
911
		tbreport(SEV_SECONDARY, 'assign_wrapper_failed', $exitcode);
Chad Barb's avatar
Chad Barb committed
912
		return 7;
913 914
	    }
	    else {
915
		# No recovery, no retry.
916
		tbreport(SEV_SECONDARY, 'assign_wrapper_failed', $exitcode);
Chad Barb's avatar
Chad Barb committed
917 918 919
		return 1;
	    }
	}
920
	TBDebugTimeStamp("mapper wrapper finished");
921

Chad Barb's avatar
Chad Barb committed
922 923
	print "Mapped to physical reality!\n";
    }
924

925
    # Check cancel flag before continuing. No retry, 
926
    TBGetCancelFlag($pid, $eid, \$canceled);
927 928 929 930
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
931

932 933 934 935 936 937 938
    #
    # When doing a modify, we have to compare vlans to determine which
    # vlans actually changed and need to be deleted, before processing
    # the new vlans for the experiment. Note that vlans that already
    # exist on the switches will be left as is by snmpit.
    #
    # We must do this before the nfree of deleted nodes in the next section
939
    # because the new test in nfree that prevents nodes from accidentally
940 941 942 943 944
    # getting released when they are in a vlan.
    #
    if ($type == MODIFY) {
	my @diff = ();
	my @same = ();
945 946 947 948 949 950 951 952 953
	my $ret;

	if ($ELABINELAB || !$MAINSITE || !$special) {
	    $ret = Lan->CompareVlansWithSwitches($experiment, \@diff, \@same);
	}
	else {
	    $ret = Lan->CompareVlansWithSwitches2($experiment);
	}
	if ($ret) {
954 955 956 957 958
	    tberror({type => 'summary', severity => SEV_SECONDARY,
		     error => ['vlan_setup_failed']},
		    "Failed to compare old vlans");
	    return 1;
	}
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
	if ($ELABINELAB || !$MAINSITE || !$special) {
	    if (@diff) {
		print "Removing obsolete vlans @diff\n";
		system("snmpit -f ". join(" ", map("-o $_", @diff)));
		if ($?) {
		    tberror({type => 'summary', severity => SEV_SECONDARY,
			     error => ['vlan_setup_failed']},
			    "Failed to remove obsolete VLANs.");
		    return 1;
		}
	    }
	}
	else {
	    print "Synchronizing VLANs.\n";
	    system("snmpit -X $pid $eid");
974 975 976
	    if ($?) {
		tberror({type => 'summary', severity => SEV_SECONDARY,
			 error => ['vlan_setup_failed']},
977
			"Failed to synchronize VLANs.");
978 979 980 981 982
		return 1;
	    }
	}
    }

983 984 985 986 987 988 989 990 991
    #
    # Look for any nodes in RES_TEARDOWN. These need to be released,
    # and if a virtnode, they need to be torn down. We cannot wait for
    # the virtnodes to go down with the physnode they are hosted on,
    # so teardown and release the virtnodes first, and then do the
    # physnodes.
    #
    # Errors are fatal; no recovery or retry.
    #
992
    if ($type == MODIFY || $type == UPDATE) {
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
	my $allocstate = TBDB_ALLOCSTATE_RES_TEARDOWN();
	
	$db_result =
	    DBQueryFatal("select r.node_id,nt.isvirtnode,nt.isremotenode ".
			 "  from reserved as r ".
			 "left join nodes as n on n.node_id=r.node_id ".
			 "left join node_types as nt on nt.type=n.type ".
			 "where r.pid='$pid' and r.eid='$eid' and ".
			 "      n.allocstate='$allocstate'");

	if ($db_result->numrows) {
	    my @virtnodes = ();
	    my @physnodes = ();
	    
	    print "Tearing down and releasing unused nodes\n";

	    # First teardown/release virtnodes. 
	    while (my ($node,$isvirt,$isrem) = $db_result->fetchrow_array()) {
		if ($isvirt) {
		    push(@virtnodes, $node);
		}
		elsif (!$isrem) {
		    push(@physnodes, $node);
		}
	    }
1018 1019 1020
	    # See below.
	    @deleted_pnodes = @physnodes;
	    
1021 1022 1023
	    if (@virtnodes) {
		TBDebugTimeStamp("vnode_setup started");
		
1024
		if (system("vnode_setup -k $pid $eid @virtnodes")) {
1025
		    tberror "Failed to tear down unused virtnodes!\n";
1026 1027 1028 1029 1030
		    return 1;
		}
		TBDebugTimeStamp("vnode_setup finished");
		
		if (system("nfree $pid $eid @virtnodes")) {
1031
		    tberror "Failed to nfree unused virtnodes!\n";
1032 1033 1034 1035
		    return 1;
		}
	    }
	    if (@physnodes) {
1036 1037 1038
		if ($elabinelab) {
		    print "Removing nodes from inner elab.\n";
		    if (system("elabinelab -r $pid $eid @physnodes")) {
1039
			tberror "Failed to remove inner nodes!";
1040 1041
			return 1;
		    }
1042 1043 1044 1045 1046 1047
		} elsif ($plabinelab) {
		    print "Removing nodes from inner plab.\n";
		    if (system("plabinelab -r $pid $eid @physnodes")) {
			tberror "Failed to remove inner nodes!";
			return 1;
		    }
1048 1049 1050
		}

		#
1051 1052
		# If the experiment is firewalled, cleanup the nodes
		# we are releasing.
1053
		# 
1054 1055
		if ($firewalled && undoFWNodes($experiment, 1,
					       @deleted_pnodes)) {
1056 1057 1058
		    return 1;
		}
		
1059
		if (system("nfree $pid $eid @physnodes")) {
1060
		    tberror "Failed to nfree unused physnodes!\n";
1061 1062 1063 1064 1065 1066
		    return 1;
		}
	    }
	}
    }

1067 1068 1069 1070 1071 1072
    # Exit here if we are testing.
    if ($TESTMODE) {
	print "Testing run - Stopping here.\n";
	return 0;
    }

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    #
    # Handle tarballs - we might need to fetch some from URLs if the user
    # asked for that.
    #
    print "Fetching tarballs and RPMs (if any) ...\n";
    TBDebugTimeStamp("tarfiles_setup started");

    if (system("tarfiles_setup $pid $eid")) {
	#
	# No recovery for now - what would we do?
	#
1084 1085 1086
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['tarfiles_setup_failed']},
		"Failed to set up tarballs.");
1087 1088 1089 1090
	return 1;
    }
    TBDebugTimeStamp("tarfiles_setup finished");

1091 1092 1093 1094
    #
    # If there are any Plab dslice nodes in the experiment, create the
    # dslice now
    #
1095
    if ($type > MODIFY_RECOVER) {
1096 1097 1098
	# Are there any Plab nodes?  First get a list of node types in the exp;
	# if any are types hosted by any of the PLCs we know about, create
	# all slices necessary for the experiment in a single plabslice call.
1099
	$db_result =
1100 1101 1102 1103 1104 1105 1106 1107
	    DBQueryFatal("select nt.type,ppi.plc_name from nodes as n ".
			 "  left join node_types as nt on n.type = nt.type ".
			 "  left join reserved as r on r.node_id = n.node_id ".
			 "  left join plab_plc_info as ppi ".
			 "    on nt.type = ppi.node_type".
			 " where r.pid='$pid' and r.eid='$eid'".
			 "    and ppi.node_type is not NULL".
			 " group by nt.type");
1108 1109

	if ($db_result->numrows) {
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
	    my $info_str = "";
	    while (my ($nt,$plc) = $db_result->fetchrow_array()) {
		$info_str .= " $plc($nt)";
	    }
	    print "Configuring Slices for $info_str.\n";
	    TBDebugTimeStamp("plabslice started");
	    if (system("plabslice create $pid $eid")) {
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['plabslice_create_failed']},
			"Failed to configure Slices.");
		return 3;
1121
	    }
1122
	    TBDebugTimeStamp("plabslice finished");
1123 1124 1125
	}
    }

1126
    # Check cancel flag before continuing. No retry, 
1127
    TBGetCancelFlag($pid, $eid, \$canceled);
1128 1129 1130 1131
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
1132

1133 1134 1135 1136 1137 1138 1139 1140 1141
    #
    # These things need to get started before the nodes come up, so we'll
    # do them before the os_setup. Everything else can done in parallel with
    # os_setup. (Actually, these probably can too, since they should finish
    # long before the nodes reboot, but better safe than sorry)
    #
    print "Setting up mountpoints.\n";
    TBDebugTimeStamp("mountpoints started");
    if (system("exports_setup")) {
1142 1143 1144
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['mountpoints_setup_failed']},
		"Failed to setup mountpoints.");
1145 1146 1147
	return 1;
    }
    TBDebugTimeStamp("mountpoints finished");
Chad Barb's avatar
Chad Barb committed
1148

1149 1150 1151
    TBDebugTimeStamp("named started");
    print "Setting up named maps.\n";
    if (system("named_setup")) {
1152
	tbwarn "Failed to add node names to named map.";
1153 1154
	#
	# This is a non-fatal error.
Chad Barb's avatar
Chad Barb committed
1155
	#
1156 1157
    }
    TBDebugTimeStamp("named finished");
Chad Barb's avatar
Chad Barb committed
1158

Timothy Stack's avatar
Timothy Stack committed
1159 1160 1161 1162
    if ($NFSTRACESUPPORT) {
	print "Cleaning NFS traces.\n";
	TBDebugTimeStamp("nfstrace gc started");
	if (system("nfstrace gc $pid $eid")) {
1163 1164 1165
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['nfstrace_setup_failed']},
		    "Failed to setup nfstrace.");
Timothy Stack's avatar
Timothy Stack committed
1166 1167 1168
	    return 1;
	}
	TBDebugTimeStamp("nfstrace gc finished");
1169 1170
    }

1171
    # Check cancel flag before continuing. No retry, 
1172
    TBGetCancelFlag($pid, $eid, \$canceled);
1173 1174 1175 1176
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
Chad Barb's avatar
Chad Barb committed
1177

1178 1179 1180 1181
    #
    # Setup any control-net firewall.
    # This must be done before reloading and rebooting nodes.
    #
1182
    if ($firewalled && ($type == REAL || $type == MODIFY) &&
1183 1184
	doFWlans($experiment,
		 (($type == MODIFY) ? FWADDNODES : FWSETUP), undef)) {