template_instantiate.in 21.9 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2006, 2007 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{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/>.
# 
# }}}
23 24
#
use English;
25
use strict;
26
use Getopt::Std;
27
use POSIX qw(setsid);
28 29 30 31
use POSIX qw(strftime);
use Errno qw(EDQUOT);
use XML::Simple;
use Data::Dumper;
32
use Cwd qw(realpath);
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

#
# 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
Leigh Stoller's avatar
Leigh Stoller committed
49
	  "Usage: template_instantiate [-q] [-w] [-s]\n".
50 51 52
	  "         [-S reason] [-L reason] [-a <time>] [-l <time>] ".
	  "-e <eid> <guid/vers>\n".
	  "switches and arguments:\n".
53
	  "-b       - batchmode; insert into batch queue\n".
54
	  "-p       - preload only; do not swapin\n".
55 56
	  "-w       - wait for template to be instantiated\n".
	  "-q       - be less chatty\n".
57
	  "-E <str> - A pithy sentence describing the instance\n".
58
	  "-x <file>- XML file of parameter bindings\n".
59 60 61 62 63 64 65 66 67 68
	  "-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);
}
69
my $optlist	 = "qwe:S:L:na:l:se:x:bE:t:r:fp";
70 71 72
my %options      = ();
my $quiet        = 0;
my $waitmode     = 0;
73
my $batchmode    = 0;
74
my $foreground   = 0;
75
my $preload      = 0;
76
my $description;
77 78 79
my $paramfile;
my $guid;
my $version;
80 81
my $eid;
my %parameters   = ();
82 83 84 85 86 87 88 89 90 91 92

#
# Configure variables
#
my $TB		= "@prefix@";
my $EVENTSYS	= @EVENTSYS@;
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
my $TBDOCBASE	= "@TBDOCBASE@";
my $TBBASE	= "@TBBASE@";
my $CONTROL	= "@USERNODE@";
93
my $BOSSNODE    = "@BOSSNODE@";
94
my $OPSDBSUPPORT= @OPSDBSUPPORT@;
95
my $STAMPS      = @STAMPS@;
96 97

# Locals
98
my $EVhandle;
99
my $exptidx;
100 101
my $template;
my $instance;
102
my $logfile;
103
my $template_tag;
104
my @ExptStates  = ();
105 106 107 108
# For the END block below.
my $cleaning    = 0;
my $exptcreated = 0;
my $justexit    = 1;
109 110 111 112 113
# 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.
114 115 116 117

# Programs we need
my $checkquota  = "$TB/sbin/checkquota";
my $batchexp    = "$TB/bin/batchexp";
118
my $swapin      = "$TB/bin/template_swapin";
119
my $endexp      = "$TB/bin/endexp";
120
my $dbcontrol   = "$TB/sbin/opsdb_control";
121
my $archcontrol = "$TB/bin/archive_control";
122 123
my $CVSBIN      = "/usr/bin/cvs";
my $RLOG        = "/usr/bin/rlog";
124 125 126 127 128

# Protos
sub ParseArgs();
sub fatal($$);
sub sighandler($);
129
sub SetupEventHandler();
130 131 132 133 134 135 136 137

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
138
use Template;
139
use Experiment;
140
use User;
141
use event;
142
use libaudit;
143

144 145
# In libdb
my $projroot = PROJROOT();
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

#
# 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.
#
169 170 171
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    tbdie("You ($UID) do not exist!");
172
}
173 174 175 176
my $user_dbid  = $this_user->dbid();
my $user_uid   = $this_user->uid();
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
177 178 179 180 181

#
# Before doing anything else, check for overquota ... lets not waste
# our time. Make sure user sees the error by exiting with 1.
#
182
if (system("$checkquota $user_uid") != 0) {
183 184
    tberror("You are over your disk quota on $CONTROL; ".
	    "please login there and cleanup!");
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    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';
}

#
201
# Grab template and do access check.
202
#
203
$template = Template->Lookup($guid, $version);
204

