batchexp.in 34.9 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
2 3
#
# EMULAB-COPYRIGHT
Leigh B. Stoller's avatar
Leigh B. Stoller committed
4
# Copyright (c) 2000-2006 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5 6
# All rights reserved.
#
7 8
use English;
use Getopt::Std;
9
use POSIX qw(isatty setsid);
10
use POSIX qw(strftime);
11
use Errno qw(EDQUOT);
12 13

#
14 15 16 17
# Create an experiment. The experiment is either run immediately, or
# placed into the batch system to be run later. If no NS file is
# supplied, an experiment shell is created (this is currently an admin
# only option).
18
#
19
# TODO: Remove expt_expires and priority.
20
#       Add calls to check_slot() to verify inputs.
21
# 
Leigh B. Stoller's avatar
Leigh B. Stoller committed
22 23 24 25 26 27 28 29 30
# 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. 
# 
31 32
sub usage()
{
33
    print(STDERR
34
	  "Usage: batchexp [-q] [-i [-w]] [-n] [-f] [-E description] [-g gid]\n".
35
	  "                [-S reason] [-L reason] [-a <time>] [-l <time>]\n".
36
	  "                -p <pid> -e <eid> <nsfile>\n".
37
	  "switches and arguments:\n".
38 39 40
	  "-i       - swapin immediately; by default experiment is batched\n".
	  "-w       - wait for non-batchmode experiment to preload or swapin\n".
	  "-f       - preload experiment (do not swapin or queue yet)\n".
41
	  "-q       - be less chatty\n".
42 43
	  "-S <str> - Experiment cannot be swapped; must provide reason\n".
	  "-L <str> - Experiment cannot be IDLE swapped; must provide reason\n".
44
	  "-n       - Do not send idle email (internal option only)\n".
45 46
	  "-a <nnn> - Auto swapout nnn minutes after experiment is swapped in\n".
	  "-l <nnn> - Auto swapout nnn minutes after experiment goes idle\n".
47
	  "-s       - Save disk state on swapout\n".
48 49 50 51 52 53 54 55
	  "-E <str> - A pithy sentence describing your experiment\n".
	  "-p <pid> - The project in which to create the experiment\n".
	  "-g <gid> - The group in which to create the experiment\n".
	  "-e <eid> - The experiment name (unique, alphanumeric, no blanks)\n".
	  "<nsfile> - NS file to parse for experiment.\n");
    exit(-1);
}

56
sub ParseArgs();
57 58
sub CheckCopyArgs();
sub CopyInArchive();
59 60
sub fatal($);

61
my $optlist = "iE:g:e:p:S:L:a:l:sfwqt:nzc:bxy:";
62
my $batchmode= 1;
63 64
my $frontend = 0;
my $waitmode = 0;
65
my $quiet    = 0;
66
my $linktest = 0;	# non-zero means level to run at.
67 68
my $zeemode  = 0;	# Hey, out of options.
my $zeeopt   = "";	# To pass along.
69
my $savestate= 0;
70 71
my $template_mode  = 0;	# New stuff; experiment templates.
my $instance_idx   = 0;	# New stuff; experiment templates.
72 73 74 75 76 77 78 79 80 81
# All of these are for experiment dup and branch. Really mucks things up.
# These globals are set when we parse the -c argument, but used later
my $copybranch = 0;	# A branch instead of a duplicate
my $copyfrom;		# Copy from where, archive or current experiment.
my $copyarg;            # The -c argument.
my $copyidx;            # The index of the experiment copied.
my $copypid;		# The pid of the experiment copied.
my $copyeid;		# The eid of the experiment copied.
my $copytag;		# The archive tag to us.
my $copydir;		# Directory extracted from archive, to delete.
82 83 84 85 86

#
# Configure variables
#
my $TB       = "@prefix@";
87
my $PROJROOT = "/proj";
88
my $EVENTSYS = @EVENTSYS@;
89 90
my $TBOPS    = "@TBOPSEMAIL@";
my $TBLOGS   = "@TBLOGSEMAIL@";
91 92
my $TBDOCBASE = "@TBDOCBASE@";
my $TBBASE   = "@TBBASE@";
93
my $CONTROL  = "@USERNODE@";
94

95 96 97 98 99 100
#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
Kevin Atkinson's avatar
Kevin Atkinson committed
101
use libtblog;
102
use libArchive;
103

104 105 106 107 108
my $parser      = "$TB/libexec/parse-ns";
my $mkexpdir    = "$TB/libexec/mkexpdir";
my $checkquota  = "$TB/sbin/checkquota";
my $tbbindir    = "$TB/bin/";
my $RSYNC	= "/usr/local/bin/rsync";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
109
my $errorstat=-1;
110 111
my $user_name;
my $user_email;
112
my $dbuid;
113

