swapexp.in 45.2 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-2008 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 13

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

18 19
sub usage()
{
20
    print(STDERR
21
	  "Usage: swapexp [-q] [-b | -w] [-i | -a | -f] [-r] [-e]\n".
22 23 24 25
	  "               <-s in | out | restart | modify | pause>\n".
	  "               <pid> <eid> [<nsfile>]\n".
	  "switches and arguments:\n".
	  "-w       - wait for non-batchmode experiment swap/modify\n".
26
	  "-q       - be less chatty\n".
27 28 29 30 31 32
	  "-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".
	  "<pid>    - The project the experiment belongs to\n".
	  "<eid>    - The experiment name (id)\n".
	  "<nsfile> - Optional NS file to parse for experiment modify\n");
33 34
    exit(-1);
}
35
my  $optlist = "biafres:wqx";
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#
# 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) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
52
	tbdie($message);
53
    }
54
    elsif ($status > 0) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
55
	tbnotice($message);
56
    }
57 58 59
    else {
	tbinfo($message);
    }
60 61 62
    exit($status);
}

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

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
Kevin Atkinson's avatar
 
Kevin Atkinson committed
81
use libtblog;
82
use libArchive;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
83
use Template;
84
use Experiment;
85
use User;
86

87 88 89 90 91 92 93 94 95
# Be careful not to exit on transient error; 0 means infinite retry.
$libdb::DBQUERY_MAXTRIES = 0;

# For the END block below.
my $cleaning = 0;
my $justexit = 1;
my $signaled = 0;

my $tbdir    = "$TB/bin";
96
my $tbdata   = "tbdata";
97
my $checkquota = "$TB/sbin/checkquota";
98
my $batch    = 0;
99
my $idleswap = 0;
100 101
my $autoswap = 0;
my $force    = 0;
Chad Barb's avatar
Chad Barb committed
102
my $reboot   = 0;
103
my $waitmode = 0;
104
my $quiet    = 0;
105
my $eventsys_restart   = 0;
106
my $errorstat= -1;
107 108
my $modifyHosed   = 0;
my $modifySwapped = 0;
109
my $robotexp = 0;
110
my $template_node = 0;
Chad Barb's avatar
 
Chad Barb committed
111

112
my $inout;
113
my $logfile;
114
my $logname;
115
my @allnodes;
116
my @row;
117
my $action;
118
my $tag;
119
my $nextswapstate;
120
my $termswapstate;
Chad Barb's avatar
 
Chad Barb committed
121

Kevin Atkinson's avatar
 
Kevin Atkinson committed
122 123
my $modifyError; # needed when emailing error

124
# Protos
125
sub fatal($;$);
126 127 128
sub CheckFWinfo($);
sub GatherFWinfo();
		
129 130 131
#
# Untaint the path
# 
132
$ENV{'PATH'} = "/bin:/usr/bin:$TB/libexec/vis";
133 134 135 136 137 138 139
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

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

140 141 142 143 144 145 146
#
# 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);

147 148 149 150 151 152 153 154
#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
155 156 157
if (defined($options{"i"})) {
    $idleswap = 1;
}
158 159 160
if (defined($options{"w"})) {
    $waitmode = 1;
}
161 162 163 164 165 166
if (defined($options{"a"})) {
    $autoswap = 1;
}
if (defined($options{"f"})) {
    $force = 1;
}
167 168 169
if (defined($options{"b"})) {
    $batch = 1;
}
Chad Barb's avatar
 
Chad Barb committed
170 171 172
if (defined($options{"r"})) {
    $reboot = 1;
}
173 174 175
if (defined($options{"e"})) {
    $eventsys_restart = 1;
}
176 177 178
if (defined($options{"q"})) {
    $quiet = 1;
}
179 180 181
if (defined($options{"x"})) {
    $template_mode = 1;
}
182 183 184
if (defined($options{"s"})) {
    $inout = $options{"s"};

Chad Barb's avatar
Chad Barb committed
185 186 187
    if ($inout ne "out"     &&
	$inout ne "in"      &&
	$inout ne "restart" &&
188
	$inout ne "pause"   &&
Chad Barb's avatar
 
Chad Barb committed
189
	$inout ne "modify") {
190 191 192 193 194 195 196
	usage();
    }
}
else {
    usage();
}

197 198 199 200 201
usage()
    if (($waitmode && $batch) ||
	($inout ne "modify" && @ARGV != 2) ||
	(($waitmode || $batch) && ($idleswap || $autoswap || $force)));

