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

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2006 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
    print STDERR "Usage: $0 -force { in | out | update [-reboot] [-eventsys_restart] } pid eid\n";
28 29 30 31 32 33 34
    exit(-1);
}

#
# Configure variables
#
my $TBROOT         = "@prefix@";
35
my $TBOPS          = "@TBOPSEMAIL@";
Timothy Stack's avatar
Timothy Stack committed
36
my $TBLOGS         = "@TBLOGSEMAIL@";
37
my $MAINSITE	   = @TBMAINSITE@;
38
my $THISHOMEBASE   = "@THISHOMEBASE@";
39 40
my $TESTMODE       = @TESTMODE@;
my $DISABLE_EVENTS = "@DISABLE_EVENT_SCHED@";
41
my $piper          = "$TBROOT/sbin/locpiper";
Timothy Stack's avatar
Timothy Stack committed
42
my $NFSTRACESUPPORT= @NFSTRACESUPPORT@;
43 44 45 46 47 48 49 50 51 52 53

# 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;
54
use libadminctrl;
55
use libadminmfs;
56
use libtblog;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
57
use libArchive;
58

59
#require exitonwarn; # exitonwarn isn't really a module, so just require it
60 61 62 63

#
# Actual swap-in and swap-out functions, defined below.
#
64 65 66
sub doSwapout($);
sub doSwapin($);

67 68 69 70
#
# Firewall stuff
# XXX maybe should be elsewhere
#
71 72 73 74 75
sub FWSETUP()     { return 1; }
sub FWADDNODES()  { return 2; }
sub FWDELNODES()  { return 3; }
sub FWTEARDOWN()  { return 4; }
sub doFW($$$$);
76 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 4; }
sub CLEANUP() { return 3; }
sub RETRY()   { return 2; }
sub UPDATE()  { return 1; }
Chad Barb's avatar
Chad Barb committed
86
sub UPDATE_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
my $force  = 0;
my $errors = 0;
106
my $updatehosed = 0;
107
my $state;
108
my $canceled;
109 110
my $os_setup_pid;
my $cleanvlans;
111
my $nextState;
112 113

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

my $swapop = shift;	

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

#
# Get other arguments.
#

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

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
#
# 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");
}

168 169 170 171 172 173
#
# Set Error reporting info
# 
tblog_set_info($pid,$eid,$UID);

#
174
# Turn on timestamps
175
#
176 177
TBDebugTimeStampsOn();

178 179 180 181 182 183
# Need this below.
my ($dbuid, $uname, $umail);
if (UNIX2DBUID($UID, \$dbuid)) {
    UserDBInfo($dbuid, \$uname, \$umail);
}

184 185 186
#
# Print starting message.
#
187 188
my $exptidx;
TBExptIDX($pid, $eid, \$exptidx);
189

190 191
print "Beginning swap-$swapop for $pid/$eid ($exptidx). " .
    TBTimeStampWithDate() . "\n";
192 193 194 195 196 197
TBDebugTimeStamp("tbswap $swapop started");

#
# Get experiment state; verify that experiment exists.
#
if (! ($state = ExpState($pid, $eid))) {
198
    tbdie "No such experiment $pid/$eid";
199
}
200 201 202
# Sanity check the current state. 
if (!$force) {
    if ($swapop eq "in") {
203
	tbdie("Experiment should be ACTIVATING. Currently $state.")
204
	    if ($state ne EXPTSTATE_ACTIVATING);
205
    }
206
    elsif ($swapop eq "out") {
207
	tbdie("Experiment should be SWAPPING. Currently $state.")
208
	    if ($state ne EXPTSTATE_SWAPPING);
209
    }
210
    elsif ($swapop eq "update") {
211
	tbdie("Experiment should be MODIFY_RESWAP. Currently $state.")
212
	    if ($state ne EXPTSTATE_MODIFY_RESWAP);
213 214
    }
}
215 216
# Get elabinelab status. See below.
if (! TBExptIsElabInElab($pid, $eid, \$elabinelab)) {
217
    tbdie("Could not get elabinelab status for experiment $pid/$eid");
218
}
219 220 221 222 223 224 225 226 227 228 229
# 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);
}
230

231 232 233 234 235
#
# See if the experiment is firewalled
#
my $firewalled = TBExptFirewall($pid, $eid);

