template_create.in 12 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 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
use Getopt::Std;
use POSIX qw(isatty setsid);
use POSIX qw(strftime);
use Errno qw(EDQUOT);

#
# 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: create_expt_template [-q] [-w] [-E description]\n".
	  "                [-g gid] <pid> <tid> <input file>\n".
	  "switches and arguments:\n".
	  "-w       - wait for template to be created.\n".
	  "-q       - be less chatty\n".
	  "-E <str> - A pithy sentence describing the template\n".
	  "-g <gid> - The group in which to create the experiment\n".
	  "<pid>    - The project in which to create the experiment\n".
37
	  "<tid>    - The template name (alphanumeric, no blanks)\n".
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	  "<input>  - Input file for experiment.\n");
    exit(-1);
}
my $optlist	 = "qwE:g:m:";
my $quiet        = 0;
my $waitmode     = 0;
my $description  = "";
my $modify       = 0;
my $pid;
my $tid;
my $gid;
my $inputfile;
# For modify.
my $parent_guid;
my $parent_vers;
53
my $parent_template;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

#
# 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@";

# Locals
my $user_name;
my $user_email;
70
my $template;
71 72
my $dbuid;
my $guid;
73 74
my $vers;
my $eid;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
75
my $archive_idx = 0;
76
# For the END block below.
77
my $cleaning    = 0;
78
my $exptcreated = 0;
79
my $justexit    = 1;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

# Programs we need
my $checkquota  = "$TB/sbin/checkquota";
my $batchexp    = "$TB/bin/batchexp";
my $endexp      = "$TB/bin/endexp";
my $makegraph   = "$TB/bin/template_graph";

# Protos
sub ParseArgs();
sub fatal($$);

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use libtblog;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
98
use libArchive;
99
use Template;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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

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

#
# 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';
}

#
# Make sure UID is allowed to create experiments in this project.
#
if (! TBProjAccessCheck($dbuid, $pid, $gid, TB_PROJECT_CREATEEXPT)) {
    tbdie("You do not have permission to create experiments in $pid/$gid");
}

#
# On modify, must check access to the parent template.
#
if ($modify) {
169 170 171
    $parent_template = Template->Lookup($parent_guid, $parent_vers);

    if (!defined($parent_template)) {
172 173
	tbdie("Experiment template $parent_guid/$parent_vers does not exist!");
    }
174 175

    if (!$parent_template->AccessCheck($dbuid, TB_EXPT_READINFO)) {
176 177 178 179 180 181
	tbdie("You do not have permission to modify experiment template ".
	      "$parent_guid/$parent_vers");
    }
}

#
182
# Create a template record. 
183 184 185 186 187 188 189 190 191 192 193 194 195 196
#
my %args = ();

if ($modify) {
    $args{'parent_guid'} = $parent_guid;
    $args{'parent_vers'} = $parent_vers;
}
$args{'pid'}         = $pid;
$args{'gid'}         = $gid;
$args{'tid'}         = $tid;
$args{'uid'}         = $dbuid;
$args{'description'} = DBQuoteSpecial($description);
$args{'description'} =~ s/^\'(.*)\'$/$1/;

197
if (! ($template = Template->Create(\%args))) {
198 199 200
    tbdie("Could not create a new template record!");
}

201 202 203 204 205 206 207 208 209
#
# At this point, we need to force a cleanup no matter how we exit.
# See the END block below.
#
$justexit = 0;

#
# The description is versioned metadata the user can modify.
#
210
$template->NewMetadata("description", $description, $dbuid) == 0
211 212 213 214 215
    or fatal(-1, "Failed to insert metadata record for description");

#
# The TID is versioned metadata the user can modify.
#
216
$template->NewMetadata("TID", $tid, $dbuid) == 0
217 218 219
    or fatal(-1, "Failed to insert metadata record for description");

#
220
# Copy the rest of the metadata from parent to child
221 222
#
if ($modify) {
223 224
    $template->CopyMetadata($parent_template, $dbuid) == 0
	or fatal(-1, "Failed to copy metadata records");
225 226
}

227 228 229 230 231
# Grab stuff we need out of the template.
$guid = $template->guid();
$vers = $template->vers();
$eid  = $template->eid();

232
# Now invoke batchexp to preload the experiment. Note special -x option.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
233
system("$batchexp ". 
234 235
       "-x " . ($modify ? $parent_template->eid() : "-") . " " .
       "-q -i -f -E 'Experiment Template Preload $guid/$vers' ".
236 237 238 239 240 241 242
       "-p $pid -e $eid $inputfile");
fatal($? >> 8, "Oops")
    if ($?);

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

243
# Input files are kept in the DB, with the template.
244 245 246
fatal(-1, "Could not add NS file to template store")
    if ($template->AddInputFile($inputfile) < 0);

