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

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2005 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 $THISHOMEBASE   = "@THISHOMEBASE@";
38 39
my $TESTMODE       = @TESTMODE@;
my $DISABLE_EVENTS = "@DISABLE_EVENT_SCHED@";
40
my $piper          = "$TBROOT/sbin/locpiper";
Timothy Stack's avatar
Timothy Stack committed
41
my $NFSTRACESUPPORT= @NFSTRACESUPPORT@;
42 43 44 45 46 47 48 49 50 51 52

# 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;
53
use libadminctrl;
54
use libadminmfs;
55 56
use libtblog;

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

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

65 66 67 68
#
# Firewall stuff
# XXX maybe should be elsewhere
#
69 70 71 72 73
sub FWSETUP()     { return 1; }
sub FWADDNODES()  { return 2; }
sub FWDELNODES()  { return 3; }
sub FWTEARDOWN()  { return 4; }
sub doFW($$$$);
74 75

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


80 81 82 83
sub REAL()    { return 4; }
sub CLEANUP() { return 3; }
sub RETRY()   { return 2; }
sub UPDATE()  { return 1; }
Chad Barb's avatar
Chad Barb committed
84
sub UPDATE_RECOVER()  { return 0; }
85

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

91 92 93 94 95 96
#
# Turn off line buffering on output
#

$| = 1;

97 98
my $updateReboot   = 0;
my $updateReconfig = 1;
99 100
my $update_Eventsys_restart = 0;
my $elabinelab     = 0;
101 102
my $force  = 0;
my $errors = 0;
103
my $updatehosed = 0;
104
my $state;
105
my $canceled;
106 107
my $os_setup_pid;
my $cleanvlans;
108
my $nextState;
109 110

#
111
# First argument is either "in", "out", or "update";
112 113 114 115 116
# this value goes into $swapop.
#

my $swapop = shift;	

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

#
# Get other arguments.
#

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

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

165 166 167 168 169 170
#
# Set Error reporting info
# 
tblog_set_info($pid,$eid,$UID);

#
171
# Turn on timestamps
172
#
173 174
TBDebugTimeStampsOn();

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

181 182 183
#
# Print starting message.
#
184 185
my $exptidx;
TBExptIDX($pid, $eid, \$exptidx);
186

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

#
# Get experiment state; verify that experiment exists.
#
if (! ($state = ExpState($pid, $eid))) {
195
    tbdie "No such experiment $pid/$eid";
196
}
197 198 199
# Sanity check the current state. 
if (!$force) {
    if ($swapop eq "in") {
200
	tbdie("Experiment should be ACTIVATING. Currently $state.")
201
	    if ($state ne EXPTSTATE_ACTIVATING);
202
    }
203
    elsif ($swapop eq "out") {
204
	tbdie("Experiment should be SWAPPING. Currently $state.")
205
	    if ($state ne EXPTSTATE_SWAPPING);
206
    }
207
    elsif ($swapop eq "update") {
208
	tbdie("Experiment should be MODIFY_RESWAP. Currently $state.")
209
	    if ($state ne EXPTSTATE_MODIFY_RESWAP);
210 211
    }
}
212 213
# Get elabinelab status. See below.
if (! TBExptIsElabInElab($pid, $eid, \$elabinelab)) {
214
    tbdie("Could not get elabinelab status for experiment $pid/$eid");
215
}
216

217 218 219 220 221
#
# See if the experiment is firewalled
#
my $firewalled = TBExptFirewall($pid, $eid);

