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

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2012 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";
47
my $SNMPIT	   = "$TBROOT/bin/snmpit";
48
my $portstats	   = "$TBROOT/bin/portstats";
Timothy Stack's avatar
Timothy Stack committed
49
my $NFSTRACESUPPORT= @NFSTRACESUPPORT@;
50
my $PGENISUPPORT   = @PROTOGENI_SUPPORT@;
51 52 53 54 55 56 57 58 59 60 61

# 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;
62
use libadminctrl;
63
use libadminmfs;
64
use libtblog;
65
use EmulabFeatures;
66
use Experiment;
67
use User;
68
use Lan;
69
use Firewall;
70 71 72 73

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

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


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

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

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

$| = 1;

100 101
my $updateReboot   = 0;
my $updateReconfig = 1;
102 103
my $update_Eventsys_restart = 0;
my $elabinelab     = 0;
104
my $plabinelab     = 0;
105 106 107 108 109
my $force          = 0;
my $noswapout      = 0;
my $genimode       = 0;
my $errors         = 0;
my $updatehosed    = 0;
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 198
# Slowly convert to using Experiment module.
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    tbdie("Could not lookup experiment object!")
}

199 200 201
#
# Print starting message.
#
202 203 204
my $exptidx = $experiment->idx();
my $state   = $experiment->state();
my $group   = $experiment->GetGroup();
205

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

210 211 212
# Sanity check the current state. 
if (!$force) {
    if ($swapop eq "in") {
213
	tbdie("Experiment should be ACTIVATING. Currently $state.")
214
	    if ($state ne EXPTSTATE_ACTIVATING);
215
    }
216
    elsif ($swapop eq "out") {
217
	tbdie("Experiment should be SWAPPING. Currently $state.")
218
	    if ($state ne EXPTSTATE_SWAPPING);
219
    }
220
    elsif ($swapop eq "modify" || $swapop eq "update") {
221
	tbdie("Experiment should be MODIFY_RESWAP. Currently $state.")
222
	    if ($state ne EXPTSTATE_MODIFY_RESWAP);
223 224
    }
}
225 226
# Get elabinelab status. See below.
if (! TBExptIsElabInElab($pid, $eid, \$elabinelab)) {
227
    tbdie("Could not get elabinelab status for experiment $pid/$eid");
228
}
229 230 231 232 233 234 235 236 237 238 239
# 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);
}
240

241 242 243 244 245 246 247 248
#
# See if we use the new version of SyncVlans.
#
my $syncvlans =
    (EmulabFeatures->FeatureEnabled("SyncVlans",
				    $this_user, $group, $experiment)
     || $pid eq "emulab-ops");

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

254 255 256
#
# Do actual swapping
#
257 258 259 260
if ($swapop eq "out") {
    #
    # Swap out
    #
261
    tblog_set_attempt(1);
262
    $errors = doSwapout(REAL);
263
}
264
elsif ($swapop eq "update" || $swapop eq "modify") {
265 266 267 268 269 270
    #
    # 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";
271
    if (! TBAdmissionControlCheck(undef, $experiment, undef)) {
272 273 274
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['admission_control_failure']},
		"Admission control failure!\n");
275 276 277 278 279 280
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
    
281 282
    #
    # Update.
283 284 285
    #
    tblog_set_attempt(1);

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

292 293 294 295 296
    #
    # 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
297

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