114 115 116 117 118 119 120
# 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;
121 122 123 124 125 126

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

127 128 129 130 131 132 133
#
# 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);

134 135
#
# Untaint the path
136
#
137 138
# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
139 140
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

141 142 143 144 145
my $eid;
my $pid;
my $gid;
my $description;
my $tempnsfile;
146 147 148
my $swappable    = 1;
my $noswap_reason;
my $idleswap     = 1;
149
my $idleswaptime = 60 * TBGetSiteVar("idle/threshold");
150
my $noidleswap_reason;
151
my $autoswap     = 0;
152
my $autoswaptime = 10 * 60;
153 154 155
my $idleignore   = 0;
my $priority     = TB_EXPTPRIORITY_LOW;
my $exptstate    = EXPTSTATE_NEW();
156
my $batchstate   = BATCHSTATE_UNLOCKED();
157 158
my $now          = localtime();
my $committed    = 0;
159

160
#
161
# Verify user and get his DB uid.
162
#
163
if (! UNIX2DBUID($UID, \$dbuid)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
164
    tbdie("You do not exist in the Emulab Database!");
165 166
}

167 168 169 170
#
# Get email info for user.
#
if (! UserDBInfo($dbuid, \$user_name, \$user_email)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
171
    tbdie("Cannot determine your name and email address.");
172 173
}

174 175 176 177 178
#
# 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) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
179
    tberror("You are over your disk quota on $CONTROL; please cleanup!");
180 181 182
    exit(1);
}

183
#
184
# Parse command arguments.
185
#
186
ParseArgs();
187
CheckCopyArgs();
188 189 190

#
# Sanity check them.
191
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
192 193 194
usage()
    if (!defined($pid) || !defined($eid));
usage()
195
    if (defined($tempnsfile) && defined($copyarg));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
196

197 198 199
if (!defined($gid)) {
    $gid = $pid;
}
200
if (!defined($description)) {
201 202
    $description = "'Created by $dbuid'";
}
203
if (! $swappable && (!defined($noswap_reason) || $noswap_reason eq "")) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
204
    tbdie("Must provide a reason with -S option (not swappable reason)!");
205
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
206
if (! $idleswap && (!defined($noidleswap_reason) || $noidleswap_reason eq "")){
Kevin Atkinson's avatar
 
Kevin Atkinson committed
207
    tbdie("Must provide a reason with -L option (no idleswap reason)!");
208
}
209
if (!defined($tempnsfile) && !defined($copyarg) && !TBAdmin($dbuid)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
210
    tbdie("Only admins can create experiments with no NS file");
211
}
212 213
my $nsfile  = "$eid.ns";
my $repfile = "$eid.report";
214

215 216 217 218 219 220
# Defaults for the DB and for the email message. 
$noswap_reason = "'None Given'"
    if (!defined($noswap_reason));
$noidleswap_reason = "'None Given'"
    if (!defined($noidleswap_reason));

221
#
222
# Make sure UID is allowed to create experiments in this project.
223
#
224
if (! TBProjAccessCheck($dbuid, $pid, $gid, TB_PROJECT_CREATEEXPT)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
225
    die("You do not have permission to create experiments in $pid/$gid");
226 227
}

228 229 230
if (defined($copyarg)) {
    # This will be handled below.
    ;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
231 232 233
}
elsif (!defined($tempnsfile)) {
    # If no NS file, then override swap/idle stuff. 
234 235 236
    $swappable     = 0;
    $idleswap      = 0;
}
237
elsif (! -f $tempnsfile || ! -r $tempnsfile || -z $tempnsfile) {
238
    # Exit so that user sees the error, not us.
Kevin Atkinson's avatar
 
Kevin Atkinson committed
239
    tberror("$tempnsfile does not exist or is not a readable file!");
240 241
    exit(1);
}
242

243 244 245 246
#
# Batch jobs get a shorter idle time
#
my $swaptime = $idleswaptime;
247
if ($batchmode && TBSiteVarExists("idle/batch_threshold")) {
248 249 250 251 252 253
    my $batchidleswaptime = TBGetSiteVar("idle/batch_threshold");
    if ($swaptime > $batchidleswaptime) {
	$swaptime = $batchidleswaptime;
    }
}

254
#
255 256
# Grab me a secret key for accessing tar/rpm files via the web interface.
# Grab another secret key for the event system HMACs.
257
#
258 259
my $webkey   = TBGenSecretKey();
my $eventkey = TBGenSecretKey();
260