202 203 204 205 206
if ($eventsys_restart && $inout ne "modify") {
    print STDOUT "Usage: swapexp: -e (eventsys_restart) can be used ".
                 "only with -s modify\n";
    usage();
}
Chad Barb's avatar
 
Chad Barb committed
207 208 209
my $pid   = $ARGV[0];
my $eid   = $ARGV[1];

210 211 212
#
# Untaint the arguments.
#
213
if ($pid =~ /^([-\w\.]+)$/) {
214 215 216
    $pid = $1;
}
else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
217
    tbdie("Tainted argument $pid!");
218
}
219
if ($eid =~ /^([-\w\.]+)$/) {
220 221 222
    $eid = $1;
}
else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
223
    tbdie("Tainted argument $eid!");
224
}
225
my $repfile = "tbreport.log";
226 227
my $tempnsfile;
my $modnsfile;
228
my $nsfile;
229

Leigh B. Stoller's avatar
Leigh B. Stoller committed
230
if ($inout eq "modify" && @ARGV > 2) {
231 232 233 234 235
    $tempnsfile = $ARGV[2];

    #
    # Untaint nsfile argument; Allow slash.
    #
236
    if ($tempnsfile =~ /^([-\w\.\/]+)$/) {
237
	$tempnsfile = $1;
238 239
    }
    else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
240
	tbdie("Tainted nsfile name: $tempnsfile");
241 242 243 244 245 246 247 248 249
    }
    #
    # 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;
250
    }
251
    else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
252
	tbdie("Tainted nsfile returned by realpath: $translated");
253 254 255
    }

    #
256 257 258 259 260 261 262
    # 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.
263 264 265
    #
    if (! ($tempnsfile =~ /^\/tmp\/[-\w]+-\d+\.nsfile/) &&
	! ($tempnsfile =~ /^\/var\/tmp\/php\w+/) &&
266 267
	! TBValidUserDir($tempnsfile, 0)) {
	tbdie("$tempnsfile does not resolve to an allowed directory!");
268 269 270
    }

    if (! -f $tempnsfile || -z $tempnsfile || ! -r $tempnsfile) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
271
	tbdie("$tempnsfile does not look like an NS file!");
272
    }
273 274
    $nsfile    = "$eid.ns";
    $modnsfile = "${eid}-modify.ns";
275
}
276

277 278 279 280 281 282 283 284 285
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();

286 287 288 289
#
# 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.
#
290
if (my $instance = Template::Instance->LookupByExptidx($experiment->idx())) {
291
    if ($inout ne "in" && !$template_mode) {
292 293 294 295 296
	die("*** $0:\n".
	    "    $pid/$eid is a template instance; use another command\n");
    }
}

297
#
298
# Verify user and get his DB uid and other info for later.
299
#
300 301 302
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
303
}
304 305 306 307 308
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();
309

310 311 312 313 314 315 316 317 318 319 320
#
# 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();

Kevin Atkinson's avatar
 
Kevin Atkinson committed
321 322 323 324 325
#
# Set error reporting info
#
tblog_set_info($pid,$eid,$UID);

326
#
Chad Barb's avatar
 
Chad Barb committed
327
# Verify that this person can muck with the experiment.
328 329
# Note that any script down the line has to do an admin check also. 
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
330
if ($UID && !$isadmin &&
331
    ! $experiment->AccessCheck($this_user, TB_EXPT_DESTROY)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
332
    tbdie("You do not have permission to swap or modify this experiment!");
333 334
}

335 336 337 338
# Must do this before lock tables!
# idleswap is in minutes, threshold is in hours
$idleswap_time = 60 * TBGetSiteVar("idle/threshold");

339 340 341 342 343 344 345 346 347
#
# In wait mode, block interrupt until we spin off the background process.
#
if ($waitmode) {
    $SIG{TERM} = 'IGNORE';
    $SIG{QUIT} = 'IGNORE';
    $SIG{INT}  = 'IGNORE';
}

348 349 350
#
# Check for overquota; we deal with it below, cause of the batch system.
#
351
my $overquota = system("$checkquota $user_uid");
352 353

