template_swapin.in 22.5 KB
Newer Older
1 2 3 4 5 6 7
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
# Copyright (c) 2006 University of Utah and the Flux Group.
# All rights reserved.
#
use English;
8
use strict;
9
use Getopt::Std;
10
use POSIX qw(setsid);
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
use POSIX qw(strftime);
use Errno qw(EDQUOT);
use XML::Simple;
use Data::Dumper;

#
# Create a new experiment template. 
#
# 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 - Everything okay.
# $status > 0 - Expected error. User not allowed for some reason. 
# 
sub usage()
{
    print(STDERR
	  "Usage: template_swapin [-q] [-w] [-s]\n".
	  "         [-S reason] [-L reason] [-a <time>] [-l <time>] ".
	  "-e <eid> <guid/vers>\n".
	  "switches and arguments:\n".
35
	  "-b       - batchmode; insert into batch queue\n".
36 37
	  "-w       - wait for template to be instantiated\n".
	  "-q       - be less chatty\n".
38
	  "-E <str> - A pithy sentence describing the instance\n".
39
	  "-x <file>- XML file of parameter bindings\n".
40 41 42 43 44 45 46 47 48 49
	  "-S <str> - Instance cannot be swapped; must provide reason\n".
	  "-L <str> - Instance cannot be IDLE swapped; must provide reason\n".
	  "-n       - Do not send idle email (internal option only)\n".
	  "-a <nnn> - Auto swapout nnn minutes after instance is swapped in\n".
	  "-l <nnn> - Auto swapout nnn minutes after instance goes idle\n".
	  "-s       - Save disk state on swapout\n".
	  "-e <eid> - The instance name (unique, alphanumeric, no blanks)\n".
	  "<guid/vers> - GUID and version to swapin\n");
    exit(-1);
}
50
my $optlist	 = "qwe:S:L:na:l:se:x:bE:t:r:f";
51 52 53
my %options      = ();
my $quiet        = 0;
my $waitmode     = 0;
54
my $batchmode    = 0;
55
my $foreground   = 0;
56
my $description;
57 58 59
my $paramfile;
my $guid;
my $version;
60 61
my $eid;
my %parameters   = ();
62 63 64 65 66 67 68 69 70 71 72 73

#
# Configure variables
#
my $TB		= "@prefix@";
my $PROJROOT	= "/proj";
my $EVENTSYS	= @EVENTSYS@;
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
my $TBDOCBASE	= "@TBDOCBASE@";
my $TBBASE	= "@TBBASE@";
my $CONTROL	= "@USERNODE@";
74
my $BOSSNODE    = "@BOSSNODE@";
75
my $OPSDBSUPPORT= @OPSDBSUPPORT@;
76 77 78 79 80

# Locals
my $user_name;
my $user_email;
my $dbuid;
81
my $EVhandle;
82
my $exptidx;
83 84
my $template;
my $instance;
85
my $run;
86
my $logname;
87
my $template_tag;
88
my @ExptStates  = ();
89 90 91 92
# For the END block below.
my $cleaning    = 0;
my $exptcreated = 0;
my $justexit    = 1;
93 94 95 96 97
# For replay
my $replay_exptidx;	# Instance to replay.
my $replay_runidx;	# Optional run within instance to replay.
my $replay_instance;	# Replay a complete instance, from first run.
my $replay_run;	        # Replay starting with a particular run in instance.
98 99 100 101 102 103

# Programs we need
my $checkquota  = "$TB/sbin/checkquota";
my $batchexp    = "$TB/bin/batchexp";
my $swapexp     = "$TB/bin/swapexp";
my $endexp      = "$TB/bin/endexp";
104
my $dbcontrol   = "$TB/sbin/opsdb_control";
105
my $archcontrol = "$TB/bin/archive_control";
106 107 108 109 110

# Protos
sub ParseArgs();
sub fatal($$);
sub sighandler($);
111
sub SetupEventHandler();
112 113 114 115 116 117 118 119

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
120
use Template;
121
use Experiment;
122
use event;
123
use libaudit;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

# Be careful not to exit on transient error
$libdb::DBQUERY_MAXTRIES = 0;

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

#
# 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);

#
# Untaint the path
#
# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Verify user and get his DB uid.
#
if (! UNIX2DBUID($UID, \$dbuid)) {
    tbdie("You do not exist in the Emulab Database!");
}

#
# Get email info for user.
#
if (! UserDBInfo($dbuid, \$user_name, \$user_email)) {
    tbdie("Cannot determine your name and email address.");
}