261 262 263 264 265 266 267 268 269
#
# In wait mode, block SIGINT until we spin off the background process.
#
if ($waitmode) {
    $SIG{QUIT} = 'IGNORE';
    $SIG{TERM} = 'IGNORE';
    $SIG{INT}  = 'IGNORE';
}

270
#
271 272
# Create an experiment record. The pid/eid has to be unique, so lock the
# table for the check/insert.
273
#
274 275 276 277
DBQueryFatal("lock tables experiments write, ".
	     "            experiment_stats write, ".
	     "            experiment_resources write, ".
	     "            testbed_stats read");
278

279 280 281
$query_result =
    DBQueryFatal("SELECT pid,eid FROM experiments ".
		 "WHERE eid='$eid' and pid='$pid'");
282

283 284
if ($query_result->numrows) {
    DBQueryWarn("unlock tables");
Kevin Atkinson's avatar
 
Kevin Atkinson committed
285
    tbdie("Experiment $eid in project $pid already exists!");
286
}
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
#
# Grab the next highest index to use. We used to use an auto_increment
# field in the table, but if the DB is ever "dropped" and recreated,
# it will reuse indicies that are crossed referenced in the other two
# tables.
#
$query_result =
    DBQueryFatal("select MAX(exptidx) from experiment_stats");
my ($exptidx) = $query_result->fetchrow_array();
$exptidx++;

#
# Lets be really sure!
#
foreach my $table ("experiments", "experiment_stats", "experiment_resources",
		   "testbed_stats") {

    my $slot = (($table eq "experiments") ? "idx" : "exptidx");
	
    $query_result =
	DBQueryFatal("select * from $table where ${slot}=$exptidx");
    
    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
Kevin Atkinson's avatar
 
Kevin Atkinson committed
312
	tbdie("Experiment index $exptidx exists in $table; this is bad!");
313 314 315
    }
}

316
#
317 318
# Insert the record. This reserves the pid/eid for us. If its a batchmode
# experiment, we will update the record later so that the batch daemon
319 320
# will recognize it. We insert the record as locked and ACTIVATING so that
# no one can mess with the experiment until later. 
321
#
322
if (! DBQueryWarn("INSERT INTO experiments ".
323
		  "(idx, eid, pid, gid, expt_created, expt_name,".
324
		  " expt_head_uid,expt_swap_uid, state, priority, swappable,".
325
		  " idleswap, idleswap_timeout, autoswap, autoswap_timeout,".
326
		  " idle_ignore, keyhash, expt_locked, eventkey,".
327
		  " noswap_reason, noidleswap_reason, batchmode, ".
328
		  " batchstate, linktest_level, savedisk, instance_idx) ".
329
		  "VALUES ($exptidx, '$eid', '$pid', '$gid', now(), ".
330
		  "$description,'$dbuid', '$dbuid', '$exptstate', $priority, ".
331
		  "$swappable, $idleswap, '$swaptime', $autoswap, ".
332
		  "'$autoswaptime', $idleignore, '$webkey', ".
333
		  "now(), '$eventkey', $noswap_reason, ".
334
		  "$noidleswap_reason, $batchmode, '$batchstate', ".
335
		  "$linktest, $savestate, $instance_idx)")) {
336
    DBQueryWarn("unlock tables");
Kevin Atkinson's avatar
 
Kevin Atkinson committed
337
    tbdie("DB error inserting experiment record for $pid/$eid!");
338 339
}

340
#
341
# Create an experiment_resources record for the above record.
342
#
343 344 345 346 347 348
$query_result =
    DBQueryWarn("insert into experiment_resources (tstamp, exptidx) ".
		"values (now(), $exptidx)");

if (!$query_result) {
    DBQueryWarn("delete from experiments where pid='$pid' and eid='$eid'");
349
    DBQueryWarn("unlock tables");
Kevin Atkinson's avatar
 
Kevin Atkinson committed
350
    tbdie("DB error inserting experiment resources record for $pid/$eid!");
351
}
352
my $rsrcidx = $query_result->insertid;
353 354 355

#
# Now create an experiment_stats record to match.
356
#
357
if (! DBQueryWarn("insert into experiment_stats ".
358 359 360 361 362
		  "(eid, pid, creator, gid, created, batch, exptidx, rsrcidx) ".
		  "values('$eid', '$pid', '$dbuid', '$gid', now(), ".
		  "$batchmode, $exptidx, $rsrcidx)")) {
    DBQueryWarn("delete from experiments where pid='$pid' and eid='$eid'");
    DBQueryWarn("delete from experiment_resources where idx=$rsrcidx");
363
    DBQueryWarn("unlock tables");
Kevin Atkinson's avatar
 
Kevin Atkinson committed
364
    tbdie("DB error inserting experiment stats record for $pid/$eid!");
365 366 367 368 369 370
}

