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

#
4
# Copyright (c) 2000-2015 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
24 25
#

26 27
use English;
use Getopt::Std;
28
use POSIX qw(isatty setsid);
29
use RPC::XML;
30
use Cwd qw(realpath);
31 32

#
Chad Barb's avatar
Chad Barb committed
33
# This gets invoked from the Web interface.
34
# Swap an experiment in, swap it out, restart or modify.
35
#
Chad Barb's avatar
Chad Barb committed
36

37 38
sub usage()
{
39
    print(STDERR
40
	  "Usage: swapexp [-q] [-b | -w] [-i | -a | -f] [-r] [-e] [-N]\n".
41 42 43 44
	  "               <-s in | out | restart | modify | pause>\n".
	  "               <pid> <eid> [<nsfile>]\n".
	  "switches and arguments:\n".
	  "-w       - wait for non-batchmode experiment swap/modify\n".
45
	  "-q       - be less chatty\n".
46 47 48
	  "-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".
49
	  "-N       - Suppress most email to the user and testbed-ops\n".
50 51 52
	  "<pid>    - The project the experiment belongs to\n".
	  "<eid>    - The experiment name (id)\n".
	  "<nsfile> - Optional NS file to parse for experiment modify\n");
53 54
    exit(-1);
}
55
my  $optlist = "biafres:wqxgNXno";
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#
# 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) {
72
	tbdie($message);
73
    }
74
    elsif ($status > 0) {
75
	tbnotice($message);
76
    }
77 78 79
    else {
	tbinfo($message);
    }
80 81 82
    exit($status);
}

83 84 85 86 87
#
# Configure variables
#
my $TB     = "@prefix@";
my $TBOPS  = "@TBOPSEMAIL@";
88
my $TBROBOCOPS = "@TBROBOCOPSEMAIL@";
89
my $TBLOGS = "@TBLOGSEMAIL@";
90
my $TBINFO = "$TB/expinfo";
91
my $TBDOCBASE = "@TBDOCBASE@";
92
my $TBBASE = "@TBBASE@";
93
my $CONTROL  = "@USERNODE@";
94
my $ISFS     = ("@BOSSNODE_IP@" eq "@FSNODE_IP@") ? 1 : 0;
95 96 97 98 99 100 101

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
102
use libtblog;
103
use libArchive;
104
use Template;
105
use Experiment;
106
use User;
107

108 109 110 111 112 113
# For the END block below.
my $cleaning = 0;
my $justexit = 1;
my $signaled = 0;

my $tbdir    = "$TB/bin";
114
my $tbdata   = "tbdata";
115
my $checkquota = "$TB/sbin/checkquota";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
116
my $vtopgen  = "$TB/bin/vtopgen";
117
my $batch    = 0;
118
my $idleswap = 0;
119 120
my $autoswap = 0;
my $force    = 0;
121
my $lockforce= 0;
Chad Barb's avatar
Chad Barb committed
122
my $reboot   = 0;
123
my $waitmode = 0;
124
my $quiet    = 0;
125
my $genimode = 0;
126 127
my $noswapout= 0;
my $noreconfig=0;
128
my $eventsys_restart   = 0;
129
my $errorstat= -1;
130 131
my $modifyHosed   = 0;
my $modifySwapped = 0;
132
my $robotexp = 0;
133
my $template_node = 0;
134
my $noemail      = 0;
135
my $xmlout       = 0;
Chad Barb's avatar
Chad Barb committed
136

137
my $inout;
138
my $logfile;
139
my $logname;
140
my @allnodes;
141
my @row;
142
my $action;
143
my $tag;
144
my $nextswapstate;
145
my $termswapstate;
Chad Barb's avatar
Chad Barb committed
146

Kevin Atkinson's avatar
Kevin Atkinson committed
147 148
my $modifyError; # needed when emailing error

149
# Protos
150
sub fatal($;$);
151 152 153
sub CheckFWinfo($);
sub GatherFWinfo();
		
154 155 156
#
# Untaint the path
# 
157
$ENV{'PATH'} = "/bin:/usr/bin:$TB/libexec/vis";
158 159 160 161 162 163 164
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

165 166 167 168 169 170 171
#
# 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);