236 237 238
#
# Do actual swapping
#
239 240 241 242
if ($swapop eq "out") {
    #
    # Swap out
    #
243
    tblog_set_attempt(1);
244
    $errors = doSwapout(REAL);
245
}
246
elsif ($swapop eq "update") {
247 248 249 250 251 252 253
    #
    # 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";
    if (! TBAdmissionControlCheck($UID, $pid, $eid, undef)) {
254 255 256
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['admission_control_failure']},
		"Admission control failure!\n");
257 258 259 260 261 262
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
    
263 264
    #
    # Update.
265 266 267
    #
    tblog_set_attempt(1);

268 269 270 271 272
    #
    # Phase One -- swap experiment partially out.
    #
    print STDERR "Backing up physical state...\n";
    TBExptBackupPhysicalState($pid,$eid);
273

274
    $errors = doSwapout(UPDATE);
Chad Barb's avatar
Chad Barb committed
275

Leigh B. Stoller's avatar
Leigh B. Stoller committed
276 277 278 279 280 281
    print STDERR "Doing a swapmodswapout on the experiment archive ...\n";    
    if (libArchive::TBExperimentArchiveSwapModSwapOut($pid, $eid) < 0) {
	tberror("Failed to do a swapmodswapout on the experiment archive!");
	$errors = 1;
    }

282
    if ($errors) {
283
	#
284 285 286 287 288
	# Clean up the mess, leaving the experiment in the SWAPPED state,
	# 
	print STDERR "Cleaning up after errors.\n";
	doSwapout(CLEANUP);
	$updatehosed = 1;
289
    }
290
    else {
291
	#
292
	# Phase Two -- swap experiment back in.
293
	#
Chad Barb's avatar
Chad Barb committed
294 295
	$errors = doSwapin(UPDATE);

296
	if ($errors) {
Chad Barb's avatar
Chad Barb committed
297 298 299
	    #
	    # There were errors; see if we can recover.
	    #
300
	    my $CanRecover = 1;
Chad Barb's avatar
Chad Barb committed
301 302 303

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

307 308 309 310 311 312 313 314
	    if ($CanRecover) {
		print STDERR "Recovering virtual and physical state.\n";

		if (TBExptRemoveVirtualState($pid, $eid) ||
		    TBExptRestoreVirtualState($pid, $eid) ||
		    TBExptRestorePhysicalState($pid,$eid)) {
		    print STDERR "Could not restore backed-up state; ";
		    $CanRecover = 0;
Chad Barb's avatar
Chad Barb committed
315
		}
316 317 318 319 320 321 322
		else {
		    print STDERR "Doing a recovery swap-in of old state.\n";

		    if (doSwapin(UPDATE_RECOVER)) {
			print STDERR "Could not swap in old physical state; ";
			$CanRecover = 0;
		    }
Chad Barb's avatar
Chad Barb committed
323 324
		}
	    }
325 326 327 328 329 330 331

	    #
	    # 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.
	    # 
	    if (! $CanRecover) {
332
		print STDERR "Recovery aborted! Swapping experiment out.\n";
Chad Barb's avatar
Chad Barb committed
333
		doSwapout(CLEANUP);
334 335 336 337
		$updatehosed = 1;
	    }
	    else {
		print STDERR "Update recovery successful.\n";
Chad Barb's avatar
Chad Barb committed
338
	    }
339
	}
Chad Barb's avatar
Chad Barb committed
340 341
    }
}
342 343 344 345 346
elsif ($swapop eq "in") {
    #
    # Swap in
    #
    my $retries = 2;
347 348 349 350 351 352 353

    #
    # Before real swapin, do cursory admission control. assign_wrapper does
    # a more stringent check using assign.
    #
    print STDERR "Checking with Admission Control ...\n";
    if (! TBAdmissionControlCheck($UID, $pid, $eid, undef)) {
354 355 356
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['admission_control_failure']},
		"Admission control failure!\n");
357 358 359 360 361
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
362 363

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

366 367 368 369 370 371 372 373 374 375
    #
    # 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--;
376
	tblog_inc_attempt();
377

378 379
	print STDERR "Cleaning up after errors; will try again.\n";
	doSwapout(RETRY);
380

381 382
	print STDERR "Trying again...\n";
	$errors = doSwapin(RETRY);
383
    }
384 385
    if ($errors || $canceled) {
	print STDERR "Cleaning up after " .
386
	    ($canceled ? "cancelation" : "errors") . ".\n";
387
	doSwapout(CLEANUP);
388 389 390
    }
}

391 392 393 394
tblog_set_attempt(0);