if (! DBQueryWarn("unlock tables")) {
    DBQueryWarn("delete from experiments where pid='$pid' and eid='$eid'");
    DBQueryWarn("delete from experiment_resources where idx=$rsrcidx");
    DBQueryWarn("delete from experiment_stats where exptidx=$exptidx");
Kevin Atkinson's avatar
 
Kevin Atkinson committed
371
    tbdie("DB error unlocking tables!");
372 373
}

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

Kevin Atkinson's avatar
Kevin Atkinson committed
380 381 382 383 384
#
# Set error reporting info
# 
tblog_set_info($pid,$eid,$UID);

385
#
386
# Create a directory structure for the experiment.
387
#
388
if (system("$mkexpdir $pid $gid $eid") != 0) {
389 390 391 392
    if (($? >> 8) == EDQUOT()) {
	# Obey exit status protocol for web page; User should see this.
	$errorstat = 1;
    }
393
    fatal("$mkexpdir failed");
394 395
}

396 397 398 399 400 401 402 403 404 405
#
# Grab the working directory path, and thats where we work.
# The user's experiment directory is off in /proj space.
#
my $workdir = TBExptWorkDir($pid, $eid);
my $userdir = TBExptUserDir($pid, $eid);

chdir("$workdir") or
    fatal("Could not chdir to $workdir: $!");

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
#
# Create a new archive, which might actually be a branch of an existing one
# when doing an experiment branch (fork).
#
if ($copybranch) {
    # Currently, support branching from existing experiment only.
    fatal("Could not create experiment archive!")
	if (libArchive::TBForkExperimentArchive($pid, $eid,
						$copypid,
						$copyeid, $copytag) < 0);
}
elsif (libArchive::TBCreateExperimentArchive($pid, $eid) < 0) {
    fatal("Could not create experiment archive!");
}

#
# Okay, if copying/branching an experiment, we have to go find the
# NS file, extracting the special (currently by convention) archive
# directory into the new experiment. This will set the tempnsfile
# variable needed below.
#
if ($copyarg) {
    CopyInArchive();
}

431 432 433 434 435 436 437 438 439 440
#
# It would be nice to check for overquota during the rest of this
# setup, but thats going to be a pain. Besides, its very unlikely
# that someone goes overquota at this point. Typically, the person
# is already overquota at this point. If this turns out to be wrong,
# it will be easy to add a little test to make sure there is at least
# a reasonable amount of room to proceed (create temp file and stick
# some data in it).
# 

441 442 443 444 445 446 447 448 449 450
#
# Dump the eventkey into a file in the experiment directory. 
#
if ($EVENTSYS) {
    open(KEY, ">" . TBDB_EVENTKEY($pid, $eid)) or
	fatal("Could not create eventkey file: $!");
    print KEY $eventkey;
    close(KEY);
}

451 452 453 454 455 456
# And dump the web key too.
open(KEY, ">" . TBDB_WEBKEY($pid, $eid)) or
    fatal("Could not create webkey file: $!");
print KEY $webkey;
close(KEY);

457
#
458 459 460
# If no NS file, we are done. We must unlock it and reset its state
# appropriately. We leave the experiment in the "new" state so that
# the user is forced to do a modify first (to give it a topology). 
461
#
462
if (!defined($tempnsfile)) {
463
    TBUnLockExp($pid, $eid, EXPTSTATE_NEW());
464 465
    exit(0);
}
466

467
#
468
# Now we can get the NS file!
469
#
470
if (system("/bin/cp", "$tempnsfile", "$nsfile")) {
471
    fatal("Could not copy $tempnsfile to $workdir/$nsfile");
472
}
473
chmod(0664, "$nsfile");
474

475
#
476 477
# Run parse in impotent mode on the NS file.  This has no effect but
# will display any errors.
478
#
479
if (system("$parser -n $zeeopt $pid $gid $eid $nsfile") != 0) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
480 481
    # Obey exit status protocol for web page.
    $errorstat = 1;
482
    fatal("NS Parse failed!");
483 484
}

485 486 487
#
# Gather statistics; start the clock ticking.
#
488
if ($frontend || $batchmode) {
489 490 491 492 493 494 495 496
    GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_PRELOAD, 0,
		    TBDB_STATS_FLAGS_START);
}
else {
    GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_START, 0,
		    TBDB_STATS_FLAGS_START);
}