317
	if ($errors) {
Chad Barb's avatar
Chad Barb committed
318 319 320
	    #
	    # There were errors; see if we can recover.
	    #
321
	    my $CanRecover = 1;
Chad Barb's avatar
Chad Barb committed
322 323 324

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

328 329 330
	    if ($CanRecover) {
		print STDERR "Recovering virtual and physical state.\n";

331 332 333
		# 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. 
334 335 336 337 338
		if ($experiment->RemoveVirtualState() ||
		    $experiment->RestoreVirtualState() ||
		    $experiment->ReserveSharedBandwidth(1, 1) ||
		    $experiment->RemovePhysicalState() ||
		    $experiment->RestorePhysicalState()) {
339 340
		    print STDERR "Could not restore backed-up state; ";
		    $CanRecover = 0;
Chad Barb's avatar
Chad Barb committed
341
		}
342 343 344
		else {
		    print STDERR "Doing a recovery swap-in of old state.\n";

345
		    if (doSwapin(MODIFY_RECOVER)) {
346 347 348
			print STDERR "Could not swap in old physical state; ";
			$CanRecover = 0;
		    }
Chad Barb's avatar
Chad Barb committed
349 350
		}
	    }
351 352 353 354 355 356

	    #
	    # 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.
	    # 
357
	    if (!$CanRecover) {
358
		if ($noswapout || $elabinelab) {
359 360 361 362 363 364 365 366 367
		    print STDERR
			"No Recovery, but leaving experiment swapped in.\n";
		}
		else {
		    print STDERR
			"Recovery aborted! Swapping experiment out.\n";
		    doSwapout(CLEANUP);
		    $updatehosed = 1;
		}
368 369 370
	    }
	    else {
		print STDERR "Update recovery successful.\n";
Chad Barb's avatar
Chad Barb committed
371
	    }
372
	}
Chad Barb's avatar
Chad Barb committed
373 374
    }
}
375 376 377 378 379
elsif ($swapop eq "in") {
    #
    # Swap in
    #
    my $retries = 2;
380 381 382 383 384 385

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

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

399 400 401 402 403 404 405 406 407 408
    #
    # 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--;
409
	tblog_inc_attempt();
410

411 412
	print STDERR "Cleaning up after errors; will try again.\n";
	doSwapout(RETRY);
413

414 415
	print STDERR "Trying again...\n";
	$errors = doSwapin(RETRY);
416
    }
417 418
    if ($errors || $canceled) {
	print STDERR "Cleaning up after " .
419
	    ($canceled ? "cancelation" : "errors") . ".\n";
420
	doSwapout(CLEANUP);
421 422 423
    }
}

424 425 426 427
tblog_set_attempt(0);

TBGetCancelFlag($pid, $eid, \$canceled);
if ($canceled) {
428 429
    tberror ({type=>'summary', cause=>'canceled', 
	      severity=>SEV_IMMEDIATE, error=>['cancel_flag']},
430 431 432
	     "Experiment swap-$swapop canceled by user.");
}

433 434 435 436
#
# Write appropriate message and exit.
#
if ($errors) {
437
    print "Failingly finished swap-$swapop for $pid/$eid. ".TBTimeStamp()."\n";
438
    TBDebugTimeStamp("tbswap $swapop finished (failed)");
Chad Barb's avatar
Chad Barb committed
439

440 441
    # Pass out magic value to indicate that update failed!
    exit(1 | ($updatehosed ? 0x40 : 0));
442
}
443
print "Successfully finished swap-$swapop for $pid/$eid. " .TBTimeStamp()."\n";
444 445
TBDebugTimeStamp("tbswap $swapop finished (succeeded)");
exit(0);
446 447 448 449

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

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

464
sub doSwapout($) {
465
    my $type = shift;
466 467
    my $swapout_errors = 0;

468 469
    tblog_set_cleanup(1) if $type == CLEANUP;

470 471 472 473 474 475 476 477 478
    #
    # 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
479

480
    if (0 && $NFSTRACESUPPORT && $type == REAL) {
Timothy Stack's avatar
Timothy Stack committed
481 482
	print "Getting files accessed via NFS.\n";
	TBDebugTimeStamp("nfstrace started");
483
	system("nfstrace transfer $pid $eid");
Timothy Stack's avatar
Timothy Stack committed
484
	TBDebugTimeStamp("nfstrace finished");
485
    }
486

487
    if (! $TESTMODE) { 
488 489
	if (! ($DISABLE_EVENTS || $elabinelab)) {
	    if ($type >= RETRY ||
490
		($update_Eventsys_restart && $type == MODIFY) ) {
491
		print "Stopping the event system\n";
492
		if (system("eventsys_control stop $pid,$eid")) {
493 494 495
		    tberror({type => 'secondary', severity => SEV_SECONDARY,
			     error => ['eventsys_stop_failed']},
			    "Failed to stop the event system.");
496 497
		    $swapout_errors = 1;
		}
498 499 500 501

		#
		# Stop the location piper.
		#
502
		if (0 && -x $piper) {
503 504
		    print "Stopping the location piper\n";
		    if (system("$piper -k $pid $eid")) {
505 506 507
			tberror({type => 'secondary', severity => SEV_SECONDARY,
				 error => ['piper_stop_failed']},
				"Failed to stop location piper.");
508 509 510
			$swapout_errors = 1;
		    }
		}
511 512
	    }
	}
513 514 515 516 517 518
	
	#
	# 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).
	#
519
	if ($elabinelab && $type >= CLEANUP) {
520 521
	    print "Tearing down elabinelab. This could take a while.\n";
	    if (system("elabinelab -k $pid $eid")) {
522 523 524
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['elabinelab_tear_down_failed']},
			"Failed to teardown elabinelab!");
525 526 527 528
		$swapout_errors = 1;
	    }
	}

