swapexp.in 48.3 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3 4

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2012 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
6 7 8
# All rights reserved.
#

9 10
use English;
use Getopt::Std;
11
use POSIX qw(isatty setsid);
12
use RPC::XML;
13 14

#
Chad Barb's avatar
Chad Barb committed
15
# This gets invoked from the Web interface.
16
# Swap an experiment in, swap it out, restart or modify.
17
#
Chad Barb's avatar
Chad Barb committed
18

19 20
sub usage()
{
21
    print(STDERR
22
	  "Usage: swapexp [-q] [-b | -w] [-i | -a | -f] [-r] [-e] [-N]\n".
23 24 25 26
	  "               <-s in | out | restart | modify | pause>\n".
	  "               <pid> <eid> [<nsfile>]\n".
	  "switches and arguments:\n".
	  "-w       - wait for non-batchmode experiment swap/modify\n".
27
	  "-q       - be less chatty\n".
28 29 30
	  "-r       - reboot nodes when doing a modify experiment\n".
	  "-e       - restart event scheduler when doing a modify experiment\n".
	  "-s <op>  - Operation to perform; one of those listed above\n".
31
	  "-N       - Suppress most email to the user and testbed-ops\n".
32 33 34
	  "<pid>    - The project the experiment belongs to\n".
	  "<eid>    - The experiment name (id)\n".
	  "<nsfile> - Optional NS file to parse for experiment modify\n");
35 36
    exit(-1);
}
37
my  $optlist = "biafres:wqxgNXno";
38

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#
# Exit codes are important; they tell the web page what has happened so
# it can say something useful to the user. Fatal errors are mostly done
# with die(), but expected errors use this routine. At some point we will
# use the DB to communicate the actual error.
#
# $status < 0 - Fatal error. Something went wrong we did not expect.
# $status = 0 - Termination is proceeding in the background. Notified later.
# $status > 0 - Expected error. User not allowed for some reason. 
# 
sub ExitWithStatus($$)
{
    my ($status, $message) = @_;
    
    if ($status < 0) {
54
	tbdie($message);
55
    }
56
    elsif ($status > 0) {
57
	tbnotice($message);
58
    }
59 60 61
    else {
	tbinfo($message);
    }
62 63 64
    exit($status);
}

65 66 67 68 69
#
# Configure variables
#
my $TB     = "@prefix@";
my $TBOPS  = "@TBOPSEMAIL@";
70
my $TBROBOCOPS = "@TBROBOCOPSEMAIL@";
71
my $TBLOGS = "@TBLOGSEMAIL@";
72
my $TBINFO = "$TB/expinfo";
73
my $TBDOCBASE = "@TBDOCBASE@";
74
my $TBBASE = "@TBBASE@";
75
my $CONTROL  = "@USERNODE@";
76 77 78 79 80 81 82

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
83
use libtblog;
84
use libArchive;
85
use Template;
86
use Experiment;
87
use User;
88

89 90 91 92 93 94
# For the END block below.
my $cleaning = 0;
my $justexit = 1;
my $signaled = 0;

my $tbdir    = "$TB/bin";
95
my $tbdata   = "tbdata";
96
my $checkquota = "$TB/sbin/checkquota";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
97
my $vtopgen  = "$TB/bin/vtopgen";
98
my $batch    = 0;
99
my $idleswap = 0;
100 101
my $autoswap = 0;
my $force    = 0;
102
my $lockforce= 0;
Chad Barb's avatar
Chad Barb committed
103
my $reboot   = 0;
104
my $waitmode = 0;
105
my $quiet    = 0;
106
my $genimode = 0;
107 108
my $noswapout= 0;
my $noreconfig=0;
109
my $eventsys_restart   = 0;
110
my $errorstat= -1;
111 112
my $modifyHosed   = 0;
my $modifySwapped = 0;
113
my $robotexp = 0;
114
my $template_node = 0;
115
my $noemail      = 0;
116
my $xmlout       = 0;
Chad Barb's avatar
Chad Barb committed
117

118
my $inout;
119
my $logfile;
120
my $logname;
121
my @allnodes;
122
my @row;
123
my $action;
124
my $tag;
125
my $nextswapstate;
126
my $termswapstate;
Chad Barb's avatar
Chad Barb committed
127

Kevin Atkinson's avatar
Kevin Atkinson committed
128 129
my $modifyError; # needed when emailing error

130
# Protos
131
sub fatal($;$);
132 133 134
sub CheckFWinfo($);
sub GatherFWinfo();
		
135 136 137
#
# Untaint the path
# 
138
$ENV{'PATH'} = "/bin:/usr/bin:$TB/libexec/vis";
139 140 141 142 143 144 145
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

146 147 148 149 150 151 152
#
# Set umask for start/swap. We want other members in the project to be
# able to swap/end experiments, so the log and intermediate files need
# to be 664 since some are opened for append.
#
umask(0002);