TBGetCancelFlag($pid, $eid, \$canceled);
if ($canceled) {
395 396
    tberror ({type=>'summary', cause=>'canceled', 
	      severity=>SEV_IMMEDIATE, error=>['cancel_flag']},
397 398 399
	     "Experiment swap-$swapop canceled by user.");
}

400 401 402 403
#
# Write appropriate message and exit.
#
if ($errors) {
404
    print "Failingly finished swap-$swapop for $pid/$eid. ".TBTimeStamp()."\n";
405
    TBDebugTimeStamp("tbswap $swapop finished (failed)");
Chad Barb's avatar
Chad Barb committed
406

407 408
    # Pass out magic value to indicate that update failed!
    exit(1 | ($updatehosed ? 0x40 : 0));
409
}
410
print "Successfully finished swap-$swapop for $pid/$eid. " .TBTimeStamp()."\n";
411 412
TBDebugTimeStamp("tbswap $swapop finished (succeeded)");
exit(0);
413 414 415 416

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

##
Chad Barb's avatar
Chad Barb committed
417
#
418 419
# doSwapout - Swaps experiment out.
#
Chad Barb's avatar
Chad Barb committed
420
#             If in REAL or CLEANUP,
421 422 423
#             this function will free all nodes for the 
#             experiment.
#
Chad Barb's avatar
Chad Barb committed
424
#             If in RETRY or UDPATE,
425 426 427 428 429 430
#             only nodes not in RES_READY will be freed.
#
#             Returns 0 on success, >0 on failure.
#
##

431 432
sub doSwapout($) {
    my $type = shift; # REAL==4, CLEANUP==3, RETRY==2, UPDATE==1.
433 434
    my $swapout_errors = 0;

435 436
    tblog_set_cleanup(1) if $type == CLEANUP;

437 438 439 440 441 442 443 444 445
    #
    # 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
446

447
    if (0 && $NFSTRACESUPPORT && $type == REAL) {
Timothy Stack's avatar
Timothy Stack committed
448 449
	print "Getting files accessed via NFS.\n";
	TBDebugTimeStamp("nfstrace started");
450
	system("nfstrace transfer $pid $eid");
Timothy Stack's avatar
Timothy Stack committed
451
	TBDebugTimeStamp("nfstrace finished");
452
    }
453

454
    if (! $TESTMODE) { 
455 456 457
	if (! ($DISABLE_EVENTS || $elabinelab)) {
	    if ($type >= RETRY ||
		($update_Eventsys_restart && $type == UPDATE) ) {
458 459
		print "Stopping the event system\n";
		if (system("eventsys_control stop $pid $eid")) {
460 461 462
		    tberror({type => 'secondary', severity => SEV_SECONDARY,
			     error => ['eventsys_stop_failed']},
			    "Failed to stop the event system.");
463 464
		    $swapout_errors = 1;
		}
465 466 467 468 469 470 471

		#
		# Stop the location piper.
		#
		if (-x $piper) {
		    print "Stopping the location piper\n";
		    if (system("$piper -k $pid $eid")) {
472 473 474
			tberror({type => 'secondary', severity => SEV_SECONDARY,
				 error => ['piper_stop_failed']},
				"Failed to stop location piper.");
475 476 477
			$swapout_errors = 1;
		    }
		}
478 479
	    }
	}
480 481 482 483 484 485
	
	#
	# 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).
	#
486
	if ($elabinelab && $type >= CLEANUP) {
487 488
	    print "Tearing down elabinelab. This could take a while.\n";
	    if (system("elabinelab -k $pid $eid")) {
489 490 491
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['elabinelab_tear_down_failed']},
			"Failed to teardown elabinelab!");
492 493 494 495
		$swapout_errors = 1;
	    }
	}

496
	#
Chad Barb's avatar
Chad Barb committed
497
	# Clean up any VLANs in experiment.
498
	#
499 500 501 502 503 504 505
	# When modifying an elabinelab experiment, leave the vlans intact
	# so that the inner networks are not suddenly disconnected!
	#
	if (! ($elabinelab && $type == UPDATE)) {
	    TBDebugTimeStamp("snmpit started");
	    print STDERR "Removing VLANs.\n";
	    if (system("snmpit -r $pid $eid")) {
506 507 508
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vlan_reset_failed']},
			"Failed to reset VLANs");
509 510 511 512 513
		$swapout_errors = 1;
	    } else {
		$cleanvlans = 0;
	    }
	    TBDebugTimeStamp("snmpit finished");
514
	}
515
    }
Chad Barb's avatar
Chad Barb committed
516