529 530 531 532
	#
	# Grab our per-experiment switch stack name.
	#
	my @expswitches = $experiment->SwitchList(1);
533
	my ($perexpstack,$leader,@curswitches) = 
534 535 536 537 538 539
	    GetPerExperimentSwitchStack($experiment);
	my $stackarg = "";
	if (defined($perexpstack) && (@expswitches || @curswitches)) {
	    $stackarg = "-S $perexpstack --skip-supplied";
	}

540 541 542 543 544 545 546 547 548 549
	#
	# Remove per-experiment switch stacks.
	#
	# Clean up any reserved VLAN tags in per-experiment switches so that
	# underlying logical wires can be deleted!
	#
	if ($type != MODIFY && defined($perexpstack)) {
	    # Kill tag reservations on actual swapout.
	    TBDebugTimeStamp("snmpit started");
	    print STDERR "Removing per-experiment VLANs.\n";
550
	    if (system("$SNMPIT -S $perexpstack --redirect-err -r $pid $eid")) {
551 552 553 554 555 556 557 558 559 560
		tbwarn "Failed to remove per-experiment VLANs";
	    }
	    TBDebugTimeStamp("snmpit finished");
	}
	if ($type >= RETRY && defined($perexpstack)) {
	    print STDERR "Removing per-experiment switch stack.\n";
	    DeletePerExperimentSwitchStack($experiment);
	    $stackarg = "";
	}

561
	#
Chad Barb's avatar
Chad Barb committed
562
	# Clean up any VLANs in experiment.
563
	#
564
	# When modifying an elabinelab experiment, leave the vlans intact
565
	# so that the inner networks are not suddenly disconnected.
566
	#
567 568
	if ($type != MODIFY ||
	    ($type == MODIFY && $ELABINELAB && Lan->GotTrunks($experiment))) {
569 570
	    # Kill tag reservations on actual swapout.
	    my $tagopt = ($type != MODIFY ? "-C" : "");
571 572
	    TBDebugTimeStamp("snmpit started");
	    print STDERR "Removing VLANs.\n";
573
	    if (system("$SNMPIT $stackarg --redirect-err $tagopt -r $pid $eid")) {
574 575 576
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vlan_reset_failed']},
			"Failed to reset VLANs");
577 578 579
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("snmpit finished");
580
	}
581 582 583 584 585 586 587 588 589 590 591 592 593 594
	#
	# 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";
595
		system("$SNMPIT $stackarg --redirect-err -f -C ".
596
                    join(" ", map("-o $_", @stale)));
597 598 599 600 601 602 603 604
		if ($?) {
		    tberror({type => 'summary', severity => SEV_SECONDARY,
			     error => ['vlan_reset_failed']},
			    "Failed to remove stale vlans");
		    $swapout_errors = 1;
		}
	    }
	}
605
    }
606
	
607
    if ($type >= MODIFY) {
608 609
	# XXX Do this before releasing the nodes. Needs more thought.
	$experiment->DeleteInternalProgramAgents();
610 611
    }