172 173 174 175 176 177 178 179
#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
180 181 182
if (defined($options{"i"})) {
    $idleswap = 1;
}
183 184 185
if (defined($options{"w"})) {
    $waitmode = 1;
}
186 187 188 189 190 191
if (defined($options{"a"})) {
    $autoswap = 1;
}
if (defined($options{"f"})) {
    $force = 1;
}
192 193 194
if (defined($options{"o"})) {
    $lockforce = 1;
}
195
if (defined($options{"g"})) {
196 197 198 199 200 201
    $genimode  = 1;
    $noswapout = 1;
}
if (defined($options{"n"})) {
    $noswapout  = 1;
    $noreconfig = 1;
202
}
203 204 205
if (defined($options{"b"})) {
    $batch = 1;
}
Chad Barb's avatar
Chad Barb committed
206 207 208
if (defined($options{"r"})) {
    $reboot = 1;
}
209 210 211
if (defined($options{"e"})) {
    $eventsys_restart = 1;
}
212 213 214
if (defined($options{"q"})) {
    $quiet = 1;
}
215 216 217
if (defined($options{"x"})) {
    $template_mode = 1;
}
218 219 220
if (defined($options{"N"})) {
    $noemail = 1;
}
221 222 223 224
if (defined($options{"X"})) {
    $quiet = 1;
    $xmlout = 1;
}
225 226 227
if (defined($options{"s"})) {
    $inout = $options{"s"};

Chad Barb's avatar
Chad Barb committed
228 229 230
    if ($inout ne "out"     &&
	$inout ne "in"      &&
	$inout ne "restart" &&
231
	$inout ne "pause"   &&
232
	$inout ne "modify") {
233 234 235 236 237 238 239
	usage();
    }
}
else {
    usage();
}

240 241 242 243 244
usage()
    if (($waitmode && $batch) ||
	($inout ne "modify" && @ARGV != 2) ||
	(($waitmode || $batch) && ($idleswap || $autoswap || $force)));

245 246 247 248 249
if ($eventsys_restart && $inout ne "modify") {
    print STDOUT "Usage: swapexp: -e (eventsys_restart) can be used ".
                 "only with -s modify\n";
    usage();
}
250 251 252
my $pid   = $ARGV[0];
my $eid   = $ARGV[1];

253 254 255
#
# Untaint the arguments.
#
256
if ($pid =~ /^([-\w\.]+)$/) {
257 258 259
    $pid = $1;
}
else {
260
    tbdie("Tainted argument $pid!");
261
}
262
if ($eid =~ /^([-\w\.]+)$/) {
263 264 265
    $eid = $1;
}
else {
266
    tbdie("Tainted argument $eid!");
267
}
268
my $repfile = "tbreport.log";
269 270
my $tempnsfile;
my $modnsfile;
271
my $nsfile;
272

273
if ($inout eq "modify" && @ARGV > 2) {
274 275 276 277 278
    $tempnsfile = $ARGV[2];

    #
    # Untaint nsfile argument; Allow slash.
    #
279
    if ($tempnsfile =~ /^([-\w\.\/]+)$/) {
280
	$tempnsfile = $1;
281 282
    }
    else {
283
	tbdie("Tainted nsfile name: $tempnsfile");
284 285 286 287 288 289
    }
    #
    # Called from ops interactively. Make sure NS file in /proj or /users.
    #
    # Use realpath to resolve any symlinks.
    #
290
    my $translated = realpath($tempnsfile);
291 292
    if ($translated =~ /^([-\w\.\/]+)$/) {
	$tempnsfile = $1;
293
    }
294
    else {
295
	tbdie("Tainted nsfile returned by realpath: $translated");
296 297 298
    }

    #
299 300 301 302 303 304 305
    # 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.
306 307 308
    #
    if (! ($tempnsfile =~ /^\/tmp\/[-\w]+-\d+\.nsfile/) &&
	! ($tempnsfile =~ /^\/var\/tmp\/php\w+/) &&
309
	! ($tempnsfile =~ /^\/tmp\/php\w+/) &&
310
	! TBValidUserDir($tempnsfile, $ISFS)) {
311
	tbdie("$tempnsfile does not resolve to an allowed directory!");
312 313 314
    }

    if (! -f $tempnsfile || -z $tempnsfile || ! -r $tempnsfile) {
315
	tbdie("$tempnsfile does not look like an NS file!");
316
    }
317 318
    $nsfile    = "$eid.ns";
    $modnsfile = "${eid}-modify.ns";
319
}
320