517
    if ($type >= CLEANUP) {
518 519 520 521 522 523 524 525
	#
	# 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")) {
526 527 528
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['plabinelab_tear_down_failed']},
			"Failed to teardown plabinelab!");
529 530 531 532
		$swapout_errors = 1;
	    }
	}

533 534
	#
	# We're not attempting a retry;
535
	#
536
	# Stop all of the vnodes.
537
	#
538
	if (! $TESTMODE) { 	
539 540 541
	    print "Tearing down virtual nodes.\n";
	    TBDebugTimeStamp("vnode_setup -k started");
	    if (system("vnode_setup -d -k $pid $eid")) {
542 543 544
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vnode_tear_down_failed']},
			"Failed to tear down vnodes.");
545 546 547
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup finished");
548 549
	}

550 551 552 553 554
	#
	# Nodes behind a firewall are treated special.
	# See undoFWNodes for details.
	#
	if ($firewalled && undoFWNodes($pid, $eid)) {
555
	    tblog_set_cleanup(0);
556 557
	    return 1;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
558

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
	#
	# 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);
	}
579
	if ($soaction{'command'} && doSwapoutAction($pid, $eid, %soaction)) {
580
	    tblog_set_cleanup(0);
581
	    return 1;
582 583
	}

584 585
	#
	# remove all nodes from the experiment.
Chad Barb's avatar
Chad Barb committed
586
	# (nfree will send them to RES_FREE_DIRTY)
587 588 589 590
	#
	print STDERR "Freeing nodes.\n";
	TBDebugTimeStamp("nfree started");
	if (system("nfree $pid $eid")) {
591 592 593
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['nfree_failed']},
		    "Could not free nodes.");
594 595 596
	    $swapout_errors = 1;
	}
	TBDebugTimeStamp("nfree finished");
597 598 599 600 601

	#
	# Since this is an actual swapout, 
	# reset our count of swap out nag emails sent.
	#
602
	DBQueryWarn("update experiments set swap_requests='',sim_reswap_count='0' ".
603
		    "where eid='$eid' and pid='$pid'");
604 605
    } else {
	#
606
	# $type == RETRY or $type == UPDATE.
607 608
	# 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
609
	# (nfree will send deallocated nodes to RES_FREE_DIRTY)
610
	#
611 612 613 614 615 616 617 618
	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 ".
619 620
			 "where rv.pid='$pid' and rv.eid='$eid'");

621
	while (my ($node,$allocstate,$isvirt) = $db_result->fetchrow_array) {
622
	    if ($allocstate ne TBDB_ALLOCSTATE_RES_READY()) {
623 624 625 626 627 628
		if ($isvirt) {
		    push(@failedvnodes, $node);
		}
		else {
		    push(@failedpnodes, $node);
		}
629 630 631
	    }
	}

632 633 634 635 636 637 638
	#
	# 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")) {
639 640 641
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['vnode_tear_down_failed']},
			"Failed to tear down vnodes.");
642 643 644 645
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup -k finished");
	}
646

647 648 649 650 651 652 653 654 655 656 657
	#
	# 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;
	    }
	}

658 659 660 661
	#
	# Release all failed nodes.
	# 
	if (@failedpnodes > 0 || @failedvnodes > 0) {
662 663
	    print STDERR "Freeing failed nodes.\n";
	    
664
	    TBDebugTimeStamp("nfree started");
Chad Barb's avatar
Chad Barb committed
665 666 667 668 669
	    #
	    # 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.
	    #
670 671
	    if (system("nfree -x $pid $eid " .
		       join(" ", (@failedpnodes, @failedvnodes)))) {
672 673 674
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['nfree_failed']},
			"Could not free nodes.");
675 676 677 678 679 680
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("nfree finished");
	}
    }

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    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) {
	    # Are there any dslice nodes left?
	    $db_result =
		DBQueryFatal("select n.node_id 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 ".
			     "where r.pid='$pid' and r.eid='$eid' ".
			     " and nt.isplabdslice = 1");

	    if (!$db_result->numrows) {
		print "Destroying Planetlab slice.\n";
		TBDebugTimeStamp("plabslice destroy started");
705
		if (system("plabslice destroy $pid $eid")) {
706
		    tberror "Failed to destroy Plab dslice.";
707 708 709 710 711 712 713
		    $swapout_errors = 1;
		}
		TBDebugTimeStamp("plabslice destroy finished");
	    }
	}
    }

714 715 716 717 718 719 720 721
    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
722
	# not a failed swapin(cleanup), update, or retry.
723
	#