205 206 207
if (!defined($template)) {
    tbdie("Experiment template $guid/$version does not exist!");
}
208 209 210 211 212
my $project = $template->GetProject();
if (!defined($project)) {
    tbdie("Could not get project for $template");
}
if (! $project->AccessCheck($this_user, TB_PROJECT_CREATEEXPT)) {
213 214 215 216 217
    tberror("You do not have permission to instantiate template ".
	    "$guid/$version");
    exit(1);
}

218 219 220 221
if ($STAMPS) {
    $template->Stamp("template_instantiate", "start");
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
#
# 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
238 239 240 241 242 243
	$replay_run = $replay_instance->FirstRun();
    }
    else {
	$replay_run =
	    Template::Instance::Run->LookupByID($replay_exptidx,
						$replay_runidx);
244 245 246 247 248 249 250
    }

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

251 252
#
# If we have a parameter file, we need to copyin the values and store
253 254
# them in the DB for this experiment. Note that these override existing
# values, so we start with those first.
255 256 257 258
#
# XXX Do we keep these values in the DB forever? Or just keep the XML file
# around and archived? 
#
259 260 261
$template->FormalParameterList(\%parameters) == 0
    or tbdie("Could not get formal parameter list for $template");

262 263 264 265 266
if (defined($paramfile)) {
    my $donebad = 0;
    
    my $parse  = XMLin($paramfile,
		       VarAttr => 'name',
267
		       ForceArray => ['parameter'],
268 269 270 271
		       ContentKey => '-content',
		       SuppressEmpty => undef);

    foreach my $name (keys(%{ $parse->{'parameter'} })) {
272
	my $value = $parse->{'parameter'}->{"$name"}->{'value'};
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

	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.
288 289 290
	# Watch for unwanted parameters.
	$parameters{$name} = $value
	    if (exists($parameters{$name}));
291 292 293 294 295 296
    }
    # User sees this error.
    exit(1)
	if ($donebad);
}

297
#
298
# Generate a new template instance record.
299 300
# We will finish updating it later.
#
301
$instance = $template->NewInstance($eid, $this_user, $description);
302
if (!defined($instance)) {
303 304 305
    fatal(-1, "Could not insert new experiment instance record!");
}

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

312 313 314 315
if ($STAMPS) {
    $instance->Stamp("template_instantiate", "created");
}

316
#
317 318
# Now insert the binding records for the instance so that the parser
# can get them.
319 320 321 322 323
#
if ($paramfile) {
    foreach my $name (keys(%parameters)) {
	my $value = $parameters{$name};

324 325
	$instance->NewBinding($name, $value) == 0
	    or fatal(-1, "Error inserting binding into DB!");
326 327
    }
}
328 329
elsif (defined($replay_instance)) {
    #
330 331 332
    # 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. 
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    #
    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}));
    }
}
351

352
#
353 354
# We make a copy of either the underlying template experiment, or of the
# replay argument.
355
#
356 357
my $pid    = $template->pid();
my $copyid = $template->pid() . "," . $template->eid();
358

359 360 361 362 363 364 365 366
#
# 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();
}

367 368 369 370 371 372 373 374 375
#
# 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.
#
376
if (! $foreground) {
377 378
    $logfile = $instance->CreateLogFile("swapin");
    if (!defined($logfile)) {
379 380
	fatal(-1, "Could not create logfile!");
    }
381 382
    # Mark it open, since it exists.
    $logfile->Open();
383

384
    if (my $childpid = AuditStart(LIBAUDIT_DAEMON, $logfile->filename(),
385
			  LIBAUDIT_LOGONLY|LIBAUDIT_NODELETE|LIBAUDIT_FANCY)) {
386 387 388 389 390 391 392
	#
	# 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) {
393 394 395 396 397
	    my $idx = $instance->idx();

	    # XXX The web interface depends on this line.
	    print("Instance $pid/$eid ($idx) is now being instantiated.\n")
		if (! $quiet);
398 399
	    exit(0);
	}
400
	print("Waiting for instance $pid/$eid to fully instantiate.\n")
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
	    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();
430 431 432 433 434 435 436

    # Add audit info.  Right now this will only work when called in
    # the child of the script being audited.  Eventually these can be
    # set anywhere.
    AddAuditInfo("which", "$pid/$eid");
    AddAuditInfo("failure_frag", "T. Instantiation Failure");
    AddAuditInfo("success_frag", "New T. Instance Created");
437 438
}