321 322 323 324 325 326 327 328
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();
329
my $infodir = $experiment->InfoDir();
330

331 332 333 334
#
# 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.
#
335
if (my $instance = Template::Instance->LookupByExptidx($experiment->idx())) {
336
    if ($inout ne "in" && !$template_mode) {
337 338 339 340 341
	die("*** $0:\n".
	    "    $pid/$eid is a template instance; use another command\n");
    }
}

342
# Sanity check.
343
if (! -e $workdir) {
344
    die("*** $0:\n".
345 346 347 348 349 350 351
	"    $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");
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
}
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");
    }
}

370 371 372 373 374
# XXX Hack for geni mode.
if ($genimode) {
    $experiment->SetState(EXPTSTATE_ACTIVE);
}

375
#
376
# Verify user and get his DB uid and other info for later.
377
#
378 379 380
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
381
}
382 383 384 385 386
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();
387

388 389 390 391 392 393 394 395 396 397 398
#
# 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();

399 400 401 402 403
#
# Set error reporting info
#
tblog_set_info($pid,$eid,$UID);

404
#
405
# Verify that this person can muck with the experiment.
406 407
# Note that any script down the line has to do an admin check also. 
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
408
if ($UID && !$isadmin &&
409
    ! $experiment->AccessCheck($this_user, TB_EXPT_DESTROY)) {
410
    tbdie("You do not have permission to swap or modify this experiment!");
411 412
}

413 414 415 416
# Must do this before lock tables!
# idleswap is in minutes, threshold is in hours
$idleswap_time = 60 * TBGetSiteVar("idle/threshold");

417 418 419 420 421 422 423 424 425
#
# In wait mode, block interrupt until we spin off the background process.
#
if ($waitmode) {
    $SIG{TERM} = 'IGNORE';
    $SIG{QUIT} = 'IGNORE';
    $SIG{INT}  = 'IGNORE';
}

426 427 428
#
# Check for overquota; we deal with it below, cause of the batch system.
#
429
my $overquota = system("$checkquota -p $pid $user_uid");
430 431