724
	if ($type == REAL) {
725 726 727
	    print "Resetting mountpoints.\n";
	    TBDebugTimeStamp("exports started");
	    if (system("exports_setup")) {
728 729 730
		tberror({severity => SEV_WARNING,
			 error => ['mountpoint_reset_failed']},
			"Failed to reset mountpoints.");
731 732 733
	    }
	    TBDebugTimeStamp("exports finished");
	}
Chad Barb's avatar
Chad Barb committed
734

735 736 737 738
	#
	# Resetting named maps and email lists is fast and idempotent,
	# so whatever.
	#
739 740 741
	print "Resetting named maps.\n";
	TBDebugTimeStamp("named started");
	if (system("named_setup")) {
742
	    tbwarn "Failed to reset named map.";
743 744
	}
	TBDebugTimeStamp("named finished");
Chad Barb's avatar
Chad Barb committed
745

746 747
	print "Resetting email lists.\n";
	TBDebugTimeStamp("genelists started");
748
	if (system("genelists -t")) {
749
	    tbwarn "Failed to reset email lists.";
750 751 752 753
	}
	TBDebugTimeStamp("genelists finished");
    }

754
    #
755 756 757
    # Wipe the DB clean except during UPDATE or RETRY. In those
    #    cases, assign_wrapper will reset the DB after reading
    #    the info.
758
    #
759 760 761 762
    if ( $type >= CLEANUP ) {
	print STDERR "Resetting DB.\n";
	TBExptRemovePhysicalState( $pid, $eid );
    }
763

764
    tblog_set_cleanup(0);
765 766 767 768
    return $swapout_errors;
}

##
Chad Barb's avatar
Chad Barb committed
769
#
770 771
# doSwapin - Swaps experiment in.
#
Chad Barb's avatar
Chad Barb committed
772 773 774 775 776
#            Returns:
#              0 - successful swapin
#              1 - failed swapin; cleanup required.
#              3 - failed swapin; cleanup required; can retry.
#              7 - failed swapin; assign failed; no cleanup.
777 778
##

779
sub doSwapin($) {
780 781 782
    my $type = shift; # REAL==4, RETRY==2, UPDATE==1, UPDATE_RECOVER=0.
    # Just the physnodes ...
    my @deleted_pnodes = ();
783

784 785 786 787
    #
    # assign_wrapper does all the virtual to physical mapping 
    # and updating the DB state.
    #
788
    
Chad Barb's avatar
Chad Barb committed
789
    if ($type > UPDATE_RECOVER) {
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        #
        # 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 ".
806 807
			 "     (o.os is NULL or o.os='Linux' or ".
			 "      o.os='Fedora') and ".
808 809 810
			 "     e.pid='$pid' and e.eid='$eid'");

	    if ($db_result->numrows) {
811 812
		tberror "Endnodeshaping is disabled on Linux Images!";
		tberror "You must modify your experiment to swap it in.";
813 814 815 816
		return 1;
	    }
	}
	
Chad Barb's avatar
Chad Barb committed
817 818 819 820
	print "Mapping to physical reality ...\n";
	TBDebugTimeStamp("assign_wrapper started");

	#
821 822 823 824
	# 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
825 826
	#
	my $exitcode;
827 828 829
	my $wrapper = "assign_wrapper -u";
	$wrapper .= " -f"
	    if ($type == RETRY);
830
	
831
	if (system("$wrapper $pid $eid")) {
832 833
	    $exitcode = $? >> 8;

834
	    tberror "Failed ($exitcode) to map to reality.";
835

836 837
	    # Wrapper sets this bit when recovery is possible.
	    if ($exitcode & 64) {
838
		# We can recover. 
839
		tbreport(SEV_SECONDARY, 'assign_wrapper_failed', $exitcode);
Chad Barb's avatar
Chad Barb committed
840
		return 7;
841 842
	    }
	    else {
843
		# No recovery, no retry.
844
		tbreport(SEV_SECONDARY, 'assign_wrapper_failed', $exitcode);
Chad Barb's avatar
Chad Barb committed
845 846 847 848
		return 1;
	    }
	}
	TBDebugTimeStamp("assign_wrapper finished");
849

Chad Barb's avatar
Chad Barb committed
850 851
	print "Mapped to physical reality!\n";
    }
852

853
    # Check cancel flag before continuing. No retry, 
854
    TBGetCancelFlag($pid, $eid, \$canceled);
855 856 857 858
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
859

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    #
    # 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.
    #
    if ($type == UPDATE) {
	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);
		}
	    }