497 498 499
goto skiplog
    if ($template_mode);

500 501 502 503 504 505 506 507 508 509 510 511
#
# The rest of this goes into the background so that the user sees
# immediate response. We will send email later when the experiment
# is ready. In waitmode, we hold the parent waiting so that the user
# can script it. Must protect against async (^C) termination though.
#
my $logname = TBExptCreateLogFile($pid, $eid, "startexp");
TBExptSetLogFile($pid, $eid, $logname);
TBExptOpenLogFile($pid, $eid);
    
if (my $childpid = TBBackGround($logname)) {
    #
512 513
    # Parent exits normally, unless in waitmode. We have to set
    # justexit to make sure the END block below does not run.
514
    #
515 516
    $justexit = 1;
    
517 518 519
    if (!$waitmode) {
	print("Experiment $pid/$eid is now configuring\n".
 	      "You will be notified via email when the experiment is ".
520 521
	      "ready to use\n")
	    if (! $quiet);
522 523
	exit(0);
    }
524
    print("Waiting for " . ($batchmode ? "batch " : "") . "experiment $eid ".
525 526 527 528 529 530 531
	  "to finish " . ($frontend ? "preloading." : "swapping in.") . "\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");
    }
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

    # 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{QUIT} = 'DEFAULT';
    $SIG{INT}  = 'DEFAULT';

    #
    # Wait until child exits or until user gets bored and types ^C.
    #
    waitpid($childpid, 0);

549 550
    print("Done. Exited with status: $?\n")
	if (! $quiet);
Kevin Atkinson's avatar
 
Kevin Atkinson committed
551 552 553 554 555 556 557 558 559

    my $exit_code = $? >> 8;
    
    if ($exit_code != 0) {
	my $d = tblog_lookup_error();
	print tblog_format_error($d);
    }
    
    exit $exit_code;
560
}
561
TBdbfork();
562
skiplog:
563 564 565 566 567 568 569 570 571 572 573 574

# We are committed now. Affects how fatal() operates.
$committed = 1;

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

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
#
# We need to catch TERM cause sometimes shit happens and we have to kill
# an experiment setup 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';

595 596
#
# The guts of starting an experiment!
597
#
598 599
# A batch experiment is essentially preloaded (frontend mode) and then
# dropped into the batch queue, unless the user requested only preload.
600 601
#

602
#
603
# Run the various scripts. We want to propagate the error from tbprerun
604 605
# and tbrun back out, hence the bogus looking errorstat variable.
#
606 607
SetExpState($pid, $eid, EXPTSTATE_PRERUN)
    or fatal("Failed to set experiment state to " . EXPTSTATE_PRERUN());
608 609 610 611
$zeeopt = "-z"
    if ($zeemode);
print "Running 'tbprerun $zeeopt $pid $eid $nsfile'\n";
if (system("$tbbindir/tbprerun $zeeopt $pid $eid $nsfile") != 0) {
612
    $errorstat = $? >> 8;
613
    fatal("tbprerun failed!");
614
}
615 616
SetExpState($pid, $eid, EXPTSTATE_SWAPPED)
    or fatal("Failed to set experiment state to " . EXPTSTATE_SWAPPED());
617 618 619 620

#
# If not in frontend mode (preload only) continue to swapping exp in.
# 
621
if (! ($frontend || $batchmode)) {
622 623
    SetExpState($pid, $eid, EXPTSTATE_ACTIVATING)
	or fatal("Failed to set experiment state to ". EXPTSTATE_ACTIVATING());
624 625 626 627

    print "Running 'tbswap in $pid $eid'\n";
    if (system("$tbbindir/tbswap in $pid $eid") != 0) {
	$errorstat = $? >> 8;
628
	fatal("tbswap in failed!");
629
    }
630 631
    SetExpState($pid, $eid, EXPTSTATE_ACTIVE)
	or fatal("Failed to set experiment state to " . EXPTSTATE_ACTIVE());
632 633 634 635 636

    #
    # Look for the unsual case of more than 2 nodes and no vlans. Send a
    # warning message.
    #
637
    my @localnodes = ExpNodes($pid, $eid, 1, 0);
638
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
639
    if (@localnodes && scalar(@localnodes) > 2) {
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	my $vlans_result =
	    DBQueryFatal("select pid from virt_lans ".
			 "where pid='$pid' and eid='$eid'");
    
	if (!$vlans_result->numrows) {
	    SENDMAIL("$user_name <$user_email>",
		     "WARNING: Experiment Configuration: $pid/$eid",
		     "This experiment has zero network links defined.\n".
		     "Please check your NS file to verify this is what you ".
		     "want!\n",
		     "$user_name <$user_email>",
		     "Cc: $TBOPS", ($nsfile));
	}
    }
}