439 440 441 442
if ($STAMPS) {
    $instance->Stamp("template_instantiate", "batchexp start");
}

443 444 445 446 447 448 449 450 451
#
# 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 =
452 453
    ($batchexp, "-x", "$guid/$version,$guid/$version",
     "-y", $instance->idx(), "-q", "-f",
454
     "-p", $pid, "-e", $eid, "-g", $template->gid(),
455
     "-E", "'Experiment Template Instantiation $guid/$version' ",
456
     "-c" , $copyid);
457

458 459 460
# All the other goo.
push(@arguments, "-i")
    if (!$batchmode);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
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;

484 485 486 487
if ($STAMPS) {
    $instance->Stamp("template_instantiate", "batchexp done");
}

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
# 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!");
    }
510
    $experiment->Refresh();
511 512
}

513
#
514 515 516
# Need the current archive tag so that we can mark the new instance
# with the the corresponding state of the archive.
# 
517 518 519 520
libArchive::TBExperimentArchiveTag($template->pid(),
				   $template->eid(), \$template_tag) == 0
    or fatal(-1, "Could not get current tag for $template");

521 522 523
#
# Update the Instance
#
524
my %args = ();
525 526
$args{'exptidx'}      = $exptidx;
$args{'template_tag'} = $template_tag;
527

528 529
$instance->Update(0, \%args) == 0
    or fatal(-1, "Could not update experiment instance record!");
530

531 532
my $workdir = $experiment->WorkDir();
my $userdir = $experiment->UserDir();
533 534

#
535
# Now we stash the parameter file.
536 537
#
if ($paramfile) {
538
    system("/bin/cp", $paramfile, $userdir . "/parameters.xml") == 0
539 540 541
	or tbdie("Could not copy out $paramfile");
}

542
#
543 544
# Grab a checkout of the datastore and place it into the exp directory.
# This is essentially a copy.
545
#
546
my $instance_path = $userdir;
547 548

#
549 550 551 552 553 554 555 556 557
# Using the repository now ... the archive will eventually go away.
#
my $cvstag  = "T${guid}-${version}";
my $cvsdir  = "$projroot/$pid/templates/$guid/cvsrepo";

#
# 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.
558 559
#
if (defined($replay_instance)) {
560 561 562 563 564 565 566 567 568
    $cvstag = "T${guid}-" . $replay_instance->vers();
}
my $revision = `$RLOG -h $cvsdir/setup/.template,v | grep '${cvstag}:'`;

if (! $?) {
    print "Checking out a copy of the template datastore ($cvstag)\n";
    System("cd $instance_path; $CVSBIN -d $cvsdir ".
	   "    checkout -r '$cvstag' -d datastore setup/datastore")
	== 0 or fatal(-1, "Could not checkout from $cvsdir");
569 570 571 572 573 574 575 576 577 578

    System("cd $instance_path; $CVSBIN -d $cvsdir ".
	   "    checkout -r '$cvstag' -d . setup/.template")
	== 0 or fatal(-1, "Could not checkout from $cvsdir");

    # Want this file to be a sandbox file.
    unlink("$instance_path/tbdata/nsfile.ns");
    System("cd $instance_path; $CVSBIN -d $cvsdir ".
	   "    checkout -r '$cvstag' -d tbdata setup/tbdata")
	== 0 or fatal(-1, "Could not checkout from $cvsdir");
579
}
580 581
else {
    my $datastore_tag = $template_tag;
582

583 584 585 586 587 588 589 590 591 592 593 594 595 596
    #
    # 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();
    }

    print "Checking out a copy of the template datastore ($datastore_tag)\n";
    $instance->CopyDataStore($datastore_tag,
			     "$instance_path", $replay_instance) == 0
        or fatal(-1, "Could not copy datastore to instance");
}
597