222 223 224
#
# Do actual swapping
#
225 226 227 228 229
if ($swapop eq "out") {
    #
    # Swap out
    #
    $errors = doSwapout(REAL);
230
}
231
elsif ($swapop eq "update") {
232 233 234 235 236 237 238 239 240 241 242 243 244 245
    #
    # 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)) {
	print STDERR "Admission control failure!\n";
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
    
246 247 248 249 250 251 252
    #
    # Update.
    #
    # Phase One -- swap experiment partially out.
    #
    print STDERR "Backing up physical state...\n";
    TBExptBackupPhysicalState($pid,$eid);
253

254
    $errors = doSwapout(UPDATE);
Chad Barb's avatar
Chad Barb committed
255

256
    if ($errors) {
257
	#
258 259 260 261 262
	# Clean up the mess, leaving the experiment in the SWAPPED state,
	# 
	print STDERR "Cleaning up after errors.\n";
	doSwapout(CLEANUP);
	$updatehosed = 1;
263
    }
264
    else {
265
	#
266
	# Phase Two -- swap experiment back in.
267
	#
Chad Barb's avatar
Chad Barb committed
268 269
	$errors = doSwapin(UPDATE);

270
	if ($errors) {
Chad Barb's avatar
Chad Barb committed
271 272 273
	    #
	    # There were errors; see if we can recover.
	    #
274
	    my $CanRecover = 1;
Chad Barb's avatar
Chad Barb committed
275 276 277

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

281 282 283 284 285 286 287 288
	    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
289
		}
290 291 292 293 294 295 296
		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
297 298
		}
	    }
299 300 301 302 303 304 305

	    #
	    # 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) {
306
		print STDERR "Recovery aborted! Swapping experiment out.\n";
Chad Barb's avatar
Chad Barb committed
307
		doSwapout(CLEANUP);
308 309 310 311
		$updatehosed = 1;
	    }
	    else {
		print STDERR "Update recovery successful.\n";
Chad Barb's avatar
Chad Barb committed
312
	    }
313
	}
Chad Barb's avatar
Chad Barb committed
314 315
    }
}
316 317 318 319 320
elsif ($swapop eq "in") {
    #
    # Swap in
    #
    my $retries = 2;
321 322 323 324 325 326 327 328 329 330 331 332 333

    #
    # 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)) {
	print STDERR "Admission control failure!\n";
	print "Failingly finished swap-$swapop for $pid/$eid. " .
	    TBTimeStamp() . "\n";
	TBDebugTimeStamp("tbswap $swapop finished (failed)");
	exit(1);
    }
334 335
    
    $errors = doSwapin(REAL);
Chad Barb's avatar
Chad Barb committed
336

337 338 339 340 341 342 343 344 345 346
    #
    # 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--;
347

348 349
	print STDERR "Cleaning up after errors; will try again.\n";
	doSwapout(RETRY);
350

351 352
	print STDERR "Trying again...\n";
	$errors = doSwapin(RETRY);
353
    }
354 355
    if ($errors || $canceled) {
	print STDERR "Cleaning up after " .
356
	    ($canceled ? "cancelation" : "errors") . ".\n";
357
	doSwapout(CLEANUP);
358 359 360 361 362 363 364
    }
}

#
# Write appropriate message and exit.
#
if ($errors) {
365
    print "Failingly finished swap-$swapop for $pid/$eid. ".TBTimeStamp()."\n";
366
    TBDebugTimeStamp("tbswap $swapop finished (failed)");
Chad Barb's avatar
Chad Barb committed
367

368 369
    # Pass out magic value to indicate that update failed!
    exit(1 | ($updatehosed ? 0x40 : 0));
370
}
371
print "Successfully finished swap-$swapop for $pid/$eid. " .TBTimeStamp()."\n";
372 373
TBDebugTimeStamp("tbswap $swapop finished (succeeded)");
exit(0);
374 375 376 377

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

##
Chad Barb's avatar
Chad Barb committed
378
#
379 380
# doSwapout - Swaps experiment out.
#
Chad Barb's avatar
Chad Barb committed
381
#             If in REAL or CLEANUP,
382 383 384
#             this function will free all nodes for the 
#             experiment.
#
Chad Barb's avatar
Chad Barb committed
385
#             If in RETRY or UDPATE,
386 387 388 389 390 391
#             only nodes not in RES_READY will be freed.
#
#             Returns 0 on success, >0 on failure.
#
##