# We append this report in the email message below.
if (system("$tbbindir/tbreport -b $pid $eid 2>&1 > $repfile") != 0) {
658
    fatal("tbreport failed!");
659 660
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
661 662 663 664 665
# Latest log is always called the same thing.
if (defined($logname)) {
    system("cp -fp $logname $workdir/" . EXPTLOGNAME());
}

666 667 668 669 670 671 672 673 674 675 676
#
# Try to copy off the files for testbed information gathering.
#
TBSaveExpLogFiles($pid, $eid);

#
# Make a copy of the work dir in the user visible space so the user
# can see the log files.
#
system("cp -Rfp $workdir/ $userdir/tbdata");

Leigh B. Stoller's avatar
Leigh B. Stoller committed
677 678 679 680 681
# Now add that copy to the archive. 
if (defined($logname)) {
    libArchive::TBExperimentArchiveAddFile($pid, $eid,
					   "$userdir/tbdata/" . EXPTLOGNAME());
}
682 683 684 685 686 687 688 689 690
libArchive::TBExperimentArchiveAddFile($pid, $eid, "$userdir/tbdata/$repfile");

#
# Make a copy of the NS file where we can get at it easily. Then add it.
#
system("cp -p $workdir/$nsfile $userdir/archive/$nsfile");
libArchive::TBExperimentArchiveAddFile($pid, $eid,
				       "$userdir/archive/$nsfile") == 0 or
    fatal("Failed to add $userdir/archive/$nsfile to the archive!");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
691

692 693 694
#
# Do a SavePoint on the experiment files.
#
695
print "Doing a savepoint on the experiment archive ...\n";
696 697 698 699
if (libArchive::TBExperimentArchiveSavePoint($pid, $eid, "startexp") < 0) {
    fatal("Failed to do a savepoint on the experiment archive!");
}

700 701 702 703 704 705 706 707 708 709
#
# If this is a branch, then do a commit. Otherwise, the archive looks
# wrong cause its a branch from the original and shows all those files.
#
if ($copybranch) {
    print "Doing a commit on the experiment archive ...\n";
    libArchive::TBCommitExperimentArchive($pid, $eid, "branch_merge") == 0 or
	fatal("Failed to commit experiment archive!");
}

710 711 712 713 714 715 716 717 718 719
#
# Gather statistics.
#
if ($frontend || $batchmode) {
    GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_PRELOAD, 0);
}
else {
    GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_START, 0);
}

720 721 722 723 724 725 726 727 728 729
#
# Old accounting info (still used in web interface and autoswap).
#
TBSetExpSwapTime($pid, $eid);

#
# Set the swapper uid on success only, and *after* gathering swap stats!
#
TBExptSetSwapUID($pid, $eid, $dbuid);

730 731 732
#
# Close up the log file so the webpage stops.
#
733 734 735 736
if (!$template_mode) {
    print "Experiment $pid/$eid has been successfully created!\n";
    TBExptCloseLogFile($pid, $eid);
}
737 738 739 740

#
# Must unlock and drop batch experiments into the queue before exit.
#
741
if ($batchmode && !$frontend) {
742 743 744 745 746 747 748 749 750 751 752 753
    TBUnLockExp($pid, $eid, EXPTSTATE_QUEUED());
}
else {
    TBUnLockExp($pid, $eid);
}

#
# Clear the cancel flag now that the operation is complete. Must be
# done after we change the experiment state (above).
#
TBSetCancelFlag($pid, $eid, EXPTCANCEL_CLEAR());

754 755 756 757 758 759
#
# In template_mode we are done; the caller finishes up.
#
exit(0)
    if ($template_mode);

760 761 762
#
# Dump the report file and the log file to the user via email. 
#
763
# Yuck, we want the created time that mysql assigned at the insertion.
764 765
#
$query_result =
766
    DBQueryFatal("select expt_created from experiments ".
767
		 "where pid='$pid' and eid='$eid'");
768
my ($expt_created) = $query_result->fetchrow_array();
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
my $message;