598
# Ditto for dynamic events. 
599 600 601
$instance->CopyTemplateEvents() == 0
    or fatal(-1, "Could not copy template events to instance");

602
if (! $preload) {
603 604 605 606
    if ($STAMPS) {
	$instance->Stamp("template_instantiate", "swapin starting");
    }
    
607
    #
608
    # Now do the swapin (or it gets queued if a batch experiment).
609
    #
610 611 612
    system("$swapin -w -f -e $eid $guid/$version");
    if ($?) {
	fatal(-1, "Could not swapin instance $instance!");
613
    }
614
}
615
else {
616 617 618 619
    if ($STAMPS) {
	$instance->Stamp("template_instantiate", "preload commit");
    }
    
620 621 622 623 624 625 626 627
    #
    # Lets commit the experiment archive now. The experiment might already
    # be running, but thats not a big deal.
    #
    system("$archcontrol -t instantiate commit $pid $eid");
    if ($?) {
	fatal(-1, "Could not commit archive!");
    }
628
}
629

630 631 632 633
if ($STAMPS) {
    $instance->Stamp("template_instantiate", "done");
}

634
# Stop the web interface from spewing.
635 636
$logfile->Close()
    if (defined($logfile));
637

638
# Email is sent from libaudit at exit ...
639 640 641 642 643 644 645 646 647 648 649 650 651 652 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
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;
    }
692 693 694
    if (defined($options{"f"})) {
	$foreground = 1;
    }
695 696 697
    if (defined($options{"p"})) {
	$preload = 1;
    }
698 699 700
    if (defined($options{"b"})) {
	$batchmode = 1;
    }
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
    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;
	}
    }

727 728
    if (defined($options{"x"})) {
	my $inputfile = $options{"x"};
729 730 731 732 733 734 735 736 737 738 739 740 741 742

	# 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.
	#
743
	my $translated = realpath($inputfile);
744 745 746 747 748 749 750 751
	if ($translated =~ /^([-\w\.\/]+)$/) {
	    $inputfile = $1;
	}
	else {
	    tbdie("Bad data returned by realpath: $translated");
	}

	#
752 753 754 755 756 757
	# 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.  These .xml files
	# are allowed since this script is invoked directly from web interface
	# which generates a name that should not be guessable.
758 759 760 761
	#
	if (! ($inputfile =~ /^\/tmp\/[-\w]+-\d+\.xml/) &&
	    ! ($inputfile =~ /^\/tmp\/\d+\.xml/) &&
	    ! ($inputfile =~ /^\/var\/tmp\/php\w+/) &&
762
	    ! TBValidUserDir($inputfile, 0)) {
763 764 765 766 767 768
	    tberror("$inputfile does not resolve to an allowed directory!");
	    # Note positive status; so error goes to user not tbops.
	    exit(1);
	}
	$paramfile = $inputfile;
    }
769 770 771

    if (defined($options{"E"})) {
	if (! TBcheck_dbslot($options{"E"},
772
			     "experiment_template_instances", "description",
773 774 775 776 777
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    tbdie("Improper template description!");
	}
	$description = $options{"E"};
    }
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792

    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");
	}
    }
793 794 795 796 797 798 799
}

#
# Cleanup the mess.
#
sub cleanup()
{
800
    if (defined($experiment)) {
801 802
	# Before killing it, save off the user directory for debugging.
	$experiment->BackupUserData();
803

804
	$experiment->End("-f") == 0
805
	    or exit(-1);
806
    }
807 808
    # The web interface will stop spewing when the instance is deleted
    # cause instance Delete removes the logfile entry too.
809 810
    $instance->Delete()
	if (defined($instance));
811

812 813 814 815 816
    #
    # Cleanup DB state for the experiment now that instance is gone.
    #
    $experiment->Delete()
	if (defined($experiment));
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
}

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. 
	#
854 855
	SENDMAIL($TBOPS, 
		 "Template Creation Failure: $pid/$eid",
856 857 858 859 860 861 862 863 864
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}