392 393
sub doSwapout($) {
    my $type = shift; # REAL==4, CLEANUP==3, RETRY==2, UPDATE==1.
394 395 396 397 398 399 400 401 402 403 404
    my $swapout_errors = 0;

    #
    # 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
405

Timothy Stack's avatar
Timothy Stack committed
406 407 408
    if ($NFSTRACESUPPORT) {
	print "Getting files accessed via NFS.\n";
	TBDebugTimeStamp("nfstrace started");
409
	system("nfstrace transfer $pid $eid");
Timothy Stack's avatar
Timothy Stack committed
410
	TBDebugTimeStamp("nfstrace finished");
411
    }
412

413
    if (! $TESTMODE) { 
414 415 416
	if (! ($DISABLE_EVENTS || $elabinelab)) {
	    if ($type >= RETRY ||
		($update_Eventsys_restart && $type == UPDATE) ) {
417 418
		print "Stopping the event system\n";
		if (system("eventsys_control stop $pid $eid")) {
419
		    tberror "Failed to stop the event system.";
420 421
		    $swapout_errors = 1;
		}
422 423 424 425 426 427 428

		#
		# Stop the location piper.
		#
		if (-x $piper) {
		    print "Stopping the location piper\n";
		    if (system("$piper -k $pid $eid")) {
429
			tberror "Failed to stop location piper.";
430 431 432
			$swapout_errors = 1;
		    }
		}
433 434
	    }
	}
435 436 437 438 439 440
	
	#
	# 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).
	#
441
	if ($elabinelab && $type >= CLEANUP) {
442 443
	    print "Tearing down elabinelab. This could take a while.\n";
	    if (system("elabinelab -k $pid $eid")) {
444
		tberror "Failed to teardown elabinelab!";
445 446 447 448
		$swapout_errors = 1;
	    }
	}

449
	#
Chad Barb's avatar
Chad Barb committed
450
	# Clean up any VLANs in experiment.
451
	#
452 453 454 455 456 457 458
	# 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")) {
459
		tberror "Failed to reset VLANs";
460 461 462 463 464
		$swapout_errors = 1;
	    } else {
		$cleanvlans = 0;
	    }
	    TBDebugTimeStamp("snmpit finished");
465
	}
466
    }
Chad Barb's avatar
Chad Barb committed
467

468 469 470
    if ($type >= CLEANUP) {
	#
	# We're not attempting a retry;
471
	#
472
	# Stop all of the vnodes.
473
	#
474
	if (! $TESTMODE) { 	
475 476 477
	    print "Tearing down virtual nodes.\n";
	    TBDebugTimeStamp("vnode_setup -k started");
	    if (system("vnode_setup -d -k $pid $eid")) {
478
		tberror "Failed to tear down vnodes.";
479 480 481
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup finished");
482 483
	}

484 485 486 487 488 489 490
	#
	# Nodes behind a firewall are treated special.
	# See undoFWNodes for details.
	#
	if ($firewalled && undoFWNodes($pid, $eid)) {
	    return 1;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
491

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
	#
	# 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);
	}
512 513
	if ($soaction{'command'} && doSwapoutAction($pid, $eid, %soaction)) {
	    return 1;
514 515
	}

516 517
	#
	# remove all nodes from the experiment.
Chad Barb's avatar
Chad Barb committed
518
	# (nfree will send them to RES_FREE_DIRTY)
519 520 521 522
	#
	print STDERR "Freeing nodes.\n";
	TBDebugTimeStamp("nfree started");
	if (system("nfree $pid $eid")) {
523
	    tberror "Could not free nodes.";
524 525 526
	    $swapout_errors = 1;
	}
	TBDebugTimeStamp("nfree finished");
527 528 529 530 531

	#
	# Since this is an actual swapout, 
	# reset our count of swap out nag emails sent.
	#
532
	DBQueryWarn("update experiments set swap_requests='',sim_reswap_count='0' ".
533
		    "where eid='$eid' and pid='$pid'");
534 535
    } else {
	#
536
	# $type == RETRY or $type == UPDATE.
537 538
	# 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
539
	# (nfree will send deallocated nodes to RES_FREE_DIRTY)
540
	#
541 542 543 544 545 546 547 548
	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 ".
549 550
			 "where rv.pid='$pid' and rv.eid='$eid'");

551
	while (my ($node,$allocstate,$isvirt) = $db_result->fetchrow_array) {
552
	    if ($allocstate ne TBDB_ALLOCSTATE_RES_READY()) {
553 554 555 556 557 558
		if ($isvirt) {
		    push(@failedvnodes, $node);
		}
		else {
		    push(@failedpnodes, $node);
		}
559 560 561
	    }
	}

562 563 564 565 566 567 568
	#
	# 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")) {
569
		tberror "Failed to tear down vnodes.";
570 571 572 573
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("vnode_setup -k finished");
	}