153 154 155 156 157 158 159 160
#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
161 162 163
if (defined($options{"i"})) {
    $idleswap = 1;
}
164 165 166
if (defined($options{"w"})) {
    $waitmode = 1;
}
167 168 169 170 171 172
if (defined($options{"a"})) {
    $autoswap = 1;
}
if (defined($options{"f"})) {
    $force = 1;
}
173 174 175
if (defined($options{"o"})) {
    $lockforce = 1;
}
176
if (defined($options{"g"})) {
177 178 179 180 181 182
    $genimode  = 1;
    $noswapout = 1;
}
if (defined($options{"n"})) {
    $noswapout  = 1;
    $noreconfig = 1;
183
}
184 185 186
if (defined($options{"b"})) {
    $batch = 1;
}
Chad Barb's avatar
Chad Barb committed
187 188 189
if (defined($options{"r"})) {
    $reboot = 1;
}
190 191 192
if (defined($options{"e"})) {
    $eventsys_restart = 1;
}
193 194 195
if (defined($options{"q"})) {
    $quiet = 1;
}
196 197 198
if (defined($options{"x"})) {
    $template_mode = 1;
}
199 200 201
if (defined($options{"N"})) {
    $noemail = 1;
}
202 203 204 205
if (defined($options{"X"})) {
    $quiet = 1;
    $xmlout = 1;
}
206 207 208
if (defined($options{"s"})) {
    $inout = $options{"s"};

Chad Barb's avatar
Chad Barb committed
209 210 211
    if ($inout ne "out"     &&
	$inout ne "in"      &&
	$inout ne "restart" &&
212
	$inout ne "pause"   &&
213
	$inout ne "modify") {
214 215 216 217 218 219 220
	usage();
    }
}
else {
    usage();
}

221 222 223 224 225
usage()
    if (($waitmode && $batch) ||
	($inout ne "modify" && @ARGV != 2) ||
	(($waitmode || $batch) && ($idleswap || $autoswap || $force)));

226 227 228 229 230
if ($eventsys_restart && $inout ne "modify") {
    print STDOUT "Usage: swapexp: -e (eventsys_restart) can be used ".
                 "only with -s modify\n";
    usage();
}
231 232 233
my $pid   = $ARGV[0];
my $eid   = $ARGV[1];

234 235 236
#
# Untaint the arguments.
#
237
if ($pid =~ /^([-\w\.]+)$/) {
238 239 240
    $pid = $1;
}
else {
241
    tbdie("Tainted argument $pid!");
242
}
243
if ($eid =~ /^([-\w\.]+)$/) {
244 245 246
    $eid = $1;
}
else {
247
    tbdie("Tainted argument $eid!");
248
}
249
my $repfile = "tbreport.log";
250 251
my $tempnsfile;
my $modnsfile;
252
my $nsfile;
253

254
if ($inout eq "modify" && @ARGV > 2) {
255 256 257 258 259
    $tempnsfile = $ARGV[2];

    #
    # Untaint nsfile argument; Allow slash.
    #
260
    if ($tempnsfile =~ /^([-\w\.\/]+)$/) {
261
	$tempnsfile = $1;
262 263
    }
    else {
264
	tbdie("Tainted nsfile name: $tempnsfile");
265 266 267 268 269 270 271 272 273
    }
    #
    # Called from ops interactively. Make sure NS file in /proj or /users.
    #
    # Use realpath to resolve any symlinks.
    #
    my $translated = `realpath $tempnsfile`;
    if ($translated =~ /^([-\w\.\/]+)$/) {
	$tempnsfile = $1;
274
    }
275
    else {
276
	tbdie("Tainted nsfile returned by realpath: $translated");
277 278 279
    }

    #
280 281 282 283 284 285 286
    # The file must reside in an acceptible location. Since this script
    # runs as the caller, regular file permission checks ensure it is a
    # file the user is allowed to use.   So we don't have to be too tight
    # with the RE matching /tmp and /var/tmp files.  Note that
    # /tmp/$guid-$nsref.nsfile is also allowed since this script is
    # invoked directly from web interface which generates a name that
    # should not be guessable.
287 288 289
    #
    if (! ($tempnsfile =~ /^\/tmp\/[-\w]+-\d+\.nsfile/) &&
	! ($tempnsfile =~ /^\/var\/tmp\/php\w+/) &&
290 291
	! TBValidUserDir($tempnsfile, 0)) {
	tbdie("$tempnsfile does not resolve to an allowed directory!");
292 293 294
    }

    if (! -f $tempnsfile || -z $tempnsfile || ! -r $tempnsfile) {
295
	tbdie("$tempnsfile does not look like an NS file!");
296
    }
297 298
    $nsfile    = "$eid.ns";
    $modnsfile = "${eid}-modify.ns";
299
}
300

301 302 303 304 305 306 307 308
my $experiment = Experiment->Lookup($pid, $eid);
if (! $experiment) {
    die("*** $0:\n".
	"    No such experiment $pid/$eid in the Emulab Database.\n");
}

my $workdir = $experiment->WorkDir();
my $userdir = $experiment->UserDir();
309
my $infodir = $experiment->InfoDir();
310