895 896 897
	    # See below.
	    @deleted_pnodes = @physnodes;
	    
898 899 900
	    if (@virtnodes) {
		TBDebugTimeStamp("vnode_setup started");
		
901
		if (system("vnode_setup -k $pid $eid @virtnodes")) {
902
		    tberror "Failed to tear down unused virtnodes!\n";
903 904 905 906 907
		    return 1;
		}
		TBDebugTimeStamp("vnode_setup finished");
		
		if (system("nfree $pid $eid @virtnodes")) {
908
		    tberror "Failed to nfree unused virtnodes!\n";
909 910 911 912
		    return 1;
		}
	    }
	    if (@physnodes) {
913 914 915
		if ($elabinelab) {
		    print "Removing nodes from inner elab.\n";
		    if (system("elabinelab -r $pid $eid @physnodes")) {
916
			tberror "Failed to remove inner nodes!";
917 918
			return 1;
		    }
919 920 921 922 923 924
		} elsif ($plabinelab) {
		    print "Removing nodes from inner plab.\n";
		    if (system("plabinelab -r $pid $eid @physnodes")) {
			tberror "Failed to remove inner nodes!";
			return 1;
		    }
925 926 927
		}

		#
928 929
		# If the experiment is firewalled, cleanup the nodes
		# we are releasing.
930
		# 
931
		if ($firewalled && undoFWNodes($pid, $eid, @deleted_pnodes)) {
932 933 934
		    return 1;
		}
		
935
		if (system("nfree $pid $eid @physnodes")) {
936
		    tberror "Failed to nfree unused physnodes!\n";
937 938 939 940 941 942
		    return 1;
		}
	    }
	}
    }

943 944 945 946 947 948
    # Exit here if we are testing.
    if ($TESTMODE) {
	print "Testing run - Stopping here.\n";
	return 0;
    }

949 950 951 952 953 954 955 956 957 958 959
    #
    # 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?
	#
960 961 962
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['tarfiles_setup_failed']},
		"Failed to set up tarballs.");
963 964 965 966
	return 1;
    }
    TBDebugTimeStamp("tarfiles_setup finished");

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    #
    # If there are any Plab dslice nodes in the experiment, create the
    # dslice now
    #
    if ($type > UPDATE_RECOVER) {
	# Are there any Plab nodes?
	$db_result =
	    DBQueryFatal("select n.node_id 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 ".
			 "where r.pid='$pid' and r.eid='$eid' ".
			 " and nt.isplabdslice = 1");

	if ($db_result->numrows) {
	    # Does slice already exist?
	    $db_result =
		DBQueryFatal("select slicename from plab_slices ".
			     "where pid='$pid' and eid='$eid'");

	    if (! $db_result->numrows) {
		my @plabnodes = ();
		
		while (my ($node) = $db_result->fetchrow_array()) {
		    push(@plabnodes, $node);
		}
		
		print "Creating Planetlab slice.\n";
		TBDebugTimeStamp("plabslice create started");
995
		if (system("plabslice create $pid $eid")) {
996 997 998
		    tberror({type => 'secondary', severity => SEV_SECONDARY,
			     error => ['plabslice_create_failed']},
			    "Failed to create Plab dslice");
999 1000 1001 1002 1003 1004 1005
		    return 3;
		}
		TBDebugTimeStamp("plabslice alloc finished");
	    }
	}
    }

1006
    # Check cancel flag before continuing. No retry, 
1007
    TBGetCancelFlag($pid, $eid, \$canceled);
1008 1009 1010 1011
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021
    #
    # 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")) {
1022 1023 1024
	tberror({type => 'secondary', severity => SEV_SECONDARY,
		 error => ['mountpoints_setup_failed']},
		"Failed to setup mountpoints.");
1025 1026 1027
	return 1;
    }
    TBDebugTimeStamp("mountpoints finished");
Chad Barb's avatar
Chad Barb committed
1028

1029 1030 1031
    TBDebugTimeStamp("named started");
    print "Setting up named maps.\n";
    if (system("named_setup")) {
1032
	tbwarn "Failed to add node names to named map.";
1033 1034
	#
	# This is a non-fatal error.
Chad Barb's avatar
Chad Barb committed
1035
	#
1036 1037
    }
    TBDebugTimeStamp("named finished");
Chad Barb's avatar
Chad Barb committed
1038