574

575 576 577 578
	#
	# Release all failed nodes.
	# 
	if (@failedpnodes > 0 || @failedvnodes > 0) {
579 580
	    print STDERR "Freeing failed nodes.\n";
	    
581
	    TBDebugTimeStamp("nfree started");
Chad Barb's avatar
Chad Barb committed
582 583 584 585 586
	    #
	    # 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.
	    #
587 588
	    if (system("nfree -x $pid $eid " .
		       join(" ", (@failedpnodes, @failedvnodes)))) {
589
		tberror "Could not free nodes.";
590 591 592 593 594 595
		$swapout_errors = 1;
	    }
	    TBDebugTimeStamp("nfree finished");
	}
    }

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    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");
620
		if (system("plabslice destroy $pid $eid")) {
621
		    tberror "Failed to destroy Plab dslice.";
622 623 624 625 626 627 628
		    $swapout_errors = 1;
		}
		TBDebugTimeStamp("plabslice destroy finished");
	    }
	}
    }

629 630 631 632 633 634 635 636
    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
637
	# not a failed swapin(cleanup), update, or retry.
638
	#
639
	if ($type == REAL) {
640 641 642
	    print "Resetting mountpoints.\n";
	    TBDebugTimeStamp("exports started");
	    if (system("exports_setup")) {
643
		tberror "Failed to reset mountpoints.";
644 645 646
	    }
	    TBDebugTimeStamp("exports finished");
	}
Chad Barb's avatar
Chad Barb committed
647

648 649 650 651
	#
	# Resetting named maps and email lists is fast and idempotent,
	# so whatever.
	#
652 653 654
	print "Resetting named maps.\n";
	TBDebugTimeStamp("named started");
	if (system("named_setup")) {
655
	    tbwarn "Failed to reset named map.";
656 657
	}
	TBDebugTimeStamp("named finished");
Chad Barb's avatar
Chad Barb committed
658

659 660
	print "Resetting email lists.\n";
	TBDebugTimeStamp("genelists started");
661
	if (system("genelists -t")) {
662
	    tbwarn "Failed to reset email lists.";
663 664 665 666
	}
	TBDebugTimeStamp("genelists finished");
    }

667
    #
668 669 670
    # Wipe the DB clean except during UPDATE or RETRY. In those
    #    cases, assign_wrapper will reset the DB after reading
    #    the info.
671
    #
672 673 674 675
    if ( $type >= CLEANUP ) {
	print STDERR "Resetting DB.\n";
	TBExptRemovePhysicalState( $pid, $eid );
    }
676 677 678 679 680

    return $swapout_errors;
}

##
Chad Barb's avatar
Chad Barb committed
681
#
682 683
# doSwapin - Swaps experiment in.
#
Chad Barb's avatar
Chad Barb committed
684 685 686 687 688
#            Returns:
#              0 - successful swapin
#              1 - failed swapin; cleanup required.
#              3 - failed swapin; cleanup required; can retry.
#              7 - failed swapin; assign failed; no cleanup.
689 690
##

691
sub doSwapin($) {
692 693 694
    my $type = shift; # REAL==4, RETRY==2, UPDATE==1, UPDATE_RECOVER=0.
    # Just the physnodes ...
    my @deleted_pnodes = ();
695

696 697 698 699
    #
    # assign_wrapper does all the virtual to physical mapping 
    # and updating the DB state.
    #
700
    
Chad Barb's avatar
Chad Barb committed
701
    if ($type > UPDATE_RECOVER) {
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        #
        # 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 ".
			 "     (o.os is NULL or o.os='Linux') and ".
			 "     e.pid='$pid' and e.eid='$eid'");

	    if ($db_result->numrows) {
		print "*** Endnodeshaping is disabled on Linux Images!\n";
		print "*** You must modify your experiment to swap it in.\n";
		return 1;
	    }
	}
	
Chad Barb's avatar
Chad Barb committed
728 729 730 731
	print "Mapping to physical reality ...\n";
	TBDebugTimeStamp("assign_wrapper started");

	#
732 733 734 735
	# 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
736 737
	#
	my $exitcode;
738 739 740
	my $wrapper = "assign_wrapper -u";
	$wrapper .= " -f"
	    if ($type == RETRY);