311 312 313 314
#
# See if this is a template instance; error if the -x option not provided,
# since that means user is trying to self-terminate; not in the program.
#
315
if (my $instance = Template::Instance->LookupByExptidx($experiment->idx())) {
316
    if ($inout ne "in" && !$template_mode) {
317 318 319 320 321
	die("*** $0:\n".
	    "    $pid/$eid is a template instance; use another command\n");
    }
}

322
# Sanity check.
323
if (! -e $workdir) {
324
    die("*** $0:\n".
325 326 327 328 329 330 331
	"    $pid/$eid is missing a critical directory!\n" .
	"    $workdir\n");
}
if (! -e $userdir) {
    die("*** $0:\n".
	"    $pid/$eid is missing a critical directory!\n" .
	"    $userdir\n");
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
}
if (! -e $infodir) {
    if (! -e "$TB/expinfo/$pid") {
	die("*** $0:\n".
	    "    $TB/expinfo/$pid has not been created yet!\n".
	    "    Did you run 'fixexpinfo' like you were supposed to?\n");
    }
    #
    # This is not going to happen unless a devel tree has been
    # mixed with the main tree (or another devel tree). Try to
    # recover, bail of not possible.
    #
    if (system("/bin/mkdir -m 777 -p $infodir")) {
	die("*** $0:\n".
	    "    $infodir was missing and cannot be created!\n");
    }
}

350 351 352 353 354
# XXX Hack for geni mode.
if ($genimode) {
    $experiment->SetState(EXPTSTATE_ACTIVE);
}

355
#
356
# Verify user and get his DB uid and other info for later.
357
#
358 359 360
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
361
}
362 363 364 365 366
my $user_dbid  = $this_user->dbid();
my $user_uid   = $this_user->uid();
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
my $isadmin    = TBAdmin();
367

368 369 370 371 372 373 374 375 376 377 378
#
# Get email address of the swapper/creator, which may be different than
# the person who is actually terminating the experiment, since its polite
# to let the original creator know whats going on. 
#
my $swapper = $experiment->GetSwapper();
$swapper = $experiment->GetCreator()
    if (!defined($swapper));
my $expt_head_name  = $swapper->name();
my $expt_head_email = $swapper->email();

379 380 381 382 383
#
# Set error reporting info
#
tblog_set_info($pid,$eid,$UID);

384
#
385
# Verify that this person can muck with the experiment.
386 387
# Note that any script down the line has to do an admin check also. 
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
388
if ($UID && !$isadmin &&
389
    ! $experiment->AccessCheck($this_user, TB_EXPT_DESTROY)) {
390
    tbdie("You do not have permission to swap or modify this experiment!");
391 392
}

393 394 395 396
# Must do this before lock tables!
# idleswap is in minutes, threshold is in hours
$idleswap_time = 60 * TBGetSiteVar("idle/threshold");

397 398 399 400 401 402 403 404 405
#
# In wait mode, block interrupt until we spin off the background process.
#
if ($waitmode) {
    $SIG{TERM} = 'IGNORE';
    $SIG{QUIT} = 'IGNORE';
    $SIG{INT}  = 'IGNORE';
}

406 407 408
#
# Check for overquota; we deal with it below, cause of the batch system.
#
409
my $overquota = system("$checkquota $user_uid");
410 411