247
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
# Grab archive index for new templates.
#
if (!$modify) {
    libArchive::TBExperimentArchiveInfo($pid, $eid, \$archive_idx, undef)
	>= 0 or fatal(-1, "Could not get archive index for new template!");

    # Do a commit point on the template archive since it does not actually
    # change after it is created (instances are branches).
    libArchive::TBCommitExperimentArchive($pid, $eid, "TemplateCreate")
	>= 0 or fatal(-1, "Failed to commit experiment archive!");
}
else {
    #
    # Grab the archive index for the parent; the archive is shared.
    #
    libArchive::TBExperimentArchiveInfo($pid,
264
					$parent_template->eid(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
265 266 267 268 269 270
					\$archive_idx, undef)
	>= 0 or fatal(-1, "Could not get archive index for parent!");
      
    # Do a commit point on the template archive since it does not actually
    # change after it is created (instances are branches).
    libArchive::TBCommitExperimentArchive($pid,
271
					  $parent_template->eid(),
Leigh B. Stoller's avatar
Leigh B. Stoller committed
272 273 274 275 276 277 278 279
					  "TemplateCreate")
	>= 0 or fatal(-1, "Failed to commit experiment archive!");
}

# And update the record.
%args = ();
$args{'archive_idx'} = $archive_idx;

280
$template->Update(\%args) == 0
Leigh B. Stoller's avatar
Leigh B. Stoller committed
281 282
    or fatal(-1, "Could not update template record!");

283 284 285 286 287 288
#
# Copy the virt_parameters table to the formal parameters table.
# I am not sure about the need for this table yet, but the only way
# to get the parameters is via the parser, but we want to save this
# info forever (after the underlying experiment is terminated).
#
289
my $query_result =
290 291 292 293 294 295 296
    DBQueryWarn("select name,value from virt_parameters ".
              "where pid='$pid' and eid='$eid'");

fatal(-1, "Could not get virt_parameters for $pid/$eid")
    if (! $query_result);

while (my ($name, $value) = $query_result->fetchrow_array()) {
297
    $template->NewFormalParameter($name, $value) == 0
298 299 300
	or fatal(-1, "Could not set formal parameter for $pid/$eid")
}
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
301
#
302 303 304 305 306 307
# Generate the graph for the template.
#
system("$makegraph $guid");
fatal(-1, "Error generating template graph.")
    if ($?);

308 309 310
# Web interface depends on this line. Bad; need another way to send
# back the newly generated guid/version.
print "Template $guid/$vers has been created\n";
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
exit(0);

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

    if (@ARGV < 2 || @ARGV > 3) {
	usage();
    }
    #
    # Pick up pid/tid first and untaint.
    #
    $pid = shift(@ARGV);

    if ($pid =~ /^([-\w]+)$/) {
	$pid = $1;
    }
    else {
	tbdie("Bad data in argument: $pid.");
    }
    if (! TBcheck_dbslot($pid, "projects", "newpid",
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	tbdie("Improper project name (id)!");
    }
    
    $tid = shift(@ARGV);

    if ($tid =~ /^([-\w]+)$/) {
	$tid = $1;
    }
    else {
	tbdie("Bad data in argument: $tid.");
    }
    if (! TBcheck_dbslot($tid, "experiments", "eid",
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	tbdie("Improper template name (id)!");
    }
    if (@ARGV) {
	$inputfile = $ARGV[0];

	# Note different taint check (allow /).
	if ($inputfile =~ /^([-\w\.\/]+)$/) {
	    $inputfile = $1;
	}
	else {
	    tbdie("Bad data in input 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+\.nsfile/) &&
	    ! ($inputfile =~ /^\/tmp\/\d+\.ns/) &&
	    ! ($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);
	}
    }
    #
    # Optional gid. Defaults to pid.
    #
    if (defined($options{"g"})) {
	$gid = $options{"g"};

	if ($gid =~ /^([-\w]+)$/) {
	    $gid = $1;
	}
	else {
	    tbdie("Bad data in argument: $gid.");
	}
    }
    else {
	$gid = $pid;
    }

    #
    # Parent pointer, for modify. We always create a new template point
    # it to the parent. 
    #
    if (defined($options{"m"})) {
	if ($options{"m"} =~ /^([\w]*)\/([\d]*)$/) {
	    $parent_guid = $1;
	    $parent_vers = $2;
	    $modify      = 1;
	}
	else {
	    tbdie("Bad data in argument: " . $options{"m"});
	}
    }

    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"};
    }
    else {
	$description = "Created by $dbuid";
    }

    if (defined($options{"q"})) {
	$quiet = 1;
    }
    if (defined($options{"w"})) {
	$waitmode = 1;
    }
}

#
# Cleanup the mess.
#
sub cleanup()
{
    if ($exptcreated) {
	my $exptidx;

	exit(-1)
	    if (!TBExptIDX($pid, $eid, \$exptidx));
		
	system("$endexp -x -q -w $pid $eid");
	exit(-1)
	    if ($?);

	# And delete all the other stuff?
    }
465 466
    $template->Delete()
	if (defined($template));
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
}

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

END {
    # Normal exit, nothing to do.
484
    if (!$? || $justexit) {
485 486 487 488 489 490 491 492 493
	return;
    }
    my $saved_exitcode = $?;
    
    if ($cleaning) {
	#
	# We are screwed; a recursive error. Someone will have to clean
	# up by hand. 
	#
494
	SENDMAIL($TBOPS, 
495 496 497 498 499 500 501 502 503 504
		 "Template Creation Failure: $pid/$tid",
		 "Recursive error in cleanup! This is very bad.");
	$? = $saved_exitcode;
	return;
    }
    $cleaning = 1;
    cleanup();
    $? = $saved_exitcode;
}