if ($overquota) {
432 433
    tberror({cause => 'user', severity => SEV_WARNING,
	     error => ['over_disk_quota', $CONTROL]},
434 435
	    "You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
436 437
}

438 439 440 441 442 443 444 445 446 447 448 449
#
# Lets check to make sure user did not delete their home dir.
# Maybe in the future, when exports_setup does not cause all
# mounts to hiccup.
#
if (0 && $inout ne "out" && $inout ne "pause") {
    my $homdirerror;
    if ($this_user->HomeDirOkay(\$homdirerror) != 0) {
	ExitWithStatus(1, "$homdirerror\n");
    }
}

450 451 452 453
#
# Temp fix; Disallow swapmod to firewalled experiments. This will come
# out later.
#
454
my $firewalled = $experiment->IsFirewalled();
455

456 457 458 459 460 461 462 463 464 465
#
# 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');

466 467 468
# See below.
my $sharingvlans = $experiment->SharingVlans();

469 470 471 472 473 474 475
# Do not swapout the shared node experiment on a failed modify.
# Do not reboot or reconfig either.
if ($inout eq "modify" &&
    $pid eq TBOPSPID() &&
    ($eid eq "shared-nodes" || $eid eq "shared-node")) {
    $noswapout  = 1;
    $noreconfig = 1;
476
    $reboot     = 0;
477 478
}

479 480 481 482 483
#
# 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
484
# the tb scripts.
485
#
486
$experiment->LockTables() == 0
487 488 489 490 491 492 493
    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();
494
my $canceled        = $experiment->canceled();
495 496 497 498 499 500 501 502 503 504 505 506 507 508
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();
509

510 511
if ($inout ne "out") {
    # I'm going to update this below, so fix the value before I use it.
512
    $idleswap_time = min($idleswaptime * 60, $idleswap_time);
513 514 515
    $idleswaptime = $idleswap_time / 60.0;
}

516 517
my $swapsettings = 
  "Idle-Swap:   $idleswapstr".
518
  ($idleswapbit ? ", at $idleswaptime hours\n" : " (Reason: $noidleswap)\n").
519 520
  "Auto-Swap:   $autoswapstr".
  ($autoswapbit ? ", at $autoswaptime hours\n" : "\n");
521

522
if (! chdir($workdir)) {
523
    tbdie("Could not chdir to $workdir: $!");
524 525
}

526
#
527 528 529
# This script is called from the batch daemon.
# 
if ($batch) {
530
    #
531 532 533
    # 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. 
534
    #
535
    tbdie("Experiment $pid/$eid is supposed to be a batch experiment!")
536 537
	if (!$isbatchexpt);
    
538
    tbdie("Batch experiment $pid/$eid should be locked!")
539 540
	if (!defined($expt_locked) ||
	    $batchstate ne BATCHSTATE_LOCKED());
541 542
    
    tbdie("Batch experiment $pid/$eid is locked down; cannot be swapped!")
543 544
	if ($lockdown);

545
    if ($inout eq "in") {
546 547
	tbdie("Batch experiment $pid/$eid is not in the proper state!\n".
	      "Currently $estate, but should be QUEUED.")
548 549
	    if ($estate ne EXPTSTATE_QUEUED);
	
550 551 552
	tbdie({cause => 'canceled', severity => SEV_IMMEDIATE,
	       error => ['cancel_flag']},
	      "Batch experiment $pid/$eid has been canceled! Aborting.")
553
	    if ($canceled);
554 555

	# Do not allow it to swap in. What about swapout? 
556 557 558
	tbdie({type => 'primary', severity => SEV_ERROR,
	       error => ['over_disk_quota', $CONTROL]},
	      "Batch experiment cannot swap in when over quota! Aborting.")
559
	    if ($overquota);
560 561
    }
    elsif ($inout eq "out") {
562 563
	tbdie("Batch experiment $pid/$eid is not in the proper state!\n".
	      "Currently $estate, but should be ACTIVE.")
564
	    if ($estate ne EXPTSTATE_ACTIVE);
565 566
    }
    else {
567
	tbdie("Improper request from batch daemon for $pid/$eid!\n");
568 569 570 571
    }
}
else {
    if ($isbatchexpt) {
572 573 574 575
	#
	# User is requesting that a batch either be injected or paused.
	# Sanity check the state, but otherwise let the batch daemon
	# handle it.
576 577
	#
	ExitWithStatus(1, "Batch experiment $pid/$eid is still canceling!")
578
	    if ($canceled);
579

580 581 582
	ExitWithStatus(1, "Batch experiment $pid/$eid is locked down!")
	    if ($lockdown);

583
	if ($inout eq "in") {
584
	    ExitWithStatus(1,
585 586 587
			   "Batch experiment $pid/$eid must be SWAPPED to\n".
			   "QUEUE. Currently $estate.")
		if ($estate ne EXPTSTATE_SWAPPED);
588

589 590 591 592 593 594 595 596
	    #
	    # 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!")
597
		if ($experiment->creator() ne $user_uid);
598

599 600 601 602 603 604
	    if ($overquota) {
		tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		ExitWithStatus(1,
			       "Batch experiment $pid/$eid cannot swap in when ".
			       "over quota!\n")
	    }
605
	    
606
	    $experiment->SetState(EXPTSTATE_QUEUED);
607 608
	}
	elsif ($inout eq "out") {
609
	    ExitWithStatus(1,
610 611 612 613
			   "Batch experiment $pid/$eid must be ACTIVE or\n".
			   "ACTIVATING to swap out. Currently $estate.")
		if ($estate ne EXPTSTATE_ACTIVE &&
		    $estate ne EXPTSTATE_ACTIVATING);
614 615 616 617 618

	    #
	    # Since the batch daemon has control, all we can do is set
	    # the cancel bit.
	    # 
619
	    $experiment->SetCancelFlag(EXPTCANCEL_SWAP);
620 621
	}
	elsif ($inout eq "pause") {
622
	    ExitWithStatus(1,
623 624 625
			   "Batch experiment $pid/$eid must be QUEUED to\n".
			   "DEQUEUE. Currently $estate.")
		if ($estate ne EXPTSTATE_QUEUED);
626 627

	    #
628
	    # XXX. The batch daemon might already have the experiment, but
629 630
	    # not have shipped it off to startexp. Use a cancel flag since
	    # that is the only consistent mechanism to tell the batch daemon
631 632 633 634
	    # what it should do. Otherwise, we can just change its state
	    # to yank it from the queue.
	    #
	    if ($batchstate ne BATCHSTATE_UNLOCKED()) {
635
		$experiment->SetCancelFlag(EXPTCANCEL_DEQUEUE);
636 637
	    }
	    else {
638
		$experiment->SetState(EXPTSTATE_SWAPPED);
639
	    }
640
	}
641
	elsif ($inout eq "modify") {
642
	    ExitWithStatus(1,
643 644 645 646
			   "Batch experiment $pid/$eid must be SWAPPED or\n".
			   "ACTIVE to modify. Currently $estate.")
		if (($estate ne EXPTSTATE_SWAPPED &&
		     $estate ne EXPTSTATE_ACTIVATING) ||
647
		    $batchstate ne BATCHSTATE_UNLOCKED());
648

649 650 651
	    ExitWithStatus(1,
			"Cannot modify an active firewalled experiment (yet).")
		if ($firewalled && $estate ne EXPTSTATE_SWAPPED && !$isadmin);
652

653 654
	    ExitWithStatus(1,
			"Cannot modify an active ElabInElab experiment (yet).")
655
		if ($elabinelab && $estate ne EXPTSTATE_SWAPPED);
656

657 658 659 660 661 662
	    if ($overquota) {
		tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		ExitWithStatus(1,
			       "Cannot modify batch experiment $pid/$eid when ".
			       "over quota!\n")
	    }
663
	    
664
	    #
665
	    # Otherwise, proceed with the modify. The experiment will be
666 667
	    # locked below, and so it cannot be injected or otherwise messed
	    # with since its state is going to be changed before we unlock
668 669 670 671
	    # 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. 
672
	    #
673 674
	    goto doit;
	}
675
	else {
676
	    tbdie("Operation $inout not allowed on a batch experiment!");
677
	}
678 679
	ExitWithStatus(0, 
		       "Batch experiment $pid/$eid state has been changed.\n");
680
      doit:
681
    }
682 683 684 685 686 687 688 689 690 691
    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);
692

693 694
 	ExitWithStatus(1,
		       "Experiment $pid/$eid is locked down; cannot swap!\n")
695
	    if ($lockdown && !$lockforce);
696

697 698
	ExitWithStatus(1,
		       "Experiment is sharing vlans; cannot swap or modify!\n")
699
	    if (($inout eq "out" || $inout eq "modify") && $sharingvlans);
700

701 702 703 704 705 706 707 708 709 710
	#
	# 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!");
		  }