if ($overquota) {
354 355
    tberror({cause => 'user', severity => SEV_WARNING,
	     error => ['over_disk_quota', $CONTROL]},
356 357
	    "You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
358 359
}

360 361 362 363
#
# Temp fix; Disallow swapmod to firewalled experiments. This will come
# out later.
#
364
my $firewalled = $experiment->IsFirewalled();
365

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

376 377 378 379 380
#
# 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
381
# the tb scripts.
382
#
383
$experiment->LockTables() == 0
384 385 386 387 388 389 390
    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();
391
my $canceled        = $experiment->canceled();
392 393 394 395 396 397 398 399 400 401 402 403 404 405
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();
406

407 408
if ($inout ne "out") {
    # I'm going to update this below, so fix the value before I use it.
409
    $idleswap_time = min($idleswaptime * 60, $idleswap_time);
410 411 412
    $idleswaptime = $idleswap_time / 60.0;
}

413 414
my $swapsettings = 
  "Idle-Swap:   $idleswapstr".
415
  ($idleswapbit ? ", at $idleswaptime hours\n" : " (Reason: $noidleswap)\n").
416 417
  "Auto-Swap:   $autoswapstr".
  ($autoswapbit ? ", at $autoswaptime hours\n" : "\n");
418

419
if (! chdir($workdir)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
420
    tbdie("Could not chdir to $workdir: $!");
421 422
}

423
#
424 425 426
# This script is called from the batch daemon.
# 
if ($batch) {
427
    #
428 429 430
    # 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. 
431
    #
Kevin Atkinson's avatar
 
Kevin Atkinson committed
432
    tbdie("Experiment $pid/$eid is supposed to be a batch experiment!")
433 434
	if (!$isbatchexpt);
    
Kevin Atkinson's avatar
 
Kevin Atkinson committed
435
    tbdie("Batch experiment $pid/$eid should be locked!")
436 437
	if (!defined($expt_locked) ||
	    $batchstate ne BATCHSTATE_LOCKED());
Kevin Atkinson's avatar
 
Kevin Atkinson committed
438 439
    
    tbdie("Batch experiment $pid/$eid is locked down; cannot be swapped!")
440 441
	if ($lockdown);

442
    if ($inout eq "in") {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
443 444
	tbdie("Batch experiment $pid/$eid is not in the proper state!\n".
	      "Currently $estate, but should be QUEUED.")
445 446
	    if ($estate ne EXPTSTATE_QUEUED);
	
447 448 449
	tbdie({cause => 'canceled', severity => SEV_IMMEDIATE,
	       error => ['cancel_flag']},
	      "Batch experiment $pid/$eid has been canceled! Aborting.")
450
	    if ($canceled);
451 452

	# Do not allow it to swap in. What about swapout? 
453 454 455
	tbdie({type => 'primary', severity => SEV_ERROR,
	       error => ['over_disk_quota', $CONTROL]},
	      "Batch experiment cannot swap in when over quota! Aborting.")
456
	    if ($overquota);
457 458
    }
    elsif ($inout eq "out") {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
459 460
	tbdie("Batch experiment $pid/$eid is not in the proper state!\n".
	      "Currently $estate, but should be ACTIVE.")
461
	    if ($estate ne EXPTSTATE_ACTIVE);
462 463
    }
    else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
464
	tbdie("Improper request from batch daemon for $pid/$eid!\n");
465 466 467 468
    }
}
else {
    if ($isbatchexpt) {
469 470 471 472
	#
	# User is requesting that a batch either be injected or paused.
	# Sanity check the state, but otherwise let the batch daemon
	# handle it.
473 474
	#
	ExitWithStatus(1, "Batch experiment $pid/$eid is still canceling!")
475
	    if ($canceled);
476

477 478 479
	ExitWithStatus(1, "Batch experiment $pid/$eid is locked down!")
	    if ($lockdown);

480
	if ($inout eq "in") {
481
	    ExitWithStatus(1,
482 483 484
			   "Batch experiment $pid/$eid must be SWAPPED to\n".
			   "QUEUE. Currently $estate.")
		if ($estate ne EXPTSTATE_SWAPPED);
485

486 487 488 489 490 491 492 493
	    #
	    # 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!")
494
		if ($experiment->creator() ne $user_uid);
495

496 497 498 499 500 501
	    if ($overquota) {
		tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		ExitWithStatus(1,
			       "Batch experiment $pid/$eid cannot swap in when ".
			       "over quota!\n")
	    }
502
	    
503
	    $experiment->SetState(EXPTSTATE_QUEUED);
504 505
	}
	elsif ($inout eq "out") {
506
	    ExitWithStatus(1,
507 508 509 510
			   "Batch experiment $pid/$eid must be ACTIVE or\n".
			   "ACTIVATING to swap out. Currently $estate.")
		if ($estate ne EXPTSTATE_ACTIVE &&
		    $estate ne EXPTSTATE_ACTIVATING);
511 512 513 514 515

	    #
	    # Since the batch daemon has control, all we can do is set
	    # the cancel bit.
	    # 
516
	    $experiment->SetCancelFlag(EXPTCANCEL_SWAP);
517 518
	}
	elsif ($inout eq "pause") {
519
	    ExitWithStatus(1,
520 521 522
			   "Batch experiment $pid/$eid must be QUEUED to\n".
			   "DEQUEUE. Currently $estate.")
		if ($estate ne EXPTSTATE_QUEUED);
523 524

	    #
525
	    # XXX. The batch daemon might already have the experiment, but
526 527
	    # not have shipped it off to startexp. Use a cancel flag since
	    # that is the only consistent mechanism to tell the batch daemon
528 529 530 531
	    # what it should do. Otherwise, we can just change its state
	    # to yank it from the queue.
	    #
	    if ($batchstate ne BATCHSTATE_UNLOCKED()) {
532
		$experiment->SetCancelFlag(EXPTCANCEL_DEQUEUE);
533 534
	    }
	    else {
535
		$experiment->SetState(EXPTSTATE_SWAPPED);
536
	    }
537
	}
538
	elsif ($inout eq "modify") {
539
	    ExitWithStatus(1,
540 541 542 543
			   "Batch experiment $pid/$eid must be SWAPPED or\n".
			   "ACTIVE to modify. Currently $estate.")
		if (($estate ne EXPTSTATE_SWAPPED &&
		     $estate ne EXPTSTATE_ACTIVATING) ||
544
		    $batchstate ne BATCHSTATE_UNLOCKED());
545

546 547 548
	    ExitWithStatus(1,
			"Cannot modify an active firewalled experiment (yet).")
		if ($firewalled && $estate ne EXPTSTATE_SWAPPED && !$isadmin);
549

550 551 552
	    ExitWithStatus(1,
			"Cannot modify an active ElabInElab experiment (yet).")
		if ($elabinelab && $estate ne EXPTSTATE_SWAPPED && !$isadmin);
553

554 555 556 557 558 559
	    if ($overquota) {
		tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		ExitWithStatus(1,
			       "Cannot modify batch experiment $pid/$eid when ".
			       "over quota!\n")
	    }
560
	    
561
	    #
562
	    # Otherwise, proceed with the modify. The experiment will be
563 564
	    # locked below, and so it cannot be injected or otherwise messed
	    # with since its state is going to be changed before we unlock
565 566 567 568
	    # 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. 
569
	    #
570 571
	    goto doit;
	}
572
	else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
573
	    tbdie("Operation $inout not allowed on a batch experiment!");
574
	}
575 576
	ExitWithStatus(0, 
		       "Batch experiment $pid/$eid state has been changed.\n");
577
      doit:
578
    }