741
	
742
	if (system("$wrapper $pid $eid")) {
743 744
	    $exitcode = $? >> 8;

745
	    tberror "Failed ($exitcode) to map to reality.";
746

747 748
	    # Wrapper sets this bit when recovery is possible.
	    if ($exitcode & 64) {
749
		# We can recover. 
Chad Barb's avatar
Chad Barb committed
750
		return 7;
751 752
	    }
	    else {
753
		# No recovery, no retry.
Chad Barb's avatar
Chad Barb committed
754 755 756 757
		return 1;
	    }
	}
	TBDebugTimeStamp("assign_wrapper finished");
758

Chad Barb's avatar
Chad Barb committed
759 760
	print "Mapped to physical reality!\n";
    }
761

762
    # Check cancel flag before continuing. No retry, 
763
    TBGetCancelFlag($pid, $eid, \$canceled);
764 765 766
    return 1
	if ($canceled);

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    #
    # 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);
		}
	    }
802 803 804
	    # See below.
	    @deleted_pnodes = @physnodes;
	    
805 806 807
	    if (@virtnodes) {
		TBDebugTimeStamp("vnode_setup started");
		
808
		if (system("vnode_setup -k $pid $eid @virtnodes")) {
809 810 811 812 813 814 815 816 817 818 819
		    print "Failed to tear down unused virtnodes!\n";
		    return 1;
		}
		TBDebugTimeStamp("vnode_setup finished");
		
		if (system("nfree $pid $eid @virtnodes")) {
		    print "Failed to nfree unused virtnodes!\n";
		    return 1;
		}
	    }
	    if (@physnodes) {
820 821 822
		if ($elabinelab) {
		    print "Removing nodes from inner elab.\n";
		    if (system("elabinelab -r $pid $eid @physnodes")) {
823
			tberror "Failed to remove inner nodes!";
824 825 826 827 828
			return 1;
		    }
		}

		#
829 830
		# If the experiment is firewalled, cleanup the nodes
		# we are releasing.
831
		# 
832
		if ($firewalled && undoFWNodes($pid, $eid, @deleted_pnodes)) {
833 834 835
		    return 1;
		}
		
836 837 838 839 840 841 842 843
		if (system("nfree $pid $eid @physnodes")) {
		    print "Failed to nfree unused physnodes!\n";
		    return 1;
		}
	    }
	}
    }

844 845 846 847 848 849
    # Exit here if we are testing.
    if ($TESTMODE) {
	print "Testing run - Stopping here.\n";
	return 0;
    }

850 851 852 853 854 855 856 857 858 859 860
    #
    # 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?
	#
861
	tberror "Failed to set up tarballs.";
862 863 864 865
	return 1;
    }
    TBDebugTimeStamp("tarfiles_setup finished");

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
    #
    # 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");
894
		if (system("plabslice create $pid $eid")) {
895
		    tberror "Failed to create Plab dslice";
896 897 898 899 900 901 902
		    return 3;
		}
		TBDebugTimeStamp("plabslice alloc finished");
	    }
	}
    }

903
    # Check cancel flag before continuing. No retry, 
904
    TBGetCancelFlag($pid, $eid, \$canceled);
905 906 907
    return 1
	if ($canceled);

908 909 910 911 912 913 914 915 916
    #
    # 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")) {
917
	tberror "Failed to setup mountpoints.";
918 919 920
	return 1;
    }
    TBDebugTimeStamp("mountpoints finished");
Chad Barb's avatar
Chad Barb committed
921

922 923 924
    TBDebugTimeStamp("named started");
    print "Setting up named maps.\n";
    if (system("named_setup")) {
925
	tbwarn "Failed to add node names to named map.";
926 927
	#
	# This is a non-fatal error.
Chad Barb's avatar
Chad Barb committed
928
	#
929 930
    }
    TBDebugTimeStamp("named finished");
Chad Barb's avatar
Chad Barb committed
931

Timothy Stack's avatar
Timothy Stack committed
932 933 934 935 936 937 938 939
    if ($NFSTRACESUPPORT) {
	print "Cleaning NFS traces.\n";
	TBDebugTimeStamp("nfstrace gc started");
	if (system("nfstrace gc $pid $eid")) {
	    tberror "Failed to setup nfstrace.";
	    return 1;
	}
	TBDebugTimeStamp("nfstrace gc finished");
940 941
    }