Timothy Stack's avatar
Timothy Stack committed
1039 1040 1041 1042
    if ($NFSTRACESUPPORT) {
	print "Cleaning NFS traces.\n";
	TBDebugTimeStamp("nfstrace gc started");
	if (system("nfstrace gc $pid $eid")) {
1043 1044 1045
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['nfstrace_setup_failed']},
		    "Failed to setup nfstrace.");
Timothy Stack's avatar
Timothy Stack committed
1046 1047 1048
	    return 1;
	}
	TBDebugTimeStamp("nfstrace gc finished");
1049 1050
    }

1051
    # Check cancel flag before continuing. No retry, 
1052
    TBGetCancelFlag($pid, $eid, \$canceled);
1053 1054 1055 1056
    if ($canceled) {
	tbreport(SEV_IMMEDIATE, 'cancel_flag');
	return 1
    }
Chad Barb's avatar
Chad Barb committed
1057

1058 1059 1060 1061
    #
    # Setup any control-net firewall.
    # This must be done before reloading and rebooting nodes.
    #
1062 1063
    if ($firewalled && ($type == REAL || $type == UPDATE) &&
	doFW($pid, $eid, (($type == UPDATE) ? FWADDNODES : FWSETUP), undef)) {
1064 1065 1066
	return 1;
    }

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    #
    # PlabinElab setup.  This is currently just tweaking out the dhcpd.conf
    # file and that must be done before os_setup (i.e., before nodes are
    # rebooted).
    #
    if ($plabinelab && !$TESTMODE && $type > UPDATE_RECOVER) {
	# for UPDATE and RETRY we pass in the -u to pick up new nodes
	my $optarg = ($type == REAL ? "" : "-u");
	
	print "Setting up plabinelab.\n";
	TBDebugTimeStamp("plabinelab setup started");
	if (system("plabinelab $optarg $pid $eid")) {
1079 1080 1081
	    tberror({type => 'secondary', severity => SEV_SECONDARY,
		     error => ['plabinelab_setup_failed']},
		    "Failed to setup plabinelab!");
1082 1083 1084 1085 1086
	    return 1;
	}
	TBDebugTimeStamp("plabinelab setup finished");
    }

Chad Barb's avatar
Chad Barb committed
1087 1088
    #
    # If user specified -reboot to update,
1089
    # and we are successfully performing the update,
1090
    # then mark all nodes in experiment so os_setup will reboot them.
1091 1092
    # We must reboot nodes on a RETRY as well, since assign has been rerun
    # and may have remapped interfaces on the nodes.
Chad Barb's avatar
Chad Barb committed
1093
    #
1094 1095
    if ($type == RETRY ||
	($type == UPDATE && ($updateReboot || $updateReconfig))) {
Mike Hibler's avatar
Mike Hibler committed
1096
	my $needreboot = ($type == RETRY || $updateReboot) ? 1 : 0;
1097

Mike Hibler's avatar
Mike Hibler committed
1098 1099
	print STDERR "Marking nodes for ",
		     $needreboot ? "reboot" : "reconfig", ".\n";
Chad Barb's avatar
Chad Barb committed
1100
	$db_result =
1101 1102 1103
	    DBQueryFatal("select r.node_id,n.allocstate from reserved as r ".
			 "left join nodes as n on n.node_id=r.node_id ".
			 "where r.pid='$pid' and r.eid='$eid'");
Chad Barb's avatar
Chad Barb committed
1104

1105 1106 1107 1108 1109 1110 1111 1112
	while (my ($node,$allocstate) = $db_result->fetchrow_array) {
	    #
	    # If the node is INIT_CLEAN, leave it alone. It will still get
	    # rebooted, but will not falsely be tagged as dirty. This is
	    # important for vnodes too, where INIT_CLEAN indicated the vnode
	    # does not even exist yet (plab nodes).
	    #
	    if ($allocstate ne TBDB_ALLOCSTATE_RES_INIT_CLEAN()) {
1113
		TBSetNodeAllocState($node,
1114
				    ($needreboot ?
1115 1116
				     TBDB_ALLOCSTATE_RES_INIT_DIRTY() :
				     TBDB_ALLOCSTATE_RES_RECONFIG()));
1117
	    }
Chad Barb's avatar
Chad Barb committed
1118 1119 1120
	}
    }

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    #
    # Lets run gentopofile again, so we get ltmap right. This will come out
    # later, most likely.
    #
    TBDebugTimeStamp("gentopofile started");
    print "Generating ltmap (again) ...\n";

    if (system("gentopofile $pid $eid")) {
        tberror("gentopofile failed!");
	return 1;
    }
    TBDebugTimeStamp("gentopofile finished");