711 712 713 714 715 716
		  if ($overquota) {
		      tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		      ExitWithStatus(1,
				     "Experiment $pid/$eid cannot swap in when ".
				     "over quota!\n")
		  }
717
		  
718 719 720 721
		  last SWITCH;
	      };
	      /^out$/i && do {
		  if ($estate ne EXPTSTATE_ACTIVE() &&
Leigh B. Stoller's avatar
Leigh B. Stoller committed
722
 		      $estate ne EXPTSTATE_PANICED() &&
723 724 725 726 727 728
		      $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
729 730 731 732 733 734 735 736 737 738 739 740
 		  #
 		  # 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.");
 		  }

741 742 743 744 745
		  if ($estate eq EXPTSTATE_ACTIVATING()) {
		      #
		      # All we can do is set the cancel flag and hope that
		      # it gets noticed. We do not wait. 
		      # 
746
		      $experiment->SetCancelFlag(EXPTCANCEL_SWAP);
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
		      
		      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");
		  }
770
		  ExitWithStatus(1,
771 772 773 774
			"Cannot modify an active firewalled experiment (yet).")
		      if ($firewalled &&
			  $estate ne EXPTSTATE_SWAPPED && !$isadmin);

775
		  ExitWithStatus(1,
776 777 778
			"Cannot modify an active ElabInElab experiment (yet).")
		      if ($elabinelab &&
			  $estate ne EXPTSTATE_SWAPPED && !$isadmin);
779

780 781 782 783 784 785
		  if ($overquota) {
		      tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		      ExitWithStatus(1,
				     "Experiment $pid/$eid cannot be modified ".
				     "when over quota!\n")
		  }
786
		  
787 788
		  last SWITCH;
	      };