612 613 614
    if ($type >= RETRY) {
	print "Removing dynamic blobs.\n";
	$experiment->RemoveBlobs();
615 616 617 618 619 620 621 622 623 624 625 626

	print "Clearing shared port vlans.\n";
	if ($experiment->ClearPortLans()) {
	    tberror({type => 'summary', severity => SEV_SECONDARY,
		     error => ['vlan_reset_failed']},
		    "Failed to remove ports from shared vlans");
	    #
	    # If this fails, we cannot release the nodes cause they
	    # have ports in someone elses vlan. Bad.
	    #
	    return -1;
	}
627 628
    }

629
    if ($type >= CLEANUP) {
630 631 632 633 634 635 636 637
	#
	# 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")) {
638 639 640
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['plabinelab_tear_down_failed']},
			"Failed to teardown plabinelab!");
641 642 643 644
		$swapout_errors = 1;
	    }
	}

645 646
	#
	# We're not attempting a retry;
647
	#
648
	# Stop all of the vnodes.
649
	#
650
	if (! $TESTMODE) { 	
651 652 653
	    print "Tearing down virtual nodes.\n";
	    TBDebugTimeStamp("vnode_setup -k started");
	    if (system("vnode_setup -d -k $pid $eid")) {
654 655 656
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vnode_tear_down_failed']},
			"Failed to tear down vnodes.");
657 658 659
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup finished");
660 661
	}

662 663 664 665
	#
	# Nodes behind a firewall are treated special.
	# See undoFWNodes for details.
	#
Leigh B Stoller's avatar
Leigh B Stoller committed
666 667 668
	# Non-firewalled experiments can now be paniced, and the swapout
	# action is similar. 
	#
669 670 671 672 673
	if ($firewalled) {
	    if (undoFWNodes($experiment)) {
		tblog_set_cleanup(0);
		return 1;
	    }
674
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
675 676 677 678
	elsif ($experiment->paniced() &&
	       Firewall::Panic($experiment, 0, Firewall::PANIC_ZAP())) {
	    return 1;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
679

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
	#
	# 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);
	}
700
	if ($soaction{'command'} && doSwapoutAction($pid, $eid, %soaction)) {
701
	    tblog_set_cleanup(0);
702
	    return 1;
703 704
	}

705 706 707 708
	#
	# Clear away Geni slivers. Do not proceed if this fails.
	#
	if ($PGENISUPPORT) {
709 710
	    require libGeni;
	    
711 712 713 714 715 716
	    if (libGeni::DeleteAllSlivers($experiment, $this_user)) {
		tberror("Could not delete slivers\n");
		return 1;
	    }
	}

717 718 719 720 721 722 723 724 725 726
	#
	# Clear logical interfaces and wires. This might move to support
	# swapmod.
	#
	print "Removing logical wires.\n";
	if (Interface::Wire->DeleteLogicalWires($experiment)) {
	    tberror("Could not delete logical wires and interfaces\n");
	    return 1;
	}

727 728
	#
	# remove all nodes from the experiment.
Chad Barb's avatar
Chad Barb committed
729
	# (nfree will send them to RES_FREE_DIRTY)
730 731 732
	#
	print STDERR "Freeing nodes.\n";
	TBDebugTimeStamp("nfree started");
733
	if (system("nfree -a $pid $eid")) {
734 735 736
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['nfree_failed']},
		    "Could not free nodes.");
737 738 739
	    $swapout_errors = 1;
	}
	TBDebugTimeStamp("nfree finished");
740 741 742 743 744

	#
	# Since this is an actual swapout, 
	# reset our count of swap out nag emails sent.
	#
745 746
	DBQueryWarn("update experiments set swap_requests='', ".
		    "   sim_reswap_count='0' ".
747
		    "where eid='$eid' and pid='$pid'");
748 749
    } else {
	#
750
	# $type == RETRY or $type == MODIFY.
751 752
	# 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
753
	# (nfree will send deallocated nodes to RES_FREE_DIRTY)
754
	#
755 756 757 758 759 760 761 762
	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 ".
763 764
			 "where rv.pid='$pid' and rv.eid='$eid' and ".
			 "      rv.genisliver_idx is null");
765