579 580 581 582 583 584 585 586 587 588
    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);
589

590 591 592 593
 	ExitWithStatus(1,
		       "Experiment $pid/$eid is locked down; cannot swap!\n")
	    if ($lockdown);

594 595 596 597 598 599 600 601 602 603
	#
	# 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!");
		  }
604 605 606 607 608 609
		  if ($overquota) {
		      tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		      ExitWithStatus(1,
				     "Experiment $pid/$eid cannot swap in when ".
				     "over quota!\n")
		  }
610
		  
611 612 613 614
		  last SWITCH;
	      };
	      /^out$/i && do {
		  if ($estate ne EXPTSTATE_ACTIVE() &&
Leigh B. Stoller's avatar
Leigh B. Stoller committed
615
 		      $estate ne EXPTSTATE_PANICED() &&
616 617 618 619 620 621
		      $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
622 623 624 625 626 627 628 629 630 631 632 633
 		  #
 		  # 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.");
 		  }

634 635 636 637 638
		  if ($estate eq EXPTSTATE_ACTIVATING()) {
		      #
		      # All we can do is set the cancel flag and hope that
		      # it gets noticed. We do not wait. 
		      # 
639
		      $experiment->SetCancelFlag(EXPTCANCEL_SWAP);
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
		      
		      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");
		  }
663
		  ExitWithStatus(1,
664 665 666 667
			"Cannot modify an active firewalled experiment (yet).")
		      if ($firewalled &&
			  $estate ne EXPTSTATE_SWAPPED && !$isadmin);

668
		  ExitWithStatus(1,
669 670 671
			"Cannot modify an active ElabInElab experiment (yet).")
		      if ($elabinelab &&
			  $estate ne EXPTSTATE_SWAPPED && !$isadmin);
672

673 674 675 676 677 678
		  if ($overquota) {
		      tbreport(SEV_ERROR, 'over_disk_quota', $CONTROL);
		      ExitWithStatus(1,
				     "Experiment $pid/$eid cannot be modified ".
				     "when over quota!\n")
		  }
679
		  
680 681
		  last SWITCH;
	      };