if ($overquota) {
412 413
    tberror({cause => 'user', severity => SEV_WARNING,
	     error => ['over_disk_quota', $CONTROL]},
414 415
	    "You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
416 417
}

418 419 420 421
#
# Temp fix; Disallow swapmod to firewalled experiments. This will come
# out later.
#
422
my $firewalled = $experiment->IsFirewalled();
423

424 425 426 427 428 429 430 431 432 433
#
# see if we've got a robot exp (this isn't the only check; if this is a
# swapmod, we've got to check tbprerun as well...
#
$robotexp = 
    TBExptContainsNodeCT($pid,$eid,'robot') || 
    TBExptContainsNodeCT($pid,$eid,'mote') || 
    TBExptContainsNodeCT($pid,$eid,'motehost') || 
    TBExptContainsNodeCT($pid,$eid,'powermon');

434 435 436
# See below.
my $sharingvlans = $experiment->SharingVlans();

437 438 439 440 441
#
# We have to protect against trying to end an experiment that is currently
# in the process of being terminated. We use a "wrapper" state (actually
# a timestamp so we can say when termination was requested) since
# terminating consists of a couple of different experiment states down inside
Chad Barb's avatar
Chad Barb committed
442
# the tb scripts.
443
#
444
$experiment->LockTables() == 0
445 446 447 448 449 450 451
    or die("*** $0:\n".
	   "    Could not lock experiment tables for $pid/$eid!\n");

my $estate          = $experiment->state();
my $batchstate      = $experiment->batchstate();
my $expt_path       = $experiment->path();
my $isbatchexpt     = $experiment->batchmode();
452
my $canceled        = $experiment->canceled();
453 454 455 456 457 458 459 460 461 462 463 464 465 466
my $expt_locked     = $experiment->locked();
my $elabinelab      = $experiment->elabinelab();
my $lockdown        = $experiment->lockdown();
my $swappablebit    = $experiment->swappable();
my $idleswapbit     = $experiment->idleswap();
my $autoswapbit     = $experiment->autoswap();
my $swappablestr    = ( $swappablebit ? "Yes" : "No" );
my $idleswapstr     = ( $idleswapbit ? "Yes" : "No" );
my $autoswapstr     = ( $autoswapbit ? "Yes" : "No" );
my $noswap          = $experiment->noswap_reason();
my $noidleswap      = $experiment->noidleswap_reason();
my $idleswaptime    = $experiment->idleswap_timeout() / 60.0;
my $autoswaptime    = $experiment->autoswap_timeout() / 60.0;
my $rendering       = $experiment->prerender_pid();
467

468 469
if ($inout ne "out") {
    # I'm going to update this below, so fix the value before I use it.
470
    $idleswap_time = min($idleswaptime * 60, $idleswap_time);
471 472 473
    $idleswaptime = $idleswap_time / 60.0;
}

474 475
my $swapsettings = 
  "Idle-Swap:   $idleswapstr".
476
  ($idleswapbit ? ", at $idleswaptime hours\n" : " (Reason: $noidleswap)\n").
477 478
  "Auto-Swap:   $autoswapstr".
  ($autoswapbit ? ", at $autoswaptime hours\n" : "\n");
479

480
if (! chdir($workdir)) {
481
    tbdie("Could not chdir to $workdir: $!");
482 483
}

484
#
485 486 487
# This script is called from the batch daemon.
# 
if ($batch) {
488
    #
489 490 491
    # Sanity Check. If called from the daemon, must already be locked,
    # must be a batch experiment, and must be in proper state for the
    # operation requested. 
492
    #
493
    tbdie("Experiment $pid/$eid is supposed to be a batch experiment!")
494 495
	if (!$isbatchexpt);
    
496
    tbdie("Batch experiment $pid/$eid should be locked!")
497 498
	if (!defined($expt_locked) ||
	    $batchstate ne BATCHSTATE_LOCKED());
499 500
    
    tbdie("Batch experiment $pid/$eid is locked down; cannot be swapped!")
501 502
	if ($lockdown);

503
    if ($inout eq "in") {
504 505
	tbdie("Batch experiment $pid/$eid is not in the proper state!\n".
	      "Currently $estate, but should be QUEUED.")
506 507
	    if ($estate ne EXPTSTATE_QUEUED);
	
508 509 510
	tbdie({cause => 'canceled', severity => SEV_IMMEDIATE,
	       error => ['cancel_flag']},
	      "Batch experiment $pid/$eid has been canceled! Aborting.")
511
	    if ($canceled);
512 513

	# Do not allow it to swap in. What about swapout? 
514 515 516
	tbdie({type => 'primary', severity => SEV_ERROR,
	       error => ['over_disk_quota', $CONTROL]},
	      "Batch experiment cannot swap in when over quota! Aborting.")
517
	    if ($overquota);
518 519
    }
    elsif ($inout eq "out") {
520 521
	tbdie("Batch experiment $pid/$eid is not in the proper state!\n".
	      "Currently $estate, but should be ACTIVE.")
522
	    if ($estate ne EXPTSTATE_ACTIVE);
523 524
    }
    else {
525
	tbdie("Improper request from batch daemon for $pid/$eid!\n");
526 527 528 529
    }
}
else {
    if ($isbatchexpt) {
530 531 532 533
	#
	# User is requesting that a batch either be injected or paused.
	# Sanity check the state, but otherwise let the batch daemon
	# handle it.
534 535
	#
	ExitWithStatus(1, "Batch experiment $pid/$eid is still canceling!")
536
	    if ($canceled);
537

538 539 540
	ExitWithStatus(1, "Batch experiment $pid/$eid is locked down!")
	    if ($lockdown);

541
	if ($inout eq "in") {
542
	    ExitWithStatus(1,
543 544 545
			   "Batch experiment $pid/$eid must be SWAPPED to\n".
			   "QUEUE. Currently $estate.")
		if ($estate ne EXPTSTATE_SWAPPED);
546

547 548 549 550 551 552 553 554
	    #
	    # For the moment, only the creator of the batch can queue it. This
	    # avoids all kinds of problems inside the batch daemon, with it
	    # not knowing who to swap the experiment in as. This is a temporary
	    # solution, at least until I have time to decide what is correct.
	    #
	    ExitWithStatus(1,
			   "Only the creator of a batch experiment can queue it!")
555
		if ($experiment->creator() ne $user_uid);
556

557 558 559 560 561 562
	    if ($overquota) {
		tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		ExitWithStatus(1,
			       "Batch experiment $pid/$eid cannot swap in when ".
			       "over quota!\n")
	    }
563
	    
564
	    $experiment->SetState(EXPTSTATE_QUEUED);
565 566
	}
	elsif ($inout eq "out") {
567
	    ExitWithStatus(1,
568 569 570 571
			   "Batch experiment $pid/$eid must be ACTIVE or\n".
			   "ACTIVATING to swap out. Currently $estate.")
		if ($estate ne EXPTSTATE_ACTIVE &&
		    $estate ne EXPTSTATE_ACTIVATING);
572 573 574 575 576

	    #
	    # Since the batch daemon has control, all we can do is set
	    # the cancel bit.
	    # 
577
	    $experiment->SetCancelFlag(EXPTCANCEL_SWAP);
578 579
	}
	elsif ($inout eq "pause") {
580
	    ExitWithStatus(1,
581 582 583
			   "Batch experiment $pid/$eid must be QUEUED to\n".
			   "DEQUEUE. Currently $estate.")
		if ($estate ne EXPTSTATE_QUEUED);
584 585

	    #
586
	    # XXX. The batch daemon might already have the experiment, but
587 588
	    # not have shipped it off to startexp. Use a cancel flag since
	    # that is the only consistent mechanism to tell the batch daemon
589 590 591 592
	    # what it should do. Otherwise, we can just change its state
	    # to yank it from the queue.
	    #
	    if ($batchstate ne BATCHSTATE_UNLOCKED()) {
593
		$experiment->SetCancelFlag(EXPTCANCEL_DEQUEUE);
594 595
	    }
	    else {
596
		$experiment->SetState(EXPTSTATE_SWAPPED);
597
	    }
598
	}
599
	elsif ($inout eq "modify") {
600
	    ExitWithStatus(1,
601 602 603 604
			   "Batch experiment $pid/$eid must be SWAPPED or\n".
			   "ACTIVE to modify. Currently $estate.")
		if (($estate ne EXPTSTATE_SWAPPED &&
		     $estate ne EXPTSTATE_ACTIVATING) ||
605
		    $batchstate ne BATCHSTATE_UNLOCKED());
606

607 608 609
	    ExitWithStatus(1,
			"Cannot modify an active firewalled experiment (yet).")
		if ($firewalled && $estate ne EXPTSTATE_SWAPPED && !$isadmin);
610

611 612
	    ExitWithStatus(1,
			"Cannot modify an active ElabInElab experiment (yet).")
613
		if ($elabinelab && $estate ne EXPTSTATE_SWAPPED);
614

615 616 617 618 619 620
	    if ($overquota) {
		tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		ExitWithStatus(1,
			       "Cannot modify batch experiment $pid/$eid when ".
			       "over quota!\n")
	    }
621
	    
622
	    #
623
	    # Otherwise, proceed with the modify. The experiment will be
624 625
	    # locked below, and so it cannot be injected or otherwise messed
	    # with since its state is going to be changed before we unlock
626 627 628 629
	    # the experiments table. The batch daemon will leave it alone
	    # until the modify is done. If the modify fails and cannot recover
	    # it is going to get swapped out; that is okay since the batch
	    # daemon does not keep state internally. 
630
	    #
631 632
	    goto doit;
	}
633
	else {
634
	    tbdie("Operation $inout not allowed on a batch experiment!");
635
	}
636 637
	ExitWithStatus(0, 
		       "Batch experiment $pid/$eid state has been changed.\n");
638
      doit:
639
    }
640 641 642 643 644 645 646 647 648 649
    else {
	#
	# If the cancel flag is set, then user must wait for that to
	# clear before we can do anything else.
	#
	ExitWithStatus(1,
		       "Experiment $pid/$eid has its cancel flag set!.\n".
		       "You must wait for that to clear before you can swap\n".
		       "or modify the experiment.\n")
	    if ($canceled);
650

651 652
 	ExitWithStatus(1,
		       "Experiment $pid/$eid is locked down; cannot swap!\n")
653
	    if ($lockdown && !$lockforce);
654

655 656
	ExitWithStatus(1,
		       "Experiment is sharing vlans; cannot swap or modify!\n")
657
	    if (($inout eq "out" || $inout eq "modify") && $sharingvlans);
658

659 660 661 662 663 664 665 666 667 668
	#
	# Check the state for the various operations.
	#
	if (!$force) {
	  SWITCH: for ($inout) {
	      /^in$/i && do {
		  if ($estate ne EXPTSTATE_SWAPPED()) {
		      ExitWithStatus(1,
				     "Experiment $pid/$eid is not swapped out!");
		  }
669 670 671 672 673 674
		  if ($overquota) {
		      tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		      ExitWithStatus(1,
				     "Experiment $pid/$eid cannot swap in when ".
				     "over quota!\n")
		  }
675
		  
676 677 678 679
		  last SWITCH;
	      };
	      /^out$/i && do {
		  if ($estate ne EXPTSTATE_ACTIVE() &&
Leigh B. Stoller's avatar
Leigh B. Stoller committed
680
 		      $estate ne EXPTSTATE_PANICED() &&
681 682 683 684 685 686
		      $estate ne EXPTSTATE_ACTIVATING()) {
		      ExitWithStatus(1,
				     "Experiment $pid/$eid is not swapped in ".
				     "or activating!\n");
		  }
		  
Leigh B. Stoller's avatar
Leigh B. Stoller committed
687 688 689 690 691 692 693 694 695 696 697 698
 		  #
 		  # Must be an admin person to swap out an experiment that
 		  # has had its panic button pressed.
 		  #
 		  if ($estate eq EXPTSTATE_PANICED() && !$isadmin) {
 		      ExitWithStatus(1,
 				     "Experiment $pid/$eid had its panic ".
 				     "button pressed!\n".
 				     "Only a testbed administrator can swap ".
 				     "this experiment out.");
 		  }

699 700 701 702 703
		  if ($estate eq EXPTSTATE_ACTIVATING()) {
		      #
		      # All we can do is set the cancel flag and hope that
		      # it gets noticed. We do not wait. 
		      # 
704
		      $experiment->SetCancelFlag(EXPTCANCEL_SWAP);
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
		      
		      ExitWithStatus(0,
				     "Experiment $pid/$eid swapin has been  ".
				     "marked for cancelation.\n".
				     "You will receive email when the original ".
				     "swap request has finished.");
		  }
		  last SWITCH;
	      };
	      /^restart$/i && do {
		  if ($estate ne EXPTSTATE_ACTIVE()) {
		      ExitWithStatus(1,
				     "Experiment $pid/$eid is not swapped in!");
		  }
		  last SWITCH;
	      };
	      /^modify$/i && do {
		  if ($estate ne EXPTSTATE_ACTIVE() &&
		      $estate ne EXPTSTATE_SWAPPED()) {
		      ExitWithStatus(1,
				     "Experiment $pid/$eid must be ACTIVE or\n".
				     "SWAPPED to modify!\n");
		  }
728
		  ExitWithStatus(1,
729 730 731 732
			"Cannot modify an active firewalled experiment (yet).")
		      if ($firewalled &&
			  $estate ne EXPTSTATE_SWAPPED && !$isadmin);

733
		  ExitWithStatus(1,
734 735 736
			"Cannot modify an active ElabInElab experiment (yet).")
		      if ($elabinelab &&
			  $estate ne EXPTSTATE_SWAPPED && !$isadmin);
737

738 739 740 741 742 743
		  if ($overquota) {
		      tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		      ExitWithStatus(1,
				     "Experiment $pid/$eid cannot be modified ".
				     "when over quota!\n")
		  }
744
		  
745 746
		  last SWITCH;
	      };
747
	      tbdie("Missing state check for action: $action");
748
	  }
749 750
	}
    }
751 752
}

753 754 755 756 757 758 759
#
# Determine the temporary and next state for experiment. If the experiment
# is a batch experiment, then the next state is actually handled by the
# batch daemon, but we still have to deal with the temporary state. 
#
SWITCH: for ($inout) {
    /^in$/i && do {
760
	$nextswapstate = EXPTSTATE_ACTIVATING();
761 762 763
	last SWITCH;
    };
    /^out$/i && do {
764
	$nextswapstate = EXPTSTATE_SWAPPING();
765 766 767
	last SWITCH;
    };
    /^restart$/i && do {
768
	$nextswapstate = EXPTSTATE_RESTARTING();
769 770 771
	last SWITCH;
    };
    /^modify$/i && do {
772 773
	$nextswapstate = (($estate eq EXPTSTATE_SWAPPED()) ?
			  EXPTSTATE_MODIFY_PARSE() : EXPTSTATE_MODIFY_REPARSE());
774 775
	last SWITCH;
    };
776
    tbdie("Missing state check for action: $action");
777
}
778 779
 
# Update idleswap_timeout to whatever the current value is.
780
if ($inout ne "out") {
781 782
    $experiment->UpdateIdleSwapTime($idleswap_time) == 0
	or tbdie("Could not update idleswap timeout for $pid/$eid");
783
}
784

785 786 787 788 789
#
# On a failure, we go back to this swapstate. Might be modified below.
# 
$termswapstate = $estate;

790 791 792
# Lock the record, set the nextstate, and unlock the table. Unlock
# tables at same time.
$experiment->Lock($nextswapstate, 1) == 0
793 794 795
    or tbdie({type => 'secondary', severity => SEV_SECONDARY,
	      error => ['set_experiment_state_failed', $nextswapstate]},
	     "Failed to set experiment state to $nextswapstate");
796 797 798 799 800 801 802

#
# At this point, we need to force a cleanup no matter how we exit.
# See the END block below.
#
$justexit = 0;

803 804 805 806 807 808
# Need the previous swapper for rollback below. Safe now that tables unlocked.
my $last_swapper = User->Lookup($experiment->swapper_idx());
if (! defined($last_swapper)) {
    tbdie("Error looking up object for last swapper!");
}

809 810
#
# XXX - At this point a failure is going to leave things in an
811 812 813 814
# inconsistent state. Be sure to call fatal() only since we are
# going into the background, and we have to send email since no
# one is going to see printed error messages (output goes into the
# log file, which will be sent along in the email). 
815 816
#

817 818
if ($inout eq "in") {
    $action = "swapped in";
819
    $tag    = "swapin";
820 821 822
}
if ($inout eq "out") {
    $action = "swapped out";
823
    $tag    = "swapout";
824 825 826 827
}
if ($inout eq "restart") {
    $action = "restarted";
}
828 829
if ($inout eq "modify") {
    $action = "modified";
830
    $tag    = "swapmod";
831
}
832

833 834 835
#
# Before going to background, we have to copy out the NS file!
#
836
if ($inout eq "modify" && defined($modnsfile)) {
837 838
    unlink($modnsfile);
    if (system("/bin/cp", "$tempnsfile", "$modnsfile")) {
839
	fatal("Could not copy $tempnsfile to $modnsfile");
840 841 842 843
    }
    chmod(0664, "$modnsfile");
}

844 845 846
#
# If not in batch mode, go into the background. Parent exits.
#
847
if (! $batch && ! $template_mode && !$genimode) {
848 849 850 851
    # Cleanup
    $experiment->CleanLogFiles() == 0
	or fatal("Could not clean up logfiles!");

852 853
    $logfile = $experiment->CreateLogFile("swapexp");
    if (!defined($logfile)) {
854 855
	fatal("Could not create logfile!");
    }
856 857 858 859 860
    $logname = $logfile->filename();
    # We want it to spew to the web.
    $experiment->SetLogFile($logfile);
    # Mark it open since we are going to start using it right away.
    $logfile->Open();
Chad Barb's avatar
Chad Barb committed
861

862 863
    if (my $childpid = TBBackGround($logname)) {
	#
864 865
	# Parent exits normally, unless in waitmode. We have to set
	# justexit to make sure the END block below does not run.
866
	#
867 868
	$justexit = 1;

869
	if (!$waitmode) {
870 871 872
	    print("Experiment $pid/$eid is now being $action.\n".
		  "You will be notified via email when the this is done.\n")
		if (! $quiet);
873 874
	    exit(0);
	}
875 876 877 878 879 880 881 882
	print("Waiting for experiment $eid to finish its swap${action}\n")
	    if (! $quiet);
	    
	if (isatty(STDIN) && !$quiet) {
	    print("You may type ^C at anytime; you will be notified via email.".
		  "\n".
		  "You will not actually interrupt the experiment itself.\n");
	}
883 884 885 886 887 888 889 890 891 892 893 894
	
	# Give child a chance to run.
	select(undef, undef, undef, 0.25);
	
	#
	# Reset signal handlers. User can now kill this process, without
	# stopping the child.
	#
	$SIG{TERM} = 'DEFAULT';
	$SIG{INT}  = 'DEFAULT';
	$SIG{QUIT} = 'DEFAULT';

895
	#
896
	# Wait until child exits or until user gets bored and types ^C.
897
	#
898 899
	waitpid($childpid, 0);
	
900 901
	print("Done. Exited with status: $?\n")
	    if (! $quiet);
902 903 904

	my $exit_code = $? >> 8;

905
	if ($exit_code != 0) {
906
	    my $d = tblog_lookup_error();
907 908 909 910 911 912 913 914 915 916 917 918 919
	    my $output = tblog_format_error($d);
	    if ($xmlout) {
		use libtblog '*SOUT'; # to avoid an unnecessary, and large,
                                      # log entry
		if (open(IN, "$logname")) {
		    $d->{log} = '';
		    while (<IN>) {
			$d->{log} .= $_;
		    }
		    close IN;
		}
		$d->{output} = $output;
	        print SOUT RPC::XML::response->new($d)->as_string(), "\n";
920
	    } elsif (!$quiet) {
921 922
		print $output;
	    }
923 924 925
	}
	exit $exit_code;

926
    }
927
    TBdbfork();
928 929
}

930 931 932 933 934 935 936 937
#
# When in waitmode, must put ourselves in another process group so that
# an interrupt to the parent will not have any effect on the backend.
#
if ($waitmode) {
    POSIX::setsid();
}

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
#
# We need to catch TERM cause sometimes shit happens and we have to kill
# an experiment swap that is hung or otherwise scrogged. Rather then 
# trying to kill off the children one by one, lets arrange to catch it
# here and send a killpg to the children. This is not to be done lightly,
# cause it can leave things worse then they were before!
#
sub handler ($) {
    my ($signame) = @_;
    
    $SIG{TERM} = 'IGNORE';
    my $pgrp = getpgrp(0);
    kill('TERM', -$pgrp);
    sleep(1);
    $signaled = 1;
    fatal("Caught SIG${signame}! Killing experiment setup ...");
}
$SIG{TERM} = \&handler;
$SIG{QUIT} = 'DEFAULT';

958 959 960 961
#
# Gather stats; start clock ticking
#
if ($inout eq "in") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
962
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPIN, $estate) == 0 or
963
	fatal("Preswap failed!");