766
	while (my ($node,$allocstate,$isvirt) = $db_result->fetchrow_array) {
767
	    if ($allocstate ne TBDB_ALLOCSTATE_RES_READY()) {
768 769 770 771 772 773
		if ($isvirt) {
		    push(@failedvnodes, $node);
		}
		else {
		    push(@failedpnodes, $node);
		}
774 775 776
	    }
	}

777 778 779 780 781 782 783
	#
	# 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")) {
784 785 786
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vnode_tear_down_failed']},
			"Failed to tear down vnodes.");
787 788 789 790
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup -k finished");
	}
791

792 793 794 795 796 797 798 799 800 801 802
	#
	# 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;
	    }
	}

803 804 805 806
	#
	# Release all failed nodes.
	# 
	if (@failedpnodes > 0 || @failedvnodes > 0) {
807 808
	    print STDERR "Freeing failed nodes.\n";
	    
809
	    TBDebugTimeStamp("nfree started");
Chad Barb's avatar
Chad Barb committed
810 811 812 813 814
	    #
	    # 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.
	    #
815 816
	    if (system("nfree -x $pid $eid " .
		       join(" ", (@failedpnodes, @failedvnodes)))) {
817 818 819
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['nfree_failed']},
			"Could not free nodes.");
820 821 822 823 824 825
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("nfree finished");
	}
    }

826 827 828 829 830 831 832 833 834 835 836 837
    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) {
838
	    # Are there any nodes left in the slice?
839
	    $db_result =
840 841 842 843 844 845 846 847 848
		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");
849 850

	    if (!$db_result->numrows) {
851
		print "Tearing down Slices.\n";
852
		TBDebugTimeStamp("plabslice destroy started");
853
		if (system("plabslice destroy $pid $eid")) {
854
		    tberror "Failed to tear down Slices.";
855 856 857 858 859 860 861
		    $swapout_errors = 1;
		}
		TBDebugTimeStamp("plabslice destroy finished");
	    }
	}
    }

862 863 864 865 866 867 868 869
    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
870
	# not a failed swapin(cleanup), update, or retry.
871
	#
872
	if ($type == REAL) {
873 874 875
	    print "Resetting mountpoints.\n";
	    TBDebugTimeStamp("exports started");
	    if (system("exports_setup")) {
876 877 878
		tberror({severity => SEV_WARNING,
			 error => ['mountpoint_reset_failed']},
			"Failed to reset mountpoints.");
879 880
	    }
	    TBDebugTimeStamp("exports finished");
Chad Barb's avatar
Chad Barb committed
881

882 883 884 885 886 887 888 889 890
	    #
	    # 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
891

892 893 894 895 896 897
	    print "Resetting email lists.\n";
	    TBDebugTimeStamp("genelists started");
	    if (system("genelists -t")) {
		tbwarn "Failed to reset email lists.";
	    }
	    TBDebugTimeStamp("genelists finished");
898 899 900
	}
    }

901
    #
902
    # Wipe the DB clean except during MODIFY or RETRY. In those
903 904
    #    cases, assign_wrapper will reset the DB after reading
    #    the info.
905
    #
906 907
    if ( $type >= CLEANUP ) {
	print STDERR "Resetting DB.\n";
908 909 910 911 912 913
	if (0 && $type == CLEANUP) {
	    $experiment->ClearBackupState();
	    $experiment->BackupPhysicalState();
	    $experiment->SaveBackupState();
	    $experiment->ClearBackupState();
	}
914 915
	# Add purge flag.
	$experiment->RemovePhysicalState(1);
916 917
	# Special. 
	$experiment->ClearPortRegistration();
918
	$experiment->ClearPortRange();
919
	$experiment->ClearGlobalIPAllocation();
920
    }
921

922
    tblog_set_cleanup(0);
923 924 925 926
    return $swapout_errors;
}

##
Chad Barb's avatar
Chad Barb committed
927
#
928 929
# doSwapin - Swaps experiment in.
#
Chad Barb's avatar
Chad Barb committed
930 931 932 933 934
#            Returns:
#              0 - successful swapin
#              1 - failed swapin; cleanup required.
#              3 - failed swapin; cleanup required; can retry.
#              7 - failed swapin; assign failed; no cleanup.
935 936
##