Kevin Atkinson's avatar
 
Kevin Atkinson committed
682
	      tbdie("Missing state check for action: $action");
683
	  }
684 685
	}
    }
686 687
}

688 689 690 691 692 693 694
#
# 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 {
695
	$nextswapstate = EXPTSTATE_ACTIVATING();
696 697 698
	last SWITCH;
    };
    /^out$/i && do {
699
	$nextswapstate = EXPTSTATE_SWAPPING();
700 701 702
	last SWITCH;
    };
    /^restart$/i && do {
703
	$nextswapstate = EXPTSTATE_RESTARTING();
704 705 706
	last SWITCH;
    };
    /^modify$/i && do {
707 708
	$nextswapstate = (($estate eq EXPTSTATE_SWAPPED()) ?
			  EXPTSTATE_MODIFY_PARSE() : EXPTSTATE_MODIFY_REPARSE());
709 710
	last SWITCH;
    };
Kevin Atkinson's avatar
 
Kevin Atkinson committed
711
    tbdie("Missing state check for action: $action");
712
}
713 714
 
# Update idleswap_timeout to whatever the current value is.
715
if ($inout ne "out") {
716 717
    $experiment->UpdateIdleSwapTime($idleswap_time) == 0
	or tbdie("Could not update idleswap timeout for $pid/$eid");
718
}
719

720 721 722 723 724
#
# On a failure, we go back to this swapstate. Might be modified below.
# 
$termswapstate = $estate;

725 726 727
# Lock the record, set the nextstate, and unlock the table. Unlock
# tables at same time.
$experiment->Lock($nextswapstate, 1) == 0
728 729 730
    or tbdie({type => 'secondary', severity => SEV_SECONDARY,
	      error => ['set_experiment_state_failed', $nextswapstate]},
	     "Failed to set experiment state to $nextswapstate");
731 732 733 734 735 736 737

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

738 739 740 741 742 743
# 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!");
}

744 745
#
# XXX - At this point a failure is going to leave things in an
746 747 748 749
# 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). 
750 751
#

752 753
if ($inout eq "in") {
    $action = "swapped in";
754
    $tag    = "swapin";
755 756 757
}
if ($inout eq "out") {
    $action = "swapped out";
758
    $tag    = "swapout";
759 760 761 762
}
if ($inout eq "restart") {
    $action = "restarted";
}
Chad Barb's avatar
 
Chad Barb committed
763 764
if ($inout eq "modify") {
    $action = "modified";
765
    $tag    = "swapmod";
Chad Barb's avatar
 
Chad Barb committed
766
}
767

768 769 770
#
# Before going to background, we have to copy out the NS file!
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
771
if ($inout eq "modify" && defined($modnsfile)) {
772 773
    unlink($modnsfile);
    if (system("/bin/cp", "$tempnsfile", "$modnsfile")) {
774
	fatal("Could not copy $tempnsfile to $modnsfile");
775 776 777 778
    }
    chmod(0664, "$modnsfile");
}

779 780 781
#
# If not in batch mode, go into the background. Parent exits.
#
782
if (! $batch && ! $template_mode) {
783 784 785 786
    # Cleanup
    $experiment->CleanLogFiles() == 0
	or fatal("Could not clean up logfiles!");

787 788
    $logfile = $experiment->CreateLogFile("swapexp");
    if (!defined($logfile)) {
789 790
	fatal("Could not create logfile!");
    }
791 792 793 794 795
    $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
796

797 798
    if (my $childpid = TBBackGround($logname)) {
	#
799 800
	# Parent exits normally, unless in waitmode. We have to set
	# justexit to make sure the END block below does not run.
801
	#
802 803
	$justexit = 1;

804
	if (!$waitmode) {
805 806 807
	    print("Experiment $pid/$eid is now being $action.\n".
		  "You will be notified via email when the this is done.\n")
		if (! $quiet);
808 809
	    exit(0);
	}
810 811 812 813 814 815 816 817
	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");
	}
818 819 820 821 822 823 824 825 826 827 828 829
	
	# 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';

830
	#
831
	# Wait until child exits or until user gets bored and types ^C.
832
	#
833 834
	waitpid($childpid, 0);
	
835 836
	print("Done. Exited with status: $?\n")
	    if (! $quiet);
Kevin Atkinson's avatar
 
Kevin Atkinson committed
837 838 839 840 841 842 843 844 845 846

	my $exit_code = $? >> 8;

	if ($exit_code != 0) {
	    my $d = tblog_lookup_error();
	    print tblog_format_error($d);
	}

	exit $exit_code;

847
    }