942
    # Check cancel flag before continuing. No retry, 
943
    TBGetCancelFlag($pid, $eid, \$canceled);
944 945
    return 1
	if ($canceled);
Chad Barb's avatar
Chad Barb committed
946

947 948 949 950
    #
    # Setup any control-net firewall.
    # This must be done before reloading and rebooting nodes.
    #
951 952
    if ($firewalled && ($type == REAL || $type == UPDATE) &&
	doFW($pid, $eid, (($type == UPDATE) ? FWADDNODES : FWSETUP), undef)) {
953 954 955
	return 1;
    }

Chad Barb's avatar
Chad Barb committed
956 957
    #
    # If user specified -reboot to update,
958
    # and we are successfully performing the update,
959
    # then mark all nodes in experiment so os_setup will reboot them.
Chad Barb's avatar
Chad Barb committed
960
    #
961 962 963
    if (($type == UPDATE) &&
	($updateReboot || $updateReconfig)) {
	print STDERR "Marking nodes for reboot/reconfig.\n";
Chad Barb's avatar
Chad Barb committed
964
	$db_result =
965 966 967
	    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
968

969 970 971 972 973 974 975 976
	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()) {
977 978 979 980
		TBSetNodeAllocState($node,
				    ($updateReboot ?
				     TBDB_ALLOCSTATE_RES_INIT_DIRTY() :
				     TBDB_ALLOCSTATE_RES_RECONFIG()));
981
	    }
Chad Barb's avatar
Chad Barb committed
982 983 984
	}
    }

985 986 987 988 989 990 991 992 993 994 995 996 997
    #
    # 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");

998 999 1000 1001 1002
    #
    # 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";
1003
    TBDebugTimeStamp("launching os_setup");
1004 1005 1006
    if (!($os_setup_pid = fork())) { 
	exec("os_setup $pid $eid") or return 1;
    } elsif ($os_setup_pid == -1) {
1007
	tberror "Fork failed.";
1008 1009
	return 1;
    }
Chad Barb's avatar
Chad Barb committed
1010

1011
    #
1012 1013 1014 1015 1016
    # 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.)
1017 1018 1019 1020 1021
    #

    print "Setting up VLANs.\n";
    TBDebugTimeStamp("snmpit started");
    if (system("snmpit -t $pid $eid")) {
1022
	tberror "Failed to set up VLANs.";
1023 1024 1025
	return 1;
    }
    TBDebugTimeStamp("snmpit finished");
Chad Barb's avatar
Chad Barb committed
1026

1027 1028 1029 1030
    #
    # An error now means that the VLANS need to be cleaned up.
    #
    $cleanvlans = 1;
Chad Barb's avatar
Chad Barb committed
1031

1032 1033
    print "Setting up email lists.\n";
    TBDebugTimeStamp("genelists started");
1034
    if (system("genelists -t")) {
1035
	tbwarn "Failed to update email lists.";
1036 1037 1038 1039 1040
	#
	# This is a non-fatal error.
	# 
    }
    TBDebugTimeStamp("genelists finished");
Chad Barb's avatar
Chad Barb committed
1041

1042 1043 1044 1045 1046 1047 1048 1049
    #
    # 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")) {
1050
	    tbwarn "Failed to clear port counters.";
1051 1052 1053 1054 1055
	    #
	    # This is a non-fatal error.
	    # 
	}
	TBDebugTimeStamp("portstats finished");
1056
    }
Chad Barb's avatar
Chad Barb committed
1057

1058 1059 1060 1061 1062 1063 1064
    #
    # 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) {
1065
	    tberror "Failed to reset OS and reboot nodes.";
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
	    #
	    # 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) {
		print STDERR "Not retrying, ".
		    "firewall may be preventing setup.\n";
		return 1;
	    }

1080
	    #
1081 1082
	    # Use returncode from os_setup process to
	    # set global $retry flag, indicating to caller
1083 1084 1085
	    # that it may be beneficial to attempt
	    # a doSwapin() again.
	    #