937
sub doSwapin($) {
938
    my $type = shift; 
939 940
    # Just the physnodes ...
    my @deleted_pnodes = ();
941

942 943 944 945 946 947
    # Special IP assignment. Must do before mapper runs and moves
    # IPs from virt_lans to interfaces table.
    if ($experiment->SetupNetworkFabrics()) {
	return 1;
    }

948 949 950 951
    #
    # assign_wrapper does all the virtual to physical mapping 
    # and updating the DB state.
    #
952
    
953
    if ($type > MODIFY_RECOVER) {
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
        #
        # 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 ".
970 971
			 "     (o.os is NULL or o.os='Linux' or ".
			 "      o.os='Fedora') and ".
972 973 974
			 "     e.pid='$pid' and e.eid='$eid'");

	    if ($db_result->numrows) {
975 976
		tberror "Endnodeshaping is disabled on Linux Images!";
		tberror "You must modify your experiment to swap it in.";
977 978 979 980
		return 1;
	    }
	}
	
Chad Barb's avatar
Chad Barb committed
981
	print "Mapping to physical reality ...\n";
982
	TBDebugTimeStamp("mapper wrapper started");
Chad Barb's avatar
Chad Barb committed
983 984

	#
985 986 987 988
	# 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
989 990
	#
	my $exitcode;
991 992
	my $cmd = "$mapper";
	if (EmulabFeatures->FeatureEnabled("OldMapper",
993
					   $this_user, $group, $experiment)) {
994
	    $cmd = "$wrapper";
995 996
	}
	$cmd .= " -f"
997
	    if ($type == RETRY);
998
	
999
	if (system("$cmd -u $pid $eid")) {
1000 1001
	    $exitcode = $? >> 8;

1002
	    tberror "Failed ($exitcode) to map to reality.";
1003

1004 1005
	    # Wrapper sets this bit when recovery is possible.
	    if ($exitcode & 64) {
1006
		# We can recover. 
1007
		tbreport(SEV_SECONDARY, 'assign_wrapper_failed', $exitcode);
Chad Barb's avatar
Chad Barb committed
1008
		return 7;
1009 1010
	    }
	    else {
1011
		# No recovery, no retry.
1012
		tbreport(SEV_SECONDARY, 'assign_wrapper_failed', $exitcode);
Chad Barb's avatar
Chad Barb committed
1013 1014 1015
		return 1;
	    }
	}
1016
	TBDebugTimeStamp("mapper wrapper finished");
1017

Chad Barb's avatar
Chad Barb committed
1018 1019
	print "Mapped to physical reality!\n";
    }
1020

1021
    # Check cancel flag before continuing. No retry, 
1022
    TBGetCancelFlag($pid, $eid, \$canceled);
1023 1024 1025 1026
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
1027

1028 1029 1030 1031 1032
    #
    # Create/update per-experiment switch stacks if necessary.
    # Still haven't done any vlan synch for modify.
    #
    my @expswitches = $experiment->SwitchList(1);
1033
    my ($perexpstack,$leader,@curswitches) = 
1034 1035 1036 1037 1038
	GetPerExperimentSwitchStack($experiment);
    my $stackarg = "";
    if (($type > MODIFY && @expswitches)
	|| ($type == MODIFY && (!defined($perexpstack) && @expswitches))) {
	print STDERR "Creating per-experiment switch stack.\n";
1039 1040
	AddPerExperimentSwitchStack($experiment,undef,undef,undef,undef,
				    @expswitches);
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
	$perexpstack = GetPerExperimentSwitchStackName($experiment);
    }
    elsif ($type == MODIFY && defined($perexpstack)
	   && (@expswitches || @curswitches)) {
	print STDERR "Updating per-experiment switch stack.\n";
	UpdatePerExperimentSwitchStack($experiment,@expswitches);
    }
    if (defined($perexpstack) && (@expswitches || @curswitches)) {
	print STDERR "Will configure per-experiment switch stack ($perexpstack) later.\n";
	$stackarg = "-S $perexpstack --skip-supplied";
    }