789
	      tbdie("Missing state check for action: $action");
790
	  }
791 792
	}
    }
793 794
}

795 796 797 798 799 800 801
#
# 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 {
802
	$nextswapstate = EXPTSTATE_ACTIVATING();
803 804 805
	last SWITCH;
    };
    /^out$/i && do {
806
	$nextswapstate = EXPTSTATE_SWAPPING();
807 808 809
	last SWITCH;
    };
    /^restart$/i && do {
810
	$nextswapstate = EXPTSTATE_RESTARTING();
811 812 813
	last SWITCH;
    };
    /^modify$/i && do {
814 815
	$nextswapstate = (($estate eq EXPTSTATE_SWAPPED()) ?
			  EXPTSTATE_MODIFY_PARSE() : EXPTSTATE_MODIFY_REPARSE());
816 817
	last SWITCH;
    };
818
    tbdie("Missing state check for action: $action");
819
}
820 821
 
# Update idleswap_timeout to whatever the current value is.
822
if ($inout ne "out") {
823 824
    $experiment->UpdateIdleSwapTime($idleswap_time) == 0
	or tbdie("Could not update idleswap timeout for $pid/$eid");
825
}
826

827 828 829 830 831
#
# On a failure, we go back to this swapstate. Might be modified below.
# 
$termswapstate = $estate;

832 833 834
# Lock the record, set the nextstate, and unlock the table. Unlock
# tables at same time.
$experiment->Lock($nextswapstate, 1) == 0
835 836 837
    or tbdie({type => 'secondary', severity => SEV_SECONDARY,
	      error => ['set_experiment_state_failed', $nextswapstate]},
	     "Failed to set experiment state to $nextswapstate");
838 839
# Maybe Lock() should do this?
$experiment->Refresh();
840 841 842 843 844 845 846

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

847 848 849 850 851 852
# 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!");
}

853 854
#
# XXX - At this point a failure is going to leave things in an
855 856 857 858
# 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). 
859 860
#

861 862
if ($inout eq "in") {
    $action = "swapped in";
863
    $tag    = "swapin";
864 865 866
}
if ($inout eq "out") {
    $action = "swapped out";
867
    $tag    = "swapout";
868 869 870 871
}
if ($inout eq "restart") {
    $action = "restarted";
}
872 873
if ($inout eq "modify") {
    $action = "modified";
874
    $tag    = "swapmod";
875
}
876

877 878 879
#
# Before going to background, we have to copy out the NS file!
#
880
if ($inout eq "modify" && defined($modnsfile)) {
881 882
    unlink($modnsfile);
    if (system("/bin/cp", "$tempnsfile", "$modnsfile")) {
883
	fatal("Could not copy $tempnsfile to $modnsfile");
884 885 886 887
    }
    chmod(0664, "$modnsfile");
}

888 889 890
#
# If not in batch mode, go into the background. Parent exits.
#
891
if (! $batch && ! $template_mode && !$genimode) {
892 893 894 895
    # Cleanup
    $experiment->CleanLogFiles() == 0
	or fatal("Could not clean up logfiles!");

896 897
    $logfile = $experiment->CreateLogFile("swapexp");
    if (!defined($logfile)) {
898 899
	fatal("Could not create logfile!");
    }
900 901 902 903 904
    $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
905

906 907
    if (my $childpid = TBBackGround($logname)) {
	#
908 909
	# Parent exits normally, unless in waitmode. We have to set
	# justexit to make sure the END block below does not run.
910
	#
911 912
	$justexit = 1;

913
	if (!$waitmode) {
914 915 916
	    print("Experiment $pid/$eid is now being $action.\n".
		  "You will be notified via email when the this is done.\n")
		if (! $quiet);
917 918
	    exit(0);
	}
919 920 921 922 923 924 925 926
	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");
	}
927 928 929 930 931 932 933 934 935 936 937 938
	
	# 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';

939
	#
940
	# Wait until child exits or until user gets bored and types ^C.
941
	#
942 943
	waitpid($childpid, 0);
	
944 945
	print("Done. Exited with status: $?\n")
	    if (! $quiet);
946 947 948

	my $exit_code = $? >> 8;

949
	if ($exit_code != 0) {
950
	    my $d = tblog_lookup_error();
951 952 953 954 955 956 957 958 959 960 961 962 963
	    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";
964
	    } elsif (!$quiet) {
965 966
		print $output;
	    }
967 968 969
	}
	exit $exit_code;