if ($frontend) {
    $message =
	"Your experiment `$eid' in project `$pid' has been created.\n" .
	"You can check the web interface to see if it looks the way\n" .
	"you expected it to. If so, you may swap the experiment in,\n" .
	"or terminate it, at any time.\n" .
        "\n";
}
else {
    $message =
	"Your experiment `$eid' in project `$pid' has been started.\n" .
	"Here is the experiment summary detailing the nodes that were\n" .
	"allocated to you. You may use the `Qualified Name' to log on\n" .
	"to your nodes. See /etc/hosts on your nodes (when running\n" .
	"FreeBSD, Linux, or NetBSD) for the IP mapping on each node.\n" .
        "\n";
787
}
788 789 790 791 792 793 794 795
$message .=
    "User:        $user_name\n" .
    "EID:         $eid\n" .
    "PID:         $pid\n" .
    "GID:         $gid\n" .
    "Description: $description\n" .
    "Swappable:   " . ($swappable ? "Yes\n" :
		                    "No  (Reason: $noswap_reason)\n") .
796
    "Idle-Swap:   " . ($idleswap  ? "Yes, at " . $idleswaptime/60.0 . " hours\n":
797
		                    "No  (Reason: $noidleswap_reason)\n") .
798
    "Auto-Swap:   " . ($autoswap  ? "Yes, at " . $autoswaptime/60.0 . " hours\n":
799 800 801 802 803 804 805 806 807 808 809 810 811 812
		                    "No\n") .
    "Created:     $expt_created\n".
    "Directory:   $userdir\n".
    "\n".
    "Appended at the end is the output of the experiment setup. If you\n" .
    "have any questions or comments, please include the output below\n" .
    "in your message to $TBOPS";

SENDMAIL("$user_name <$user_email>",
	 "New Experiment " . (($frontend == 0) ? "Started" : "Created") .
	 ": $pid/$eid",
	 $message,
	 "$user_name <$user_email>",
	 "Bcc: $TBLOGS",
813 814
	 ($repfile, $logname, $nsfile))
    if (!$zeemode);
815 816

# Done!
817
exit(0);
818

819 820 821
#
#
#
822
sub cleanup()
823
{
824
    #
825 826 827 828 829 830
    # Failed early (say, in parsing). No point in keeping any of the
    # stats or resource records. Just a waste of space since the
    # testbed_stats log indicates there was a failure and why (sorta,
    # via the exit code).
    # 
    if (!$committed) {
831 832 833
	# Completely remove all trace of the archive.
        libArchive::TBDestroyExperimentArchive($pid, $eid);

834
	#
835
	# Clear the experiment record and cleanup directories
836 837
	#
	TBExptDestroy($pid, $eid);
838 839 840 841 842

	#
	# Now we can clean up the stats records. 
	#
	DBQueryWarn("DELETE from experiment_resources ".
843
		    "WHERE idx=$rsrcidx");
844 845 846 847 848 849 850 851
	
	DBQueryWarn("DELETE from testbed_stats ".
		    "WHERE exptidx=$exptidx");

	# This must be last cause it provides the unique exptidx above.
	DBQueryWarn("DELETE from experiment_stats ".
		    "WHERE eid='$eid' and pid='$pid' and exptidx=$exptidx");

852
	return;
853
    }
854

855 856 857 858 859 860 861 862 863
    #
    # Gather statistics.
    #
    if ($frontend) {
	GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_PRELOAD, $errorstat);
    }
    else {
	GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_START, $errorstat);
    }
864

865 866 867 868
    #
    # Must clean up the experiment if it made it our of NEW state.
    #
    my $estate = ExpState($pid, $eid);
869 870 871 872 873 874 875 876
    if ($estate ne EXPTSTATE_NEW) {
	#
	# We do not know exactly where things stopped, so if the
	# experiment was activating when the signal was delivered,
	# run tbswap on it. 
	# 
	if ($estate eq EXPTSTATE_ACTIVE ||
	    ($estate eq EXPTSTATE_ACTIVATING && $signaled)) {
877
	    print "Running 'tbswap out -force $pid $eid'\n";
878
	    if (system("$tbbindir/tbswap out -force $pid $eid") != 0) {
879 880
		print "tbswap out failed!\n";
	    }
881
	    SetExpState($pid, $eid, EXPTSTATE_SWAPPED);
882
	}
883
	
884 885 886
	print "Running 'tbend -force $pid $eid'\n";
	if (system("$tbbindir/tbend -force $pid $eid") != 0) {
	    print "tbend failed!\n";
887 888
	}
    }
889
    SetExpState($pid, $eid, EXPTSTATE_TERMINATED);
890

891
    #
892 893 894 895 896 897 898
    # Okay, we *are* going to terminate the experiment.
    # 
    GatherSwapStats($pid, $eid, $dbuid, TBDB_STATS_TERMINATE, 0);

    # Clear the logfile so the webpage stops. 
    TBExptClearLogFile($pid, $eid);