848
    TBdbfork();
849 850
}

851 852 853 854 855 856 857 858
#
# 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();
}

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
#
# 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';

879 880 881 882
#
# Gather stats; start clock ticking
#
if ($inout eq "in") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
883
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPIN, $estate) == 0 or
884
	fatal("Preswap failed!");
885 886
}
elsif ($inout eq "out") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
887
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPOUT, $estate) == 0 or
888
	fatal("Preswap failed!");
889 890
}
elsif ($inout eq "modify") {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
891
    $experiment->PreSwap($this_user, TBDB_STATS_SWAPMODIFY, $estate) == 0 or
892
	fatal("Preswap failed!");
893 894
}

895 896 897
#
# Remove old report file since its contents are going to be invalid.
#
898
if ($inout ne "restart" && -e $repfile) {
899 900 901
    unlink("$repfile");
}

902 903 904 905
#
# Sanity check states in case someone changes something.
#
if ($inout eq "out") {
906
    my $optarg = (($force || $idleswap) ? "-force" : "");
907

908
    if ($experiment->Swap($Experiment::EXPT_SWAPOUT, $optarg) != 0) {
909
	$errorstat = $? >> 8;
910 911 912
	fatal({type => 'secondary', severity => SEV_SECONDARY,
	       error => ['tbswap_out_failed']},
	      "tbswap out failed!");
913
    }
914 915 916 917

    #
    # Add the files that have been detected by tracing to the archive.
    #
918 919 920 921 922 923 924
    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!");
	}
925

926 927 928 929 930 931 932 933 934
	#
	# 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
935 936
    }

937
    $experiment->SetState(EXPTSTATE_SWAPPED) == 0
938 939 940
	or fatal({type => 'secondary', severity => SEV_SECONDARY,
		  error => ['set_experiment_state_failed', EXPTSTATE_SWAPPED()]},
	         "Failed to set experiment state to " . EXPTSTATE_SWAPPED());
941
    
942
    $experiment->SetPanicBit(0) == 0
943
	or fatal("Failed to clear the panic bit!");
944
}
945
elsif ($inout eq "in") {
946 947
    # 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.
948
    $experiment->SetSwapper($this_user);
949

950
    if ($experiment->Swap($Experiment::EXPT_SWAPIN) != 0) {
951
	$errorstat = $? >> 8;
952 953 954
	fatal({type => 'secondary', severity => SEV_SECONDARY,
	       error => ['tbswap_in_failed']},
	      "tbswap in failed!");
955
    }
956 957
    
    $experiment->SetState(EXPTSTATE_ACTIVE) == 0
958 959 960
	or fatal({type => 'secondary', severity => SEV_SECONDARY,
		  error => ['set_experiment_state_failed', EXPTSTATE_ACTIVE()]},
	         "Failed to set experiment state to " . EXPTSTATE_ACTIVE());
961 962
    
    $experiment->Report($repfile, "-b");
Chad Barb's avatar
Chad Barb committed
963
}
Chad Barb's avatar
 
Chad Barb committed
964
elsif ($inout eq "modify") {
965 966 967
    #
    # Prepare the Archive for the swapmod, in case we have to "roll back".
    #
968 969 970 971 972
    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!");
	}
973 974
    }

975 976 977 978 979
    # 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
980
    print "Backing up old experiment state ... " . TBTimeStamp() . "\n";
981 982
    $experiment->BackupVirtualState() == 0
	or fatal("Could not backup experiment state; cannot safely continue!");
Chad Barb's avatar
Chad Barb committed
983 984

    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
985
    # Rerun tbprerun if modifying, but only if new NS file provided.
986 987
    # Yep, we allow reswap without changing the NS file. For Shashi and SIM.
    # Note that tbprerun kills the renderer if its running.