1053 1054 1055 1056 1057 1058 1059
    #
    # 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
1060
    # because the new test in nfree that prevents nodes from accidentally
1061 1062 1063 1064 1065
    # getting released when they are in a vlan.
    #
    if ($type == MODIFY) {
	my @diff = ();
	my @same = ();
1066 1067
	my $ret;

1068
	if ($ELABINELAB || !$syncvlans) {
1069 1070 1071 1072 1073 1074
	    $ret = Lan->CompareVlansWithSwitches($experiment, \@diff, \@same);
	}
	else {
	    $ret = Lan->CompareVlansWithSwitches2($experiment);
	}
	if ($ret) {
1075 1076 1077 1078 1079
	    tberror({type => 'summary', severity => SEV_SECONDARY,
		     error => ['vlan_setup_failed']},
		    "Failed to compare old vlans");
	    return 1;
	}
1080
	if ($ELABINELAB || !$syncvlans) {
1081 1082
	    if (@diff) {
		print "Removing obsolete vlans @diff\n";
1083
		system("$SNMPIT $stackarg --redirect-err -f -C ".
1084
		       join(" ", map("-o $_", @diff)));
1085 1086 1087 1088 1089 1090
		if ($?) {
		    tberror({type => 'summary', severity => SEV_SECONDARY,
			     error => ['vlan_setup_failed']},
			    "Failed to remove obsolete VLANs.");
		    return 1;
		}
1091
		if (defined($perexpstack)) {
1092
		    system("$SNMPIT -S $perexpstack --redirect-err -f -C ".
1093 1094 1095 1096 1097 1098 1099 1100
			   join(" ", map("-o $_", @diff)));
		    if ($?) {
			tberror({type => 'summary', severity => SEV_SECONDARY,
				 error => ['vlan_setup_failed']},
				"Failed to remove obsolete per-experiment VLANs.");
			return 1;
		    }
		}
1101 1102 1103 1104
	    }
	}
	else {
	    print "Synchronizing VLANs.\n";
1105
	    system("$SNMPIT $stackarg --redirect-err -X $pid $eid");
1106 1107 1108
	    if ($?) {
		tberror({type => 'summary', severity => SEV_SECONDARY,
			 error => ['vlan_setup_failed']},
1109
			"Failed to synchronize VLANs.");
1110 1111
		return 1;
	    }
1112
	    if (defined($perexpstack)) {
1113
		system("$SNMPIT -S $perexpstack --redirect-err -X $pid $eid");
1114 1115 1116 1117 1118 1119 1120
		if ($?) {
		    tberror({type => 'summary', severity => SEV_SECONDARY,
			     error => ['vlan_setup_failed']},
			    "Failed to synchronize per-experiment VLANs.");
		    return 1;
		}
	    }
1121 1122 1123
	}
    }

1124 1125 1126 1127 1128 1129 1130 1131 1132
    #
    # 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.
    #
1133
    if ($type == MODIFY || $type == UPDATE) {
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
	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);
		}
1155
		else {
1156 1157 1158
		    push(@physnodes, $node);
		}
	    }
1159 1160 1161
	    # See below.
	    @deleted_pnodes = @physnodes;
	    
1162 1163 1164
	    if (@virtnodes) {
		TBDebugTimeStamp("vnode_setup started");
		
1165
		if (system("vnode_setup -k $pid $eid @virtnodes")) {
1166
		    tberror "Failed to tear down unused virtnodes!\n";
1167 1168 1169 1170 1171
		    return 1;
		}
		TBDebugTimeStamp("vnode_setup finished");
		
		if (system("nfree $pid $eid @virtnodes")) {
1172
		    tberror "Failed to nfree unused virtnodes!\n";
1173 1174 1175 1176
		    return 1;
		}
	    }
	    if (@physnodes) {
1177 1178 1179
		if ($elabinelab) {
		    print "Removing nodes from inner elab.\n";
		    if (system("elabinelab -r $pid $eid @physnodes")) {
1180
			tberror "Failed to remove inner nodes!";