#
# Before doing anything else, check for overquota ... lets not waste
# our time. Make sure user sees the error by exiting with 1.
#
if (system("$checkquota $dbuid") != 0) {
    tberror("You are over your disk quota on $CONTROL; please cleanup!");
    exit(1);
}

# Now parse arguments.
ParseArgs();

#
# In wait mode, block SIGINT until we spin off the background process.
#
if ($waitmode) {
    $SIG{QUIT} = 'IGNORE';
    $SIG{TERM} = 'IGNORE';
    $SIG{INT}  = 'IGNORE';
}

#
183
# Grab template and do access check.
184
#
185
$template = Template->Lookup($guid, $version);
186

187 188 189 190 191 192
if (!defined($template)) {
    tbdie("Experiment template $guid/$version does not exist!");
}
if (! TBProjAccessCheck($dbuid,
			$template->pid(), $template->gid(),
			TB_PROJECT_CREATEEXPT)) {
193 194 195 196 197
    tberror("You do not have permission to instantiate template ".
	    "$guid/$version");
    exit(1);
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#
# Grab instance and/or run if this is a replay.
#
if (defined($replay_exptidx)) {
    $replay_instance =
      Template::Instance->LookupByExptidx($replay_exptidx);

    if (!defined($replay_instance)) {
	tbdie("Replay Instance $replay_exptidx does not exist!");
    }

    if (!defined($replay_runidx)) {
	#
	# Default to first run.
	#
	# XXX Need to convert these other routines to return Run objects
	my $row = $replay_instance->FirstRun();
215
	if (!defined($row)) {
216 217 218 219 220 221 222 223 224 225 226 227 228
	    tbdie("Could not find first run for $replay_instance!");
	}
	$replay_runidx = $row->{'idx'};
    }

    $replay_run =
      Template::Instance::Run->LookupByID($replay_exptidx, $replay_runidx);

    if (!defined($replay_run)) {
	tbdie("Replay Run $replay_runidx does not exist!");
    }
}

229 230
#
# If we have a parameter file, we need to copyin the values and store
231 232
# them in the DB for this experiment. Note that these override existing
# values, so we start with those first.
233 234 235 236
#
# XXX Do we keep these values in the DB forever? Or just keep the XML file
# around and archived? 
#
237 238 239
$template->FormalParameterList(\%parameters) == 0
    or tbdie("Could not get formal parameter list for $template");

240 241 242 243 244 245 246 247 248
if (defined($paramfile)) {
    my $donebad = 0;
    
    my $parse  = XMLin($paramfile,
		       VarAttr => 'name',
		       ContentKey => '-content',
		       SuppressEmpty => undef);

    foreach my $name (keys(%{ $parse->{'parameter'} })) {
249
	my $value = $parse->{'parameter'}->{"$name"}->{'value'};
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

	if (! TBcheck_dbslot($name,
			     "experiment_template_instance_bindings", "name",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tberror("Illegal characters in parameter name: $name");
	    $donebad++;
	}
	if (defined($value) &&
	    ! TBcheck_dbslot($value,
			     "experiment_template_instance_bindings", "value",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tberror("Illegal characters in parameter value: $value");
	    $donebad++;
	}
	# DB records inserted below, once experiment is pre-loaded.
265 266 267
	# Watch for unwanted parameters.
	$parameters{$name} = $value
	    if (exists($parameters{$name}));
268 269 270 271 272 273
    }
    # User sees this error.
    exit(1)
	if ($donebad);
}

274
#
275
# Generate a new template instance record.
276 277
# We will finish updating it later.
#
278 279
$instance = $template->NewInstance($eid, $dbuid);
if (!defined($instance)) {
280 281 282
    fatal(-1, "Could not insert new experiment instance record!");
}

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

289
#
290 291
# Now insert the binding records for the instance so that the parser
# can get them.
292 293 294 295 296
#
if ($paramfile) {
    foreach my $name (keys(%parameters)) {
	my $value = $parameters{$name};

297 298
	$instance->NewBinding($name, $value) == 0
	    or fatal(-1, "Error inserting binding into DB!");
299 300
    }
}
301 302
elsif (defined($replay_instance)) {
    #
303 304 305
    # Bindings come from the replay instance (well, run), although the
    # use can still have provided a parameter file (above) to override
    # the values from the record. 
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    #
    my %replay_bindings = ();

    $replay_run->BindingList(\%replay_bindings) == 0
	or fatal(-1, "Error getting bindings from $replay_run!");

    foreach my $name (keys(%replay_bindings)) {
	my $value = $replay_bindings{$name};

	# Insert into new instance now, for the parser to pick up.
	$instance->NewBinding($name, $value) == 0
	    or fatal(-1, "Error inserting binding into DB!");

	# These are used below for inserting the run bindings.
	$parameters{$name} = $value
	    if (exists($parameters{$name}));
    }
}
324

325
#
326 327
# We make a copy of either the underlying template experiment, or of the
# replay argument.
328
#
329 330
my $pid    = $template->pid();
my $copyid = $template->pid() . "," . $template->eid();
331

332 333 334 335 336 337 338 339
#
# Ah, but if this is a replay, then the copyid is really a tag in a
# previous experiment. 
#
if (defined($replay_instance)) {
    $copyid = $replay_instance->exptidx() . ":" . $replay_run->start_tag();
}

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
#
# Go to the background now so we have a proper log of what happened.
#
#
$SIG{TERM} = \&sighandler;

#
# Use the logonly option to audit so that we get a record mailed.
#
if (! ($foreground || $batchmode)) {
    if ($instance->CreateLogFile("swapin", \$logname) < 0) {
	fatal(-1, "Could not create logfile!");
    }

    if (my $childpid = AuditStart(LIBAUDIT_DAEMON, $logname,
				  LIBAUDIT_LOGONLY|LIBAUDIT_NODELETE)) {
	#
	# Parent exits normally, unless in waitmode. We have to set
	# justexit to make sure the END block below does not run.
	#
	$justexit = 1;

	if (!$waitmode) {
	    #
	    # Before we can actually exit, we need to wait. Totally ick;
	    # the logfile stuff needs work.
	    #
	    while (1) {
		my ($tmp1, $tmp2);

		last
		    if (TBExptGetLogFile($pid, $eid, \$tmp1, \$tmp2));

		sleep(2);
	    }
	    if ($batchmode) {
		print("Experiment $pid/$eid has entered the batch system.\n".
		      "You will be notified when it is fully instantiated.\n")
		    if (! $quiet);
	    }
	    else {
		print("Experiment $pid/$eid is now being instantiated.\n".
		      "You will be notified via email when this is done.\n")
		    if (! $quiet);
	    }
	    exit(0);
	}
	print("Waiting for experiment $eid to fully instantiate.\n")
	    if (! $quiet);
	    
	if (-t STDIN && !$quiet) {
	    print("You may type ^C at anytime; you will be notified via ".
		  "email.\n".
		  "You will not actually interrupt the instantiation.\n");
	}
	
	# 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';

	#
	# Wait until child exits or until user gets bored and types ^C.
	#
	waitpid($childpid, 0);
	
	print("Done. Exited with status: $?\n")
	    if (! $quiet);
	exit($? >> 8);
    }
    TBdbfork();
}

419 420 421 422 423 424 425 426 427
#
# Build up arguments to batchexp. I do not want to bother with shell
# escapes, hence the list argument to system instead of a long string.
# Be sure to leave it this way, or perl will invoke a shell and that
# would be a really bad thing.
#
# Note special -x option.
#
my @arguments =
428
    ($batchexp, "-x", $template->eid(), "-y", $instance->idx(), "-q", "-f",
429
     "-p", $pid, "-e", $eid, "-g", $template->gid(),
430
     "-E", "'Experiment Template Instantiation $guid/$version' ",
431
     "-c" , $copyid);
432

433 434 435
# All the other goo.
push(@arguments, "-i")
    if (!$batchmode);
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
push(@arguments, "-s")
    if (defined($options{"s"}));
push(@arguments, "-n")
    if (defined($options{"n"}));
push(@arguments, ("-S", $options{"S"}))
    if (defined($options{"S"}));
push(@arguments, ("-L", $options{"L"}))
    if (defined($options{"L"}));
push(@arguments, ("-l", $options{"l"}))
    if (defined($options{"l"}));
push(@arguments, ("-a", $options{"a"}))
    if (defined($options{"a"}));
push(@arguments, ("-t", $options{"t"}))
    if (defined($options{"t"}));

# Now invoke batchexp.
system(@arguments);
fatal($? >> 8, "Could not pre-instantiate the experiment")
    if ($?);

# Need to kill the experiment if we fail after this point.
$exptcreated = 1;

459 460 461 462 463 464 465 466
#
# Now we can do this ...
#
if (defined($logname) && ! ($foreground || $batchmode)) {
    TBExptSetLogFile($pid, $eid, $logname);
    TBExptOpenLogFile($pid, $eid);
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
# Grab the experiment record for below.
my $experiment = Experiment->Lookup($pid, $eid);
if (!defined($experiment)) {
    fatal(-1, "Experiment $pid/$eid could not be found after creation!");
}
$exptidx = $experiment->idx();

#
# Templates always get a DB; override the NS file setting of dpdb, and
# then call out to have it created.
#
if ($OPSDBSUPPORT) {
    my %args = ();
    
    $args{'dpdb'} = 1;

    $experiment->Update(\%args) == 0
	or fatal(-1, "Could not update experiment record!");
    
    if (system("$dbcontrol addexpdb $pid $eid")) {
	fatal(-1, "$dbcontrol addexpdb failed!");
    }
489
    $experiment->Refresh();
490 491
}

492
#
493 494 495
# Need the current archive tag so that we can mark the new instance
# with the the corresponding state of the archive.
# 
496 497 498 499
libArchive::TBExperimentArchiveTag($template->pid(),
				   $template->eid(), \$template_tag) == 0
    or fatal(-1, "Could not get current tag for $template");

500 501 502
#
# Update the Instance
#
503
my %args = ();
504 505
$args{'exptidx'}      = $exptidx;
$args{'template_tag'} = $template_tag;
506

507 508
$instance->Update(0, \%args) == 0
    or fatal(-1, "Could not update experiment instance record!");
509 510 511 512

# Event connect now that experiment is created.
SetupEventHandler();

513 514
my $workdir = $experiment->WorkDir();
my $userdir = $experiment->UserDir();
515 516

#
517
# Now we stash the parameter file.
518 519 520 521 522 523
#
if ($paramfile) {
    system("/bin/cp", $paramfile, $userdir . "/archive/parameters.xml") == 0
	or tbdie("Could not copy out $paramfile");
}

524
#
525 526
# Grab a checkout of the datastore and place it into the exp directory.
# This is essentially a copy.
527
#
528
my $instance_path = $userdir;
529 530 531 532 533 534 535 536 537 538 539
my $datastore_tag = $template_tag;

#
# But if this is a replay, then use the tag corresponding to the run being
# replayed, so that we get the datastore that was in place when the run was,
# well, originally run.
#
if (defined($replay_instance)) {
    $datastore_tag = $replay_run->start_tag();
}

540
print "Checking out a copy of the template datastore ($datastore_tag)\n";
541
$instance->CopyDataStore($datastore_tag,
Leigh B. Stoller's avatar
Leigh B. Stoller committed
542
			 "$instance_path/datastore") == 0
543
    or fatal(-1, "Could not copy datastore to instance");
544

545
# Ditto for dynamic events. 
546 547 548
$instance->CopyTemplateEvents() == 0
    or fatal(-1, "Could not copy template events to instance");

549 550 551
# We munge the environment variables.
$instance->InitializeEnvVariables(\%parameters) == 0
    or fatal(-1, "Could not add new environment variables to instance");
552
    
553 554 555 556
print "Writing environment strings ...\n";
$instance->WriteEnvVariables() == 0
    or fatal(-1, "Could not write environment strings for program agents");

557
#
558
# Now do the swapin (or it gets queued if a batch experiment).
559 560 561 562 563 564 565
#
@arguments = ($swapexp, "-q", "-x", "-s", "in", $pid, $eid);

system(@arguments);
fatal($? >> 8, "Could not instantiate the experiment")
    if ($?);

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
#
# We will spew forth info to the user each time the batch daemon tries to
# swap it in. 
#
if ($batchmode) {
    #
    # Spin waiting for the state to change in swapexp. We are waiting for
    # it to swapin or go back to swapped.
    #
    my $queued = 0;
    
    while (1) {
	@ExptStates = ();
	event_poll_blocking($EVhandle, 500);

	next
	    if (! @ExptStates);

	foreach my $state (@ExptStates) {
	    print "$state\n";
	    
	    if ($state eq EXPTSTATE_ACTIVATING()) {
		print "Experiment is starting a swapin attempt ...\n";
	    }
	    elsif ($state eq EXPTSTATE_ACTIVE()) {
		print "Experiment swapped in!\n";
		goto done;
	    }
	    elsif ($state eq EXPTSTATE_QUEUED()) {
		# Failed to swapin; still queued in the batch system.
		if (! $queued) {
		    print "Experiment has entered the batch system\n";
		    $queued = 1;
		}
		else {
		    print "Experiment swapin attempt failed.\n";
		}
	    }
	    elsif ($state eq EXPTSTATE_SWAPPED()) {
		# Dumped out of the batch system for some reason.
606
		print "Experiment has been removed from the batch queue.\n";
607 608 609 610 611 612 613 614 615 616 617

		#
		# We are done; remove record of this attempt and exit.
		#
		fatal(1, "Experiment has been removed from the batch queue");
	    }
	}
    }
  done:
}

618 619 620 621 622 623 624 625 626
#
# Lets commit the experiment archive now that it is active. The experiment is
# already running, but thats not a big deal.
#
system("$archcontrol -t instantiate commit $pid $eid");
if ($?) {
    fatal(-1, "Could not commit archive!");
}

627
#
628
# All instances currently start with a default run.
629
#
630 631 632 633
$run = $instance->NewRun($eid, $description);
if (!defined($run)) {
    fatal(-1, "Could not create new experiment run for $instance!");
}
634

635 636 637
#
# And the bindings for the default run ...
#
638 639
foreach my $name (keys(%parameters)) {
    my $value = $parameters{$name};
640

641 642
    $instance->NewRunBinding($name, $value) == 0
	or fatal(-1, "Error inserting run binding into DB!");
643
}
644

645
$instance->StartRun(Template::STARTRUN_FLAGS_FIRSTRUN()) == 0
646
    or fatal(-1, "Could not update start time in instance record!");
647

648 649
# Stop the web interface from spewing.
TBExptCloseLogFile($pid, $eid)
650
    if (defined($logname) && !$batchmode);
651

652
# Email is sent from libaudit at exit ...
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
exit(0);

#
# Parse command arguments. Once we return from getopts, all that are
# left are the required arguments.
#
sub ParseArgs()
{
    if (! getopts($optlist, \%options)) {
	usage();
    }

    if (@ARGV != 1) {
	usage();
    }
    #
    # Pick up guid/version first and untaint.
    #
    my $tmp = shift(@ARGV);

    if ($tmp =~ /^([\w]*)\/([\d]*)$/) {
	$guid = $1;
	$version = $2;
    }
    else {
	tbdie("Bad data in argument: $tmp");
    }

    if (defined($options{"e"})) {
	$eid = $options{"e"};

	if ($eid =~ /^([-\w]+)$/) {
	    $eid = $1;
	}
	else {
	    tbdie("Bad data in argument: $eid.");
	}
	if (! TBcheck_dbslot($eid, "experiments", "eid",
			   TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper experiment name (id)!");
	}
    }
    else {
	tberror("Must provide an experiment ID (-e option)!");
	exit(1);
    }

    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"w"})) {
	$waitmode = 1;
    }
706 707 708
    if (defined($options{"f"})) {
	$foreground = 1;
    }
709 710 711
    if (defined($options{"b"})) {
	$batchmode = 1;
    }
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    if (defined($options{"S"})) {
	if ($options{"S"} =~ /^(.*)$/) {
	    $options{"S"} = $1;
	}
    }
    if (defined($options{"L"})) {
	if ($options{"L"} =~ /^(.*)$/) {
	    $options{"L"} = $1;
	}
    }
    if (defined($options{"l"})) {
	if ($options{"l"} =~ /^(.*)$/) {
	    $options{"l"} = $1;
	}
    }
    if (defined($options{"a"})) {
	if ($options{"a"} =~ /^(.*)$/) {
	    $options{"a"} = $1;
	}
    }
    if (defined($options{"t"})) {
	if ($options{"t"} =~ /^(.*)$/) {
	    $options{"t"} = $1;
	}
    }

738 739
    if (defined($options{"x"})) {
	my $inputfile = $options{"x"};
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

	# Note different taint check (allow /).
	if ($inputfile =~ /^([-\w\.\/]+)$/) {
	    $inputfile = $1;
	}
	else {
	    tbdie("Bad data in parameter file: $inputfile");
	}

	#
	# Called from ops interactively. Make sure NS file in /proj or /users.
	#
	# Use realpath to resolve any symlinks.
	#
	my $translated = `realpath $inputfile`;
	if ($translated =~ /^([-\w\.\/]+)$/) {
	    $inputfile = $1;
	}
	else {
	    tbdie("Bad data returned by realpath: $translated");
	}

	#
	# The file must reside in /proj, /groups, or /users. Since this script
	# runs as the caller, regular file permission checks ensure its a file
	# the user is allowed to use. /tmp/$pid-$eid.nsfile.XXXXX also allowed
	# since this script is invoked directly from web interface.
	#
	if (! ($inputfile =~ /^\/tmp\/[-\w]+-\d+\.xml/) &&
	    ! ($inputfile =~ /^\/tmp\/\d+\.xml/) &&
	    ! ($inputfile =~ /^\/var\/tmp\/php\w+/) &&
	    ! ($inputfile =~ /^\/proj/) &&
	    ! ($inputfile =~ /^\/groups/) &&
	    ! ($inputfile =~ /^\/users/)) {
	    tberror("$inputfile does not resolve to an allowed directory!");
	    # Note positive status; so error goes to user not tbops.
	    exit(1);
	}
	$paramfile = $inputfile;
    }
780 781 782 783 784 785 786 787 788

    if (defined($options{"E"})) {
	if (! TBcheck_dbslot($options{"E"},
			     "experiment_templates", "description",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper template description!");
	}
	$description = $options{"E"};
    }
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803

    if (defined($options{"r"})) {
	my $replay_option = $options{"r"};

	if ($replay_option =~ /^([\d]+)$/) {
	    $replay_exptidx = $1;
	}
	elsif ($replay_option =~ /^([\d]+):([\d]+)$/) {
	    $replay_exptidx = $1;
	    $replay_runidx  = $2;
	}
	else {
	    tbdie("Bad data in argument: $replay_option");
	}
    }
804 805
}

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
#
# Subscribe to experiment state change events.
#
sub SetupEventHandler()
{
    my $port = @BOSSEVENTPORT@;
    my $URL  = "elvin://localhost:$port";
    
    # Connect to the event system, and subscribe the the events we want
    $EVhandle = event_register($URL, 0);
    
    if (!$EVhandle) {
	tbdie("Unable to register with event system\n");
    }

    my $tuple = address_tuple_alloc();
    if (!$tuple) {
	tbdie("Could not allocate an address tuple\n");
    }

    %$tuple = ( objtype   => libdb::TBDB_TBEVENT_EXPTSTATE(),
		objname   => "$pid/$eid",
		expt      => "$pid/$eid",
		host      => $BOSSNODE,
	      );
    
    if (!event_subscribe($EVhandle, \&EventHandler, $tuple)) {
	tbdie("Could not subscribe to events\n");
    }
}

#
# Callback for above.
#
sub EventHandler($$$) {
    my ($handle,$notification,undef) = @_;
    
    my $objname   = event_notification_get_objname($handle,$notification);
    my $eventtype = event_notification_get_eventtype($handle,$notification);

    print "$objname, $eventtype\n";

    return
	if ($objname ne "$pid/$eid");

    push(@ExptStates, $eventtype);
}

854 855 856 857 858 859 860 861
#
# Cleanup the mess.
#
sub cleanup()
{
    if ($exptcreated) {
	exit(-1)
	    if (!TBExptIDX($pid, $eid, \$exptidx));
862 863 864

	# Before killing it, save off the user directory for debugging.
	$experiment->BackupUserData();
865 866 867 868
		
	system("$endexp -x -q -w $pid $eid");
	exit(-1)
	    if ($?);
869
    }
870 871
    $instance->Delete()
	if (defined($instance));
872

873 874
    # Stop the web interface from spewing.
    TBExptCloseLogFile($pid, $eid)
875
	if (defined($logname) && !$batchmode);
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
}

sub fatal($$)
{
    my ($errorstat, $msg) = @_;
    
    tberror $msg;
    tbinfo "Cleaning up and exiting with status $errorstat ...";

    #
    # This exit will drop into the END block below.
    # 
    exit($errorstat);
}

sub sighandler ($) {
    my ($signame) = @_;
    
    $SIG{TERM} = 'IGNORE';
    my $pgrp = getpgrp(0);
    kill('TERM', -$pgrp);
    sleep(1);
    fatal(-1, "Caught SIG${signame}! Killing experiment setup ...");
}

END {
    # Normal exit, nothing to do.
    if (!$? || $justexit) {
	return;
    }
    my $saved_exitcode = $?;
    
    if ($cleaning) {
	#
	# We are screwed; a recursive error. Someone will have to clean
	# up by hand. 
	#
913 914
	SENDMAIL($TBOPS, 
		 "Template Creation Failure: $pid/$eid",
915 916 917 918 919 920 921 922 923
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}