1134
    # XXX fer now hack
1135
    if (0 && !$firewalled && !$elabinelab && !$plabinelab &&
1136
	($pid eq "testbed" || $pid eq "tbres")) {
1137 1138 1139 1140 1141
	DBQueryWarn("update experiments set ".
		    "    savedisk=1 where pid='$pid' and eid='$eid'");
    }


1142 1143 1144 1145 1146
    #
    # Since it'll take a while for the nodes to reboot, we'll start now, and
    # wait for the os_setup to finish, down below
    #
    print "Resetting OS and rebooting.\n";
1147
    TBDebugTimeStamp("launching os_setup");
1148 1149 1150
    if (!($os_setup_pid = fork())) { 
	exec("os_setup $pid $eid") or return 1;
    } elsif ($os_setup_pid == -1) {
1151
	tberror "Fork failed.";
1152 1153
	return 1;
    }
Chad Barb's avatar
Chad Barb committed
1154

1155
    #
1156 1157 1158 1159 1160
    # XXX
    # Don't add any steps between here and the waitpid() call below
    # without verifying that 1) It's OK for nodes to come up before
    # the step has completed and 2) It's OK for the command to run in
    # parallel with os_setup (no DB dependencies, etc.)
1161 1162 1163 1164 1165
    #

    print "Setting up VLANs.\n";
    TBDebugTimeStamp("snmpit started");
    if (system("snmpit -t $pid $eid")) {
1166 1167 1168
	tberror({type => 'summary', severity => SEV_SECONDARY,
		 error => ['vlan_setup_failed']},
		"Failed to set up VLANs.");
1169 1170 1171
	return 1;
    }
    TBDebugTimeStamp("snmpit finished");
Chad Barb's avatar
Chad Barb committed
1172

1173 1174 1175 1176
    #
    # An error now means that the VLANS need to be cleaned up.
    #
    $cleanvlans = 1;
Chad Barb's avatar
Chad Barb committed
1177

1178 1179
    print "Setting up email lists.\n";
    TBDebugTimeStamp("genelists started");
1180
    if (system("genelists -t")) {
1181
	tbwarn "Failed to update email lists.";
1182 1183 1184 1185 1186
	#
	# This is a non-fatal error.
	# 
    }
    TBDebugTimeStamp("genelists finished");
Chad Barb's avatar
Chad Barb committed
1187

1188 1189 1190 1191 1192 1193 1194 1195
    #
    # Don't clear port counters on UPDATE.
    # (XXX should clear new nodes' port counters.)

    if ($type >= RETRY) {
	print "Clearing port counters.\n";
	TBDebugTimeStamp("portstats started");
	if (system("portstats -z -a -q $pid $eid")) {
1196
	    tbwarn "Failed to clear port counters.";
1197 1198 1199 1200 1201
	    #
	    # This is a non-fatal error.
	    # 
	}
	TBDebugTimeStamp("portstats finished");
1202
    }
Chad Barb's avatar
Chad Barb committed
1203

1204 1205 1206 1207 1208 1209 1210
    #
    # OK, let's see how that os_setup did
    #
    $kid = waitpid($os_setup_pid,0);
    if ($kid == $os_setup_pid) {
	undef $os_setup_pid; # Make sure doswapout() doesn't wait for it.
	if ($CHILD_ERROR) {
1211
	    tberror "Failed to reset OS and reboot nodes.";
1212 1213 1214 1215 1216 1217 1218 1219 1220
	    #
	    # If there is a firewall involved, it could be that the
	    # firewall rules are preventing essential communication,
	    # so don't retry.
	    #
	    # XXX should only do this if the user has specified additional
	    # rules.  But right now, I may screw up too!
	    #
	    if ($firewalled) {
1221 1222 1223 1224
		tberror({type => 'secondary', severity => SEV_SECONDARY,
			 error => ['os_node_reset_failed', 'firewall']},
			"Not retrying, ".
			"possibly an error in firewall setup or configuration.");
1225 1226 1227
		return 1;
	    }

1228
	    #
1229 1230
	    # Use returncode from os_setup process to
	    # set global $retry flag, indicating to caller
1231 1232 1233
	    # that it may be beneficial to attempt
	    # a doSwapin() again.
	    #
1234
            if (($CHILD_ERROR >> 8) == 1) {
1235
		tbreport(SEV_SECONDARY, 'os_node_reset_failed', 'retry');
Chad Barb's avatar
Chad Barb committed
1236
		return 3;