964 965
}
elsif ($inout eq "out") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
966
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPOUT, $estate) == 0 or
967
	fatal("Preswap failed!");
968 969
}
elsif ($inout eq "modify") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
970
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPMODIFY, $estate) == 0 or
971
	fatal("Preswap failed!");
972 973
}

974 975 976
#
# Remove old report file since its contents are going to be invalid.
#
977
if ($inout ne "restart" && -e $repfile) {
978 979 980
    unlink("$repfile");
}

981 982 983 984
#
# Sanity check states in case someone changes something.
#
if ($inout eq "out") {
985
    my $optarg = (($force || $idleswap) ? "-force" : "");
986

987
    if ($experiment->Swap($Experiment::EXPT_SWAPOUT, $optarg) != 0) {
988
	$errorstat = $? >> 8;
989 990 991
	fatal({type => 'secondary', severity => SEV_SECONDARY,
	       error => ['tbswap_out_failed']},
	      "tbswap out failed!");
992
    }
993 994 995 996

    #
    # Add the files that have been detected by tracing to the archive.
    #
997 998 999 1000 1001 1002 1003
    if (!$template_mode) {
	if (libArchive::TBExperimentArchiveAddTracedFiles($pid, $eid) < 0) {
	    fatal({type => 'secondary', severity => SEV_SECONDARY,
		   error => ['archive_op_failed', 'add_traced_files',
			     undef, undef]},
		  "Failed to add traced files to the experiment archive!");
	}
1004

1005 1006 1007 1008 1009 1010 1011 1012 1013
	#
	# Add the experiment directory.
	#
	if (libArchive::TBExperimentArchiveAddUserFiles($pid, $eid) < 0) {
	    fatal({type => 'secondary', severity => SEV_SECONDARY,
		   error => ['archive_op_failed', 'add_user_files',
			     undef, undef]},
		  "Failed to add user files to the experiment archive!");
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1014 1015
    }

1016
    $experiment->SetState(EXPTSTATE_SWAPPED) == 0
1017 1018 1019
	or fatal({type => 'secondary', severity => SEV_SECONDARY,
		  error => ['set_experiment_state_failed', EXPTSTATE_SWAPPED()]},
	         "Failed to set experiment state to " . EXPTSTATE_SWAPPED());
1020
    
1021
    $experiment->SetPanicBit(0) == 0
1022
	or fatal("Failed to clear the panic bit!");
1023
}
1024
elsif ($inout eq "in") {
1025 1026
    # Set the swapper now so that nodes use the proper uid. If the swapin
    # fails, we leave the swapper as is, since its harmless and informative.
1027
    $experiment->SetSwapper($this_user);
1028

1029
    if ($experiment->Swap($Experiment::EXPT_SWAPIN) != 0) {
1030
	$errorstat = $? >> 8;
1031 1032 1033
	fatal({type => 'secondary', severity => SEV_SECONDARY,
	       error => ['tbswap_in_failed']},
	      "tbswap in failed!");
1034
    }
1035 1036
    
    $experiment->SetState(EXPTSTATE_ACTIVE) == 0
1037 1038 1039
	or fatal({type => 'secondary', severity => SEV_SECONDARY,
		  error => ['set_experiment_state_failed', EXPTSTATE_ACTIVE()]},
	         "Failed to set experiment state to " . EXPTSTATE_ACTIVE());
1040 1041
    
    $experiment->Report($repfile, "-b");
Chad Barb's avatar
Chad Barb committed
1042
}
1043
elsif ($inout eq "modify") {
1044 1045 1046
    #
    # Prepare the Archive for the swapmod, in case we have to "roll back".
    #
1047 1048 1049 1050 1051
    if (!$template_mode) {
	print "Doing a preswapmod on the experiment archive ...\n";
	if (libArchive::TBExperimentArchivePreSwapMod($pid, $eid) < 0) {
	    fatal("Failed to do a preswapmod on the experiment archive!");
	}
1052 1053
    }

1054 1055 1056 1057 1058
    # Gather up some firewall state for later comparison.
    if (GatherFWinfo() < 0) {
	fatal("Could not gather firewall info; cannot safely continue!");
    }

Chad Barb's avatar
Chad Barb committed
1059
    print "Backing up old experiment state ... " . TBTimeStamp() . "\n";
1060 1061
    $experiment->BackupVirtualState() == 0
	or fatal("Could not backup experiment state; cannot safely continue!");
Chad Barb's avatar
Chad Barb committed
1062 1063

    #
1064
    # Rerun tbprerun if modifying, but only if new NS file provided.
1065 1066
    # Yep, we allow reswap without changing the NS file. For Shashi and SIM.
    # Note that tbprerun kills the renderer if its running.
Chad Barb's avatar
Chad Barb committed
1067
    #
1068
    if (defined($modnsfile)) {
1069
	if ($experiment->PreRun($modnsfile) != 0) {
1070
	    print STDOUT "Modify Error: tbprerun failed.\n";
1071
	  FWHOSED:
1072 1073
	    print STDOUT "Recovering experiment state...\n";

1074 1075
	    if ($experiment->RemoveVirtualState() ||
		$experiment->RestoreVirtualState()) {
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
		$modifyHosed = 1;
		fatal("Experiment state could not be restored!");
		# Never returns;
	    }
	    #
	    # If the renderer was running when we started the swapmod, then we
	    # want to restart it. If it was stopped, then the renderer info
	    # was captured with the rest of the virtual state (restored above).
	    #
	    system("prerender -t $pid $eid")
		if ($rendering);

1088
	    $modifyError = "Update aborted; old virtual state restored.";
1089 1090 1091
	    fatal({type => 'secondary', severity => SEV_SECONDARY,
		   error => ['update_aborted', 'virtual_state_restored']},
		  $modifyError);
1092
	    # Never returns;