Kevin Atkinson's avatar
 
Kevin Atkinson committed
899 900 901 902 903
    #
    # Figure out the error if possible
    #
    my $error_data = tblog_find_error();

904 905 906
    #
    # Send a message to the testbed list. 
    #
Kevin Atkinson's avatar
 
Kevin Atkinson committed
907 908 909 910 911 912 913
    tblog_email_error($error_data,
		      "$user_name <$user_email>",
		      "Config Failure", "$pid/$eid",
		      "$user_name <$user_email>",
		      "",
		      "Cc: $TBOPS",
		      ($logname, "assign.log", "wanassign.log", $nsfile));
914

915
    #
916 917 918 919
    # Back up the work dir for post-mortem debugging. 
    #
    system("/bin/rm -rf  ${workdir}-failed");
    system("/bin/mv -f   $workdir ${workdir}-failed");
920

921 922 923 924
    #
    # Clear the record and cleanup.
    # 
    TBExptDestroy($pid, $eid);    
925 926 927
}

#
928 929
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
930
#
931
sub ParseArgs()
932
{
933 934 935 936
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
937

938
    if (@ARGV > 1) {
939 940
	usage();
    }
941 942
    if (@ARGV == 1) {
	$tempnsfile = $ARGV[0];
943

944
	# Note different taint check (allow /).
945
	if ($tempnsfile =~ /^([-\w\.\/]+)$/) {
946 947 948
	    $tempnsfile = $1;
	}
	else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
949
	    tbdie("Bad data in nsfile: $tempnsfile");
950
	}
951

952 953 954 955 956 957 958 959 960 961
	#
	# 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;
	}
	else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
962
	    tbdie("Bad data returned by realpath: $translated");
963 964 965 966 967 968 969 970 971
	}

	#
	# 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 (! ($tempnsfile =~ /^\/tmp\/[-\w]+-\d+\.nsfile/) &&
972
	    ! ($tempnsfile =~ /^\/tmp\/\d+\.ns/) &&
973 974 975 976
	    ! ($tempnsfile =~ /^\/var\/tmp\/php\w+/) &&
	    ! ($tempnsfile =~ /^\/proj/) &&
	    ! ($tempnsfile =~ /^\/groups/) &&
	    ! ($tempnsfile =~ /^\/users/)) {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
977
	    tberror("$tempnsfile does not resolve to an allowed directory!");
978 979 980 981 982
	    # Note positive status; so error goes to user not tbops.
	    exit(1);
	}
    }
    
983
    if (defined($options{"i"})) {
984
	$batchmode = 0;
985
    }
986 987 988
    if (defined($options{"f"})) {
	$frontend = 1;
    }
989 990 991
    if (defined($options{"q"})) {
	$quiet = 1;
    }
992 993 994 995
    if (defined($options{"z"})) {
	$zeemode = 1;
	$zeeopt  = "-p";
    }
996 997 998 999
    # This option should not be exported via the XMLRPC server. 
    if (defined($options{"n"})) {
	$idleignore = 1;
    }
1000

1001 1002 1003 1004
    if (defined($options{"s"})) {
	$savestate = 1;
    }

Leigh B. Stoller's avatar
Leigh B. Stoller committed
1005 1006 1007 1008 1009
    #
    # Clone an experiment, either an existing experiment or an old one
    # (using the archive). 
    #
    if (defined($options{"c"})) {
1010
	$copyarg = $options{"c"};
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1011

1012 1013 1014 1015 1016 1017 1018
	if (! (($copyarg =~ /^([-\w]+),([-\w]+)(?::[-\w]*)?$/) ||
	       ($copyarg =~ /^(\d+)(?::[-\w]*)?$/))) {
	    tbdie("Bad data in argument: $copyarg");
	}
	# This option only makes sense with -c option.
	if (defined($options{"b"})) {
	    $copybranch = 1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1019 1020 1021
	}
    }

1022 1023 1024
    #
    # pid,eid,gid get passed along as shell commands args; must taint check.
    # 
1025 1026
    if (defined($options{"p"})) {
	$pid = $options{"p"};
1027

1028
	if ($pid =~ /^([-\w]+)$/) {
1029 1030
	    $pid = $1;
	}
1031
	else {
Kevin Atkinson's avatar
 
Kevin Atkinson committed
1032
	    tbdie("Bad data in argument: $pid.");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1033
	}
1034 1035 1036 1037
    }
    if (defined($options{"e"})) {
	$eid = $options{"e"};

1038
	if ($eid =~ /^([-\w]+)$/) {