1086
            if (($CHILD_ERROR >> 8) == 1) {
Chad Barb's avatar
Chad Barb committed
1087
		return 3;
1088 1089
	    } else {
		print STDERR "Not retrying due to error type.\n";
Chad Barb's avatar
Chad Barb committed
1090
		return 1;
1091
	    }
1092 1093 1094
	}
    } else {
	undef $os_setup_pid;
1095
	tberror "Error waiting for os_setup to finish.";
1096 1097
	return 1;
    }
Chad Barb's avatar
Chad Barb committed
1098

1099 1100 1101 1102
    #
    # Okay, start the event system now that we know all the nodes have
    # rebooted (os_setup is done). This only takes a moment (puts itself
    # in the background), so its not enough of a delay to worry about.
1103 1104
    # Don't do this during an update, since we didn't kill the 
    # event system previously, so starting it again will fail!
1105
    # 
1106
    if (! ($DISABLE_EVENTS || $elabinelab)) {
1107 1108 1109 1110 1111 1112 1113
	#
	# For the robot testbed, start the location piper *before* the event
	# system.
	#
	if (-x $piper && ($type != UPDATE && $type != UPDATE_RECOVER)) {
	    print "Starting the location piper.\n";
	    if (system("$piper $pid $eid")) {
1114
		tberror "Failed to start the location piper.";
1115 1116 1117 1118
		return 1;
	    }
	}
	
1119 1120
	if ( $update_Eventsys_restart || 
	    ($type != UPDATE && $type != UPDATE_RECOVER) ) {
1121 1122 1123
	    print "Starting the event system.\n";
	    TBDebugTimeStamp("eventsys_control started");
	    if (system("eventsys_control start $pid $eid")) {
1124
		tberror "Failed to start the event system.";
1125 1126 1127
		return 1;
	    }
	    TBDebugTimeStamp("eventsys_control finished");
1128 1129
	}
    }
Chad Barb's avatar
Chad Barb committed
1130

1131 1132 1133 1134 1135 1136 1137
    #
    # Do linktest if user requested it at swapin.
    #
    my $query_result =
	DBQueryFatal("select linktest_level,linktest_pid from experiments ".
		     "where pid='$pid' and eid='$eid'");
    my ($linktest_level,$linktest_pid) = $query_result->fetchrow_array();
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

    # Temporary. Only studly users get to control linktest level.
    # Mere users always get at least level three.
    $query_result =
	DBQueryFatal("select stud from users where uid='$dbuid'");
    my ($studly) = $query_result->fetchrow_array();

    if (! $studly) {
	$linktest_level = ($linktest_level <= 3 ? 3 : $linktest_level);
    }
1148 1149 1150 1151 1152 1153 1154 1155 1156
 
    if ($linktest_level && ($type == REAL || $type == UPDATE)) {
	if ($linktest_pid) {
	    print STDERR "*** Linktest is already running! $linktest_pid\n";
	}
	else {
	    #
	    # Run it. No worries about failures.
	    #
1157
	    my $optarg = "-l $linktest_level -t 600 -m";
1158 1159 1160 1161 1162 1163 1164 1165
    
	    print "Starting linktest ... this could take a while!'\n";
	    if (system("linktest_control $optarg $pid $eid") != 0) {
		print STDERR "*** Linktest run returned non-zero status!\n";
	    }
	}
    }

1166 1167 1168
    #
    # ElabinElab setup. This might not be the right place for this!
    #
1169 1170 1171
    if ($elabinelab && !$TESTMODE && ($type == REAL || $type == UPDATE)) {
	my $optarg = ($type == UPDATE ? "-u" : "");
	
1172 1173
	print "Setting up elabinelab. This could take a while!\n";
	TBDebugTimeStamp("elabinelab setup started");
1174
	if (system("elabinelab $optarg $pid $eid")) {
1175
	    tberror "Failed to setup elabinelab!";
1176 1177
	    return 1;
	}
1178
	TBDebugTimeStamp("ElabInElab setup finished");
1179 1180
    }

1181 1182 1183
    #
    # Tell the event scheduler to START.
    # 
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    if (! ($DISABLE_EVENTS || $elabinelab)) {
	if ( $update_Eventsys_restart || 
	    ($type != UPDATE && $type != UPDATE_RECOVER) ) {
	    TBDebugTimeStamp("Starting event time");
	    if (system("tevc -e $pid/$eid now __ns_sequence start")) {
		print STDERR "*** Failed to start event time.\n";
		return 1;
	    }
	}
    }