970
    }
971
    TBdbfork();
972 973
}

974 975 976 977 978 979 980 981
#
# 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();
}

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
#
# 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';

1002 1003 1004 1005
#
# Gather stats; start clock ticking
#
if ($inout eq "in") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1006
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPIN, $estate) == 0 or
1007
	fatal("Preswap failed!");
1008 1009
}
elsif ($inout eq "out") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1010
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPOUT, $estate) == 0 or
1011
	fatal("Preswap failed!");
1012 1013
}
elsif ($inout eq "modify") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1014
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPMODIFY, $estate) == 0 or
1015
	fatal("Preswap failed!");
1016 1017
}

1018 1019 1020
#
# Remove old report file since its contents are going to be invalid.
#
1021
if ($inout ne "restart" && -e $repfile) {
1022 1023 1024
    unlink("$repfile");
}

1025 1026 1027 1028
#
# Sanity check states in case someone changes something.
#
if ($inout eq "out") {
1029
    my $optarg = (($force || $idleswap) ? "-force" : "");
1030

1031
    if ($experiment->Swap($Experiment::EXPT_SWAPOUT, $optarg) != 0) {
1032
	$errorstat = $? >> 8;
1033 1034 1035
	fatal({type => 'secondary', severity => SEV_SECONDARY,
	       error => ['tbswap_out_failed']},
	      "tbswap out failed!");
1036
    }
1037 1038 1039 1040

    #
    # Add the files that have been detected by tracing to the archive.
    #
1041 1042 1043 1044 1045 1046 1047
    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!");
	}
1048

1049 1050 1051 1052 1053 1054 1055 1056 1057
	#
	# 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
1058 1059
    }

1060
    $experiment->SetState(EXPTSTATE_SWAPPED) == 0
1061 1062 1063
	or fatal({type => 'secondary', severity => SEV_SECONDARY,
		  error => ['set_experiment_state_failed', EXPTSTATE_SWAPPED()]},
	         "Failed to set experiment state to " . EXPTSTATE_SWAPPED());
1064
    
1065
    $experiment->SetPanicBit(0) == 0
1066
	or fatal("Failed to clear the panic bit!");
1067
}
1068
elsif ($inout eq "in") {
1069 1070
    # 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.
1071
    $experiment->SetSwapper($this_user);
1072

1073
    if ($experiment->Swap($Experiment::EXPT_SWAPIN) != 0) {
1074
	$errorstat = $? >> 8;
1075 1076 1077
	fatal({type => 'secondary', severity => SEV_SECONDARY,
	       error => ['tbswap_in_failed']},
	      "tbswap in failed!");
1078
    }
1079 1080
    
    $experiment->SetState(EXPTSTATE_ACTIVE) == 0
1081 1082 1083
	or fatal({type => 'secondary', severity => SEV_SECONDARY,
		  error => ['set_experiment_state_failed', EXPTSTATE_ACTIVE()]},
	         "Failed to set experiment state to " . EXPTSTATE_ACTIVE());
1084 1085
    
    $experiment->Report($repfile, "-b");
Chad Barb's avatar
Chad Barb committed
1086
}
1087
elsif ($inout eq "modify") {
1088 1089 1090
    #
    # Prepare the Archive for the swapmod, in case we have to "roll back".
    #
1091 1092 1093 1094 1095
    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!");
	}
1096 1097
    }

1098 1099 1100 1101 1102
    # 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
1103
    print "Backing up old experiment state ... " . TBTimeStamp() . "\n";
1104 1105
    $experiment->BackupVirtualState() == 0
	or fatal("Could not backup experiment state; cannot safely continue!");
Chad Barb's avatar
Chad Barb committed
1106 1107

    #