1195 1196
    return 0;
}
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208

#
# Setup and teardown experiment firewall.
#
# XXX note that right now, we just setup the switch infrastructure
# first, and then just let everything else go.  Firewalled nodes will
# not boot until the firewall is up since the VLAN is isolated til then.
# The firewall will boot ok since it still talks to the real control net.
#
# XXX for tearing down firewalls, we assume that nodes have been "cleansed"
# and it is safe to put ports back into the default control net VLAN.
#
1209 1210
sub doFW($$$$) {
    my ($pid, $eid, $action, $nodelist) = @_;
1211
    my ($fwnode, $fwvlanname, $fwvlan, $fwport, $fwvid);
1212
    my %nodenames;
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

    #
    # See if there is a firewall, fetching node/VLAN info if so.
    # If not, we are all done.
    #
    if (!TBExptFirewall($pid, $eid, \$fwnode, \$fwvid, \$fwvlan)) {
	return 0;
    }

    if ($action == FWSETUP) {
	$fwvid = TBGetUniqueIndex("cnet_vlanid");

	print "Setting up control net firewall.\n";
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    }
    else {
	if ($action == FWADDNODES) {
	    print "Adding nodes to control net firewall.\n";
	}
	elsif ($action == FWDELNODES) {
	    print "Removing nodes from control net firewall.\n";
	}
	else {
	    print "Tearing down control net firewall.\n";
	}
1237 1238 1239 1240 1241 1242 1243

	# Prior setup didn't succeed, nothing to do
	if (!defined($fwvid)) {
	    return 0;
	}
    }

1244 1245 1246 1247 1248 1249 1250
    # See below.
    if (defined($nodelist)) {
	foreach my $node (@$nodelist) {
	    $nodenames{$node} = $node;
	}
    }

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    # XXX vlanid in the DB is currently an int, we need a more unique name
    $fwvlanname = "fw$fwvid";

    #
    # Find all the experiment nodes and their control interface switch ports
    #
    # XXX this may be replaced by a call to SNMPIT that just specifies
    # the pid/eid.  In that case someone else will first have to poplulate
    # the vlans table with this same info. 
    #
    my $db_result =
1262 1263 1264 1265 1266 1267
	DBQueryWarn("SELECT r.node_id,w.card1 ".
		    "  FROM wires AS w, reserved AS r ".
		    "WHERE r.node_id=w.node_id1 AND r.pid='$pid' ".
		    "  AND r.eid='$eid' AND w.type='Control'");
    return 1
	if (!$db_result);
1268 1269 1270

    my $portlist = "";
    while (my ($node,$cif) = $db_result->fetchrow_array()) {
1271
	print "$node $cif\n";
1272 1273
	if ($node eq $fwnode) {
	    $fwport = "$node:$cif";
1274 1275 1276 1277 1278 1279 1280 1281
	}
	elsif (defined($nodelist)) {
 	    print "foo @$nodelist\n";
	    # Only nodes we are moving in/out of the experiment.
	    $portlist .= " $node:$cif"
		if (exists($nodenames{$node}));
	}
	else {
1282 1283 1284 1285
	    $portlist .= " $node:$cif";
	}
    }
    if (!defined($fwport)) {
1286
	tberror "Firewall node '$fwnode' not found in $pid/${eid}!";
1287 1288 1289
	return 0;
    }
    if ($portlist eq "") {
1290 1291 1292 1293 1294
	#
	# We catch this up in swapexp; admin users can specify just a firewall,
	# but mere users must have at least one firewalled node. Just print
	# the warning though. 
	# 
1295
	tberror "No firewalled nodes in $pid/${eid}!";
1296 1297 1298 1299 1300 1301
    }

    #
    # XXX hack commands til we nail down the API
    #
    my $fwsetupstr1 = "snmpit $cnetstack -m $fwvlanname $portlist";
1302 1303
    my $fwsetupstr2 = "snmpit $cnetstack -N $fwvlanname";
    my $fwsetupstr3 = "snmpit $cnetstack -T $fwport $cnetvlanname $fwvlanname";