create_instance.in 29.4 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2019 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 23 24 25 26 27 28 29 30 31
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#
use strict;
use English;
32
use Getopt::Long;
33
use XML::Simple;
34
use File::Temp qw(tempfile :mktemp tmpnam :POSIX);
35
use Date::Parse;
36
use Data::Dumper;
37
use Cwd qw(realpath);
38 39 40 41 42 43

#
# Create a quick VM.
# 
sub usage()
{
44
    print "Usage: quickvm [-u uuid] [--site site:1=aggregate ...] <xmlfile>\n";
45 46
    exit(1);
}
47
my @optlist = ('d', 'v', 'u=s', 'a=s', 'S', 'k=s', 'i', 't=s');
48 49
my $debug   = 0;
my $verbose = 1;
50
my $ignorefailures = 0;
51
my $xmlfile;
52
my $webtask;
Leigh Stoller's avatar
Leigh Stoller committed
53
my $webtask_id;
54
my $localuser  = 0;
55
my $usestitcher= 0;
56 57
my $start_at;
my $stop_at;
58
my $quickuuid;
59
my $this_user;
60
my $xmlparse;
61
my $instance;
62
my $privkeyfile;
63 64
my $slice;
my $sitemap;
65
my $usetracker = 0;
Leigh Stoller's avatar
Leigh Stoller committed
66
my $maxduration = 16; # Hours. Need to make this a site variable.
67 68
my @aggregate_urns = ();

69 70 71 72 73 74 75 76 77 78 79
# Protos
sub fatal($);
sub UserError($);

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $OURDOMAIN     = "@OURDOMAIN@";
80
my $MAINSITE      = @TBMAINSITE@;
81
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
82
my $PROTOGENI_URL = "@PROTOGENI_URL@";
83 84 85
my $SACERT	  = "$TB/etc/genisa.pem";
my $CMCERT	  = "$TB/etc/genicm.pem";
my $SSHKEYGEN     = "/usr/bin/ssh-keygen";
86
my $SSHSETUP      = "$TB/sbin/aptssh-setup";
87
my $ADDPUBKEY     = "$TB/sbin/addpubkey";
88
my $CREATESLIVERS = "$TB/bin/create_slivers";
89
my $UPDATEGENIUSER= "$TB/sbin/protogeni/updategeniuser";
90
my $OPENSSL       = "/usr/bin/openssl";
91
my $MANAGEGITREPO = "$TB/bin/manage_gitrepo";
92
my $DEFAULT_URN   = "urn:publicid:IDN+$OURDOMAIN+authority+cm";
93
my $GUEST_URN     = "urn:publicid:IDN+apt.emulab.net+authority+cm";
94
my $PROTOGENI_LOCALUSER= @PROTOGENI_LOCALUSER@;
95
my $default_aggregate_urn = $DEFAULT_URN;
96 97 98 99 100 101 102 103

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

#
# Turn off line buffering on output
#
104
$| = 1;
105 106 107

# Load the Testbed support stuff.
use lib "@prefix@/lib";
108
use EmulabConstants;
109 110
use libtestbed;
use libaudit;
Leigh Stoller's avatar
Leigh Stoller committed
111
use APT_Profile;
Leigh Stoller's avatar
Leigh Stoller committed
112
use APT_Instance;
113
use APT_Geni;
114
use APT_Dataset;
115
use APT_Aggregate;
116
use Experiment;
117
use User;
118
use Project;
119
use Group;
120
use Image;
121
use emutil;
122
use libEmulab;
123 124 125 126 127 128 129 130 131
use GeniDB;
use GeniUser;
use GeniCertificate;
use GeniCredential;
use GeniSlice;
use GeniAuthority;
use GeniHRN;
use Genixmlrpc;
use GeniResponse;
132
use GeniXML;
133
use WebTask;
134
use Logfile;
135
use EmulabFeatures;
136 137 138 139 140

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
141
Getopt::Long::Configure("no_ignore_case");
142
my %options = ();
143 144 145 146
if (! GetOptions(\%options, @optlist,
		 "site=s%" => \$sitemap,
		 "start=i" => \$start_at,
		 "stop=i"  => \$stop_at)) {
147 148
    usage();
}
149
if (defined($options{"a"})) {
150
    $default_aggregate_urn = $options{"a"};
151
}
152 153 154
if (defined($options{"k"})) {
    $privkeyfile = $options{"k"};
}
155 156 157
if (defined($options{"d"})) {
    $debug = 1;
}
158 159 160
if (defined($options{"i"})) {
    $ignorefailures = 1;
}
161 162 163
if (defined($options{"v"})) {
    $verbose = 1;
}
164 165
if (defined($options{"S"})) {
    $usestitcher = 1;
166
}
167 168 169
if (defined($options{"u"})) {
    $quickuuid = $options{"u"};
}
170 171 172 173 174 175
if (defined($start_at) && $start_at !~ /^\d+$/) {
    fatal("Invalid --start_at parameter");
}
if (defined($stop_at) && $stop_at !~ /^\d+$/) {
    fatal("Invalid --stop_at parameter");
}
176 177 178 179 180 181 182 183
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not lookup/create webtask!");
    }
    $webtask->AutoStore(1);
}
184
if (@ARGV < 1) {
185 186
    usage();
}
187
$xmlfile = shift(@ARGV);
188

189 190 191 192 193 194
$this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
$localuser = 1;

195 196 197 198 199 200
if (!defined($this_user) || !$this_user->IsAdmin()) {
    if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in pathname: $xmlfile");
201 202
    }

203 204 205 206 207 208 209
    # Use realpath to resolve any symlinks.
    my $translated = realpath($xmlfile);
    if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in translated pathname: $xmlfile");
210 211 212
    }
}

213 214
# Email record.
if (! $debug) {
Leigh Stoller's avatar
Leigh Stoller committed
215 216
    my $opts = LIBAUDIT_LOGTBLOGS()|LIBAUDIT_LOGONLY();
    AuditStart(0, undef, $opts);
217 218 219
    #
    # Once we determine the project, we can add the appropriate log CC
    #
220
}
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

# Connect to the SA DB.
DBConnect(GENISA_DBNAME());

#
# Load the SA cert to act as caller context.
#
my $sa_certificate = GeniCertificate->LoadFromFile($SACERT);
if (!defined($sa_certificate)) {
    fatal("Could not load certificate from $SACERT\n");
}
my $sa_authority = GeniAuthority->Lookup($sa_certificate->urn());
if (!defined($sa_authority)) {
    fatal("Could not load SA authority object");
}
236 237 238 239
# Guest users default to the APT cluster on the Mothership.
if ($MAINSITE && !$localuser) {
    $default_aggregate_urn = $GUEST_URN;
}
240 241

#
242
# We use the normal XMLRPC route, so need a context.
243 244 245 246 247 248 249 250 251 252
#
my $context = Genixmlrpc->Context($sa_certificate);
if (!defined($context)) {
    fatal("Could not create context to talk to CM");
}
Genixmlrpc->SetContext($context);

#
# Must wrap the parser in eval since it exits on error.
#
253 254 255 256
$xmlparse = eval { XMLin($xmlfile,
			 VarAttr => 'name',
			 ContentKey => '-content',
			 SuppressEmpty => undef); };
257 258 259 260 261 262
fatal($@)
    if ($@);

#
# Make sure all the required arguments were provided.
#
263
foreach my $key ("username", "email", "profile", "portal") {
264 265 266 267 268 269 270 271 272
    fatal("Missing required attribute '$key'")
	if (! (exists($xmlparse->{'attribute'}->{"$key"}) &&
	       defined($xmlparse->{'attribute'}->{"$key"}) &&
	       $xmlparse->{'attribute'}->{"$key"} ne ""));
}

#
# Gather up args and sanity check.
#
273
my ($value, $user_urn, $user_uid, $user_hrn, $user_email, $project, $pid,
274
    $gid, $group, $sshkey, $profile, $profileid, $version, $rspecstr, $errmsg,
275
    $userslice_id, $portal, $script, $reporef, $repohash, $duration);
276 277 278

# This is used internally to determine which portal was used.
$portal = $xmlparse->{'attribute'}->{"portal"}->{'value'};
279

280
# User specified duration.
281 282 283 284 285 286 287 288 289 290 291
if (exists($xmlparse->{'attribute'}->{"duration"}) &&
    defined($xmlparse->{'attribute'}->{"duration"}) &&
    $xmlparse->{'attribute'}->{"duration"}->{'value'} ne "") {
    $duration = $xmlparse->{'attribute'}->{"duration"}->{'value'};
    if ($duration !~ /^\d+$/) {
	fatal("Duration is not an integer");
    }
    if ($duration < 1 || $duration > $maxduration) {
	UserError("Duration must be at least 1 hour but ".
		  "not more then $maxduration hour(s)");
    }
292
}
293 294
else {
    $duration = $maxduration; 
295 296
}

297 298 299 300
#
# Username and email has to be acceptable to Emulab user system.
#
$value = $xmlparse->{'attribute'}->{"username"}->{'value'};
301
if (! TBcheck_dbslot($value, "users", "uid",
302
		     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
303
    fatal("Illegal username: $value - " . TBFieldErrorString());
304 305 306 307 308 309 310 311 312 313 314 315
}
$user_uid = $value;
$user_urn = GeniHRN::Generate("$OURDOMAIN", "user", $user_uid);
$user_hrn = "${PGENIDOMAIN}.${user_uid}";

$value = $xmlparse->{'attribute'}->{"email"}->{'value'};
if (! TBcheck_dbslot($value, "users", "usr_email",
		     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
    fatal("Illegal email address: $value");
}
$user_email = $value;

316 317 318 319 320 321 322 323 324 325
#
# The instance name is optional, we will make one up if not supplied.
#
if (exists($xmlparse->{'attribute'}->{"instance_name"}) &&
    $xmlparse->{'attribute'}->{"instance_name"}->{'value'} ne "") {
    $value = $xmlparse->{'attribute'}->{"instance_name"}->{'value'};
    if (! TBcheck_dbslot($value, "experiments", "eid",
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	fatal("Illegal instance name: $value");
    }
326
    $userslice_id = $value;
327 328
}

329
#
330
# Profile.
331
#
332
# This is a safe lookup.
333 334 335
$value = $xmlparse->{'attribute'}->{"profile"}->{'value'};
$profile = APT_Profile->Lookup($value);
if (!defined($profile)) {
Leigh Stoller's avatar
Leigh Stoller committed
336
    fatal("No such profile: $value");
337
}
338 339
$profileid = $profile->profileid();
$version   = $profile->version();
340

341
#
342
# Optional rspec, as for a Parameterized Profile or a repo-based profile.
343
#
344 345
if (exists($xmlparse->{'attribute'}->{"rspec"})) {
    $rspecstr  = $xmlparse->{'attribute'}->{"rspec"}->{'value'};
346 347 348 349 350
    # Trim()
    $rspecstr =~ s/^\s+|\s+$//g;
    if ($rspecstr eq "") {
	UserError("Not a valid rspec");
    }
351
}
352
else {
353 354 355 356 357 358 359
    $rspecstr = $profile->rspec();
    # Trim()
    $rspecstr =~ s/^\s+|\s+$//g;
    if ($rspecstr eq "") {
	UserError("Profile does not have a valid rspec");
    }
    $rspecstr = $profile->CheckFirewall(!$localuser);
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
#
# Optional rspec and/or script, as for a repo-based profile.
#
if ($profile->repourl()) {
    if (exists($xmlparse->{'attribute'}->{"script"})) {
	$script = $xmlparse->{'attribute'}->{"script"}->{'value'};	

	if (! TBcheck_dbslot($script, "apt_profiles", "script",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    fatal("Illegal script for repo-based profile");
	}
	if (!exists($xmlparse->{'attribute'}->{"reporef"})) {
	    fatal("Missing refspec for repository");
	}
    }
    if (exists($xmlparse->{'attribute'}->{"reporef"})) {
	if (!exists($xmlparse->{'attribute'}->{"repohash"})) {
	    fatal("Missing hash for repository");
	}
	$reporef  = $xmlparse->{'attribute'}->{"reporef"}->{'value'};
	$repohash = $xmlparse->{'attribute'}->{"repohash"}->{'value'};

	if (! TBcheck_dbslot($repohash, "apt_profiles", "repohash",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    fatal("Illegal repository hash");
	}
	if (! TBcheck_dbslot($reporef, "default", "tinytext",
			     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	    fatal("Illegal repository refspec");
	}
    }
392 393 394 395 396
    else {
	# Otherwise we are instantiating whatever the profile itself references.
	$reporef  = "refs/heads/master";
	$repohash = $profile->repohash();
    }
397
}
398

399 400 401 402 403 404
#
# Update rspec with site aggregate urns.
#
# SetSites will tell us if we must use stitcher.
#
my $needstitcher = 0;
405 406 407 408
my $tmp = APT_Profile::SetSites(\$rspecstr, $sitemap, $default_aggregate_urn,
				\@aggregate_urns, \$needstitcher, \$errmsg);
if ($tmp) {
    ($tmp < 0 ? fatal($errmsg) : UserError($errmsg));
409
}
410 411 412 413 414 415 416
#
# Yep, this can happen when users do not put any nodes in their rspec.
#
if (!@aggregate_urns) {
    UserError("There are no nodes in your experiment, syntax error?");
}

417 418
# but do not override command line force.
$usestitcher = 1 if ($needstitcher);
419

420 421
#
# Look for datasets; need to verify that the datasets being referenced
422 423
# actually exists, in so far as we can check. We check permissions
# below when we generate the credentials.
424 425
#
$errmsg = "Bad dataset";
426
if (APT_Profile::CheckDatasets($rspecstr, \$errmsg)) {
427 428 429
    UserError($errmsg);
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
#
# Use ssh-keygen to see if the key is valid and convertable. We first
# try to get the fingerprint, which will tells us if its already in
# openssh format. If not, try to convert it.
#
if (exists($xmlparse->{'attribute'}->{"sshkey"}) &&
    defined($xmlparse->{'attribute'}->{"sshkey"}) &&
    $xmlparse->{'attribute'}->{"sshkey"} ne "") {
    $sshkey = $xmlparse->{'attribute'}->{"sshkey"}->{'value'};
    my ($fh, $keyfile) = tempfile(UNLINK => 0);
    print $fh $sshkey;

    if (system("$SSHKEYGEN -l -f $keyfile >/dev/null 2>/dev/null")) {
	if (! open(KEYGEN, "$SSHKEYGEN -i -f $keyfile 2>/dev/null |")) {
	    fatal("Could not start ssh-keygen");
	}
	$sshkey = <KEYGEN>;
	if (!close(KEYGEN)) {
	    UserError("Could not parse ssh key!");
	}
    }
451 452
    close($fh);
    unlink($keyfile);
453
}
454 455
chomp($sshkey)
    if (defined($sshkey));
456 457 458 459 460 461

#
# See if the GeniUser exists. Create if not, but that means we
# have to create an ssl certificate (which the user will never see)
# so that we can operate on behalf of the user (via speaksfor).
#
462 463 464 465 466 467 468
# Note that we want to check for the user local account ahead of
# SA account, to bypass their guest account that might still be
# in the table.
#
my $geniuser;

if ($localuser) {
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    my $emulab_user = User->Lookup($user_uid);
    
    #
    # Hmm, users with real accounts who never used Geni, but now want
    # to use APT/Cloud, have no encrypted SSL certificate. Rather then
    # force them through the web ui (and have to explain it), create one
    # for them using a random passphrase. The user will not know the
    # passphrase, but for most users it will not matter.
    #
    # This is also going to catch expired certificates, we will regenerate
    # them using the existing passphrase.
    #
    if ($emulab_user->HasValidEncryptedCert() == 0 &&
	$emulab_user->GenEncryptedCert()) {
	fatal("Could not (re)generate encrypted certificate");
    }
Leigh Stoller's avatar
Leigh Stoller committed
485
    # Now this will work; without a certificate, above line would fail.
486 487 488
    if (defined($emulab_user)) {
	$geniuser = GeniUser::LocalUser->Create($emulab_user);
    }
489 490 491 492
}
else {
    $geniuser = GeniUser->Lookup($user_urn);

493 494 495
    #
    # In Utah, check for alternate SA
    #
496
    if (!defined($geniuser) && $MAINSITE) {
497 498 499 500 501
	foreach my $urn (@aggregate_urns) {
	    if ($urn ne $GUEST_URN) {
		UserError("Guests are not allowed to use cluster: $urn");
	    }
	}
502 503
	$user_urn = GeniHRN::Generate("aptlab.net", "user", $user_uid);
	$user_hrn = "aptlab.${user_uid}";
504
	$geniuser = GeniUser->LookupGuestOnly($user_urn);
505 506
    }
}
507
if (!defined($geniuser)) {
508 509 510
    if ($localuser) {
	fatal("Could not lookup local user $user_urn");
    }
511
    
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    #
    # Do not allow overlap with local users.
    #
    if (User->Lookup($user_uid)) {
	fatal("User $user_uid exists in the local user table");
    }

    print "Geni user does not exist; creating one ...\n"
	if ($debug);

    #
    # Want to remember the auth token we emailed for later.
    #
    my $auth_token = $xmlparse->{'attribute'}->{"auth_token"}->{'value'};
    if ($auth_token !~ /^[\w]+$/) {
	fatal("Bad auth token: $auth_token");
    }
529 530 531 532 533 534 535 536
    my $blob = {"urn"      => $user_urn,
		"hrn"      => $user_hrn,
		"email"    => $user_email,
		"showuuid" => 1};
    if ($MAINSITE) {
	$blob->{'useaptca'} = 1;
    }
    my $certificate = GeniCertificate->Create($blob);
537 538 539 540 541 542 543 544 545 546
    fatal("Could not create certificate")
	if (!defined($certificate));

    $geniuser = GeniUser->Create($certificate, $sa_authority);
    fatal("Could not create new geni user")
	if (!defined($geniuser));

    $geniuser->SetAuthToken($auth_token);

    #
Leigh Stoller's avatar
Leigh Stoller committed
547
    # Setup browser ssh.
548
    #
549 550 551
    system("$SSHSETUP " . $geniuser->uuid());
    fatal("Could not create ssh key pair")
	if ($?);
552 553 554 555
}
my $user_uuid = $geniuser->uuid();
# So we know this user has dome something lately.
$geniuser->BumpActivity();
556

557 558 559
if ($localuser) {
    my $emulab_user = $geniuser->emulab_user();
    if ($emulab_user->IsNonLocal()) {
560 561
	#
	# A user created from a Geni certificate via geni-login. We
562 563
	# asked for the current ssh keys from the MA when they logged
	# in, but we ask again to make sure have the latest keys.
564
	#
565
	system("$UPDATEGENIUSER -s " . $emulab_user->uid());
566
	if (0) {
567 568
	    fatal("Could not update ssh keys for nonlocal user");
	}
569 570 571 572 573 574
	#
	# Check project membership, must be a member of at least one
	# valid project at the GPO portal.
	#
	system("$UPDATEGENIUSER -p " . $emulab_user->uid());
	if ($?) {
575 576 577
	    UserError("Could not get your project membership from your ".
		      "member authority. It is probably offline, please try ".
		      "again later.");
578
	}
Leigh Stoller's avatar
Leigh Stoller committed
579 580
	# Nonlocal users get the holding project can now join/create
	# real projects, so we get the pid passed in.
581
    }
582
    elsif (defined($sshkey) && !$emulab_user->LookupSSHKey($sshkey)) {
583 584 585 586 587 588
	#
	# XXX This is deprecated; we no longer show the ssh box to
	#     real users. Remove when we are satisfied with new
	#     ssh key management page.
	#
	
589
	#
590 591 592 593
	# A local user. We mark keys that come through this path
	# with the isaptkey flag (-a to addpubkey) so that we know
	# which key in the DB it is. The reason for this is that the
	# user might be a classic emulab user, but is now using the
594 595 596 597 598
	# APT/Cloud UI. The key provided in the web interface will
	# replace this key.
	#
	# XXX This is in flux, we now allow APT users to manage all
	# their keys via the web interface.
599
	#
600 601 602
	my ($fh, $keyfile) = tempfile(UNLINK => 0);
	print $fh $sshkey;

603
	if (system("$ADDPUBKEY -a -u $user_uid -f $keyfile")) {
604 605 606 607 608
	    fatal("Could not add new ssh pubkey");
	}
	close($fh);
	unlink($keyfile);
    }
609 610 611 612 613 614 615 616 617 618 619 620 621 622
    #
    # Hmm, users with real accounts who never used Geni, but now want
    # to use APT/Cloud, have no encrypted SSL certificate. Rather then
    # force them through the web ui (and have to explain it), create one
    # for them using a random passphrase. The user will not know the
    # passphrase, but for most users it will not matter.
    #
    # This is also going to catch expired certificates, we will regenerate
    # them using the existing passphrase.
    #
    if ($emulab_user->HasValidEncryptedCert() == 0 &&
	$emulab_user->GenEncryptedCert()) {
	fatal("Could not (re)generate encrypted certificate");
    }
623 624 625 626 627 628 629 630 631 632

    # Local users are required to select a project.
    if (! exists($xmlparse->{'attribute'}->{"pid"})) {
	fatal("No project provided for new instance");
    }
    $project = Project->Lookup($xmlparse->{'attribute'}->{"pid"}->{"value"});
    if (!defined($project)) {
	fatal("Project provided does not exist");
    }
    $pid = $project->pid();
633

634 635 636 637 638 639 640 641 642
    # Option subgroup.
    if (exists($xmlparse->{'attribute'}->{"gid"}) &&
	$xmlparse->{'attribute'}->{"gid"}->{"value"} ne "" &&
	$xmlparse->{'attribute'}->{"gid"}->{"value"} ne $pid) {
	my $val = $xmlparse->{'attribute'}->{"gid"}->{"value"};
	$group = $project->LookupGroup($val);
	if (!defined($group)) {
	    fatal("Group $val does not exist in project $pid");
	}
643 644 645 646
	if (!$group->AccessCheck($emulab_user, TB_PROJECT_CREATEEXPT)) {
	    UserError("No permission to create experiments in group ".
		      $group->pid() . "/" . $group->gid());
	}
647 648
    }
    else {
649 650 651 652
	if (!$project->AccessCheck($emulab_user, TB_PROJECT_CREATEEXPT)) {
	    UserError("No permission to create experiments in project ".
		      $project->pid());
	}
653 654 655 656
	$group = $project->GetProjectGroup();
    }
    $gid = $group->gid();

657
    # Hack for Kobus' class, generalize someday.
658
    if (0 && $pid eq "CS4480-2018") {
659 660 661 662
	my $termination = str2time("2018-05-02");
	# convert to hours till then
	$duration = int(($termination - time()) / 3600);
    }
663 664 665 666 667
}
elsif (!$localuser) {
    if (defined($sshkey)) {    #
	# Guest user; remember key. For now we accept only one key. We store
	# it simply so we can display it again for the user in the web
668
	# interface. We allow key reuse for existing users, see above.
669 670 671 672 673
	#
	$geniuser->DeleteKeys();
	$geniuser->AddKey($sshkey);
    }
    # Guest users get a holding project.
674
    $pid = $APT_HOLDINGPROJECT;
675
    $project = Project->Lookup($pid);
676
    $group = $project->GetProjectGroup();
Leigh Stoller's avatar
Leigh Stoller committed
677
    $gid = $group->gid();
678 679 680
    if (!defined($project)) {
	fatal("Project $pid does not exist");
    }
681
}
Leigh Stoller's avatar
Leigh Stoller committed
682
if (defined($profile->repourl())) {
683 684 685 686 687 688 689 690
    #
    # Make sure the repo is still accessible.
    #
    my $check = emutil::ExecQuiet("$MANAGEGITREPO check ".
				  "'" . $profile->repourl() . "'");
    if ($?) {
	UserError($check);
    }
Leigh Stoller's avatar
Leigh Stoller committed
691 692 693 694 695
    $tmp = APT_Profile::SetRepo(\$rspecstr, $profile->repourl(),
				$reporef, $repohash, $geniuser, \$errmsg);
    if ($tmp) {
	($tmp < 0 ? fatal($errmsg) : UserError($errmsg));
    }
696 697
}

698 699 700
#
# Now we know where to send to logs.
#
701 702
if (!$debug) {
    AddAuditInfo("cc", $project->LogsEmailAddress());
703
    AddAuditInfo("brand", $project->Brand());
704
}
705

706 707 708 709 710 711
# Check for expired certs and speaksfor.
my $retval = APT_Geni::VerifyCredentials($geniuser, \$errmsg);
if ($retval) {
    ($retval < 0 ? fatal($errmsg) : UserError($errmsg));
}

712
#
713 714 715
#
# Now generate a slice registration and credential
#
716
my $safe_uid    = $user_uid; $safe_uid =~ s/_/-/;
717 718
my $slice_id    = (defined($userslice_id) ? $userslice_id :
		   $safe_uid . "-QV" . TBGetUniqueIndex('next_quickvm', 1));
719 720 721
my $slice_auth  = ($pid eq $gid ? $pid : "${pid}:${gid}");
my $slice_urn   = GeniHRN::Generate("${OURDOMAIN}:${slice_auth}",
				    "slice", $slice_id);
722 723 724
if (!defined($slice_urn)) {
    fatal("Could not generate a valid slice urn!");
}
725
my $slice_hrn   = "${PGENIDOMAIN}.${pid}.${slice_id}";
726
my $SERVER_NAME = (exists($ENV{"SERVER_NAME"}) ? $ENV{"SERVER_NAME"} : "");
727 728 729 730

#
# Make sure slice is unique. Probably retry here at some point. 
#
731 732 733 734
if (GeniSlice->Lookup($slice_hrn) || GeniSlice->Lookup($slice_urn) ||
    ($PROTOGENI_LOCALUSER &&
     (grep {$_ eq $DEFAULT_URN} @aggregate_urns) &&
     Experiment->Lookup($project->pid(), $userslice_id))) {
735
    if (defined($userslice_id)) {
736
	UserError("Experiment name already in use, please use another. If you ".
737 738 739 740 741 742
		  "just terminated an experiment with this name, it takes a ".
		  "minute or two for the name to become available again.");
    }
    else {
	fatal("Could not form a unique slice name");
    }
743
}
744

745 746 747 748 749 750 751 752 753 754 755 756 757
#
# Generate a certificate for this new slice.
#
my $slice_certificate =
    GeniCertificate->Create({'urn'  => $slice_urn,
			     'hrn'  => $slice_hrn,
			     'showuuid' => 1,
			     'email'=> $user_email});

if (!defined($slice_certificate)) {
    fatal("Could not generate certificate for $slice_urn");
}
# Slice is created as locked.
758 759
$slice = GeniSlice->Create($slice_certificate,
			   $geniuser, $sa_authority, undef, 1);
760 761 762 763
if (!defined($slice)) {
    $slice_certificate->Delete();
    fatal("Could not create new slice object for $slice_urn");
}
764
# These get quick expirations, unless it is a real user.
765 766
if ($slice->SetExpiration((defined($start_at) ? $start_at : time()) +
			  ($duration * 3600)) != 0) {
767 768 769 770
    fatal("Could not set the slice expiration for $slice_urn");
}
my $slice_uuid = $slice->uuid();

771 772 773 774 775 776 777 778 779 780 781
#
# Generate a new ssl key/cert to be used to derive an ssh key pair
# or whatever else is needed. This is sent along as an option when the
# sliver is created (or provisioned, when stitching).
#
# This is going to be a real geni certificate, albeit a slice
# certificate in the alternate CA domain, that can be used at the
# "portal" XMLRPC interface. The key is unencrypted and put on the
# nodes, hence the alternate CA, and the XMLRPC server will not allow
# this certificate to do anything, except at the portal RPC server.
#
782
my $alt_urn = GeniHRN::Generate("aptlab.net:${slice_auth}", "slice", $slice_id);
783 784 785 786 787 788 789 790 791
my $alt_hrn = "aptlab.${pid}.${slice_id}";
my $alt_url = "$PROTOGENI_URL/portal";

my $altblob = {"urn"      => $alt_urn,
	       "hrn"      => $alt_hrn,
	       "url"      => $alt_url,
	       "uuid"     => $slice_uuid,
	       "email"    => $user_email,
	       "nostore"  => 1,
792
               "keyfile"  => $privkeyfile,
793 794 795 796 797 798
	       "useaptca" => 1,
	       "showuuid" => 1};
my $alt_certificate = GeniCertificate->Create($altblob);
fatal("Could not create alt certificate")
    if (!defined($alt_certificate));

799 800 801 802 803 804 805 806
#
# Encrypt blocks.
#
$tmp = APT_Profile::EncryptBlocks(\$rspecstr, $alt_certificate, \$errmsg);
if ($tmp) {
    ($tmp < 0 ? fatal($errmsg) : UserError($errmsg));
}

807
#
808
# Got this far, lets create a quickvm record.
809
#
810
my $quickvm_uuid = (defined($quickuuid) ? $quickuuid : NewUUID());
811 812 813
if (!defined($quickvm_uuid)) {
    fatal("Could not generate a new uuid");
}
814
my $blob = {'uuid'         => $quickvm_uuid,
815
	    'name'         => $slice_id,
816 817 818 819 820 821
	    'profile_id'   => $profileid,
	    'profile_version' => $version,
	    'slice_uuid'   => $slice_uuid,
	    'creator'      => $geniuser->uid(),
	    'creator_idx'  => $geniuser->idx(),
	    'creator_uuid' => $geniuser->uuid(),
822 823 824
	    'status'       => ($start_at ? "deferred" : "created"),
	    'start_at'     => $start_at,
	    'stop_at'      => $stop_at,
825 826
	    'servername'   => $SERVER_NAME,
	    'rspec'        => $rspecstr,
827
	    'cert'         => $alt_certificate->cert(),
828
	    'privkey'      => $alt_certificate->PrivKeyDelimited(),
829
};
830 831 832 833 834
if ($profile->repourl()) {
    if (defined($script)) {
	$blob->{"script"}  = $script;
    }
    $blob->{"repourl"}   = $profile->repourl();
835 836
    $blob->{"reporef"}   = $reporef;
    $blob->{"repohash"}  = $repohash;
837
}
838 839 840
if (defined($project)) {
    $blob->{"pid"}     = $project->pid();
    $blob->{"pid_idx"} = $project->pid_idx();
841 842
    $blob->{"gid"}     = $group->gid();
    $blob->{"gid_idx"} = $group->gid_idx();
843
}
844
$errmsg = undef;
845
$instance = APT_Instance->Create($blob, \$errmsg);
Leigh Stoller's avatar
Leigh Stoller committed
846
if (!defined($instance)) {
847 848
    fatal(defined($errmsg) ? $errmsg :
	  "Could not create instance record for $quickvm_uuid");
849
}
850 851 852 853 854
# Apply policies,
if ($instance->ApplyExtensionPolicies()) {
    $instance->Delete();
    fatal("Error applying policies");
}
855

856 857 858 859 860
# Generate the extra credentials that tells the backend this experiment
# can access the datasets.
my @dataset_credentials = ();
$retval = $instance->CreateDatasetCreds(\$errmsg, \@dataset_credentials);
if ($retval) {
861
    $instance->Delete();
862
    ($retval < 0 ? fatal($errmsg) : UserError($errmsg));
863 864
}

865 866 867
# We use this list of references for ParRun below.
my @aggregate_list = ();
foreach my $aggregate_urn (@aggregate_urns) {
868 869
    my $aptaggregate = APT_Aggregate->Lookup($aggregate_urn);
    if (!defined($aptaggregate)) {
870 871
	$slice->Delete();
	$instance->Delete();
872
        UserError("$aggregate_urn is not a valid (known) aggregate.");
873
    }
874 875 876
    my $aggregate_name = $aptaggregate->name();

    # Check to make sure the aggregate is online and reachable
877 878 879
    # We do not do this if the experiment start is deferred.
    if (!defined($start_at)) {
	if ($aptaggregate->CheckStatus(\$errmsg)) {
880
	    if ($usestitcher || !$aptaggregate->deferrable()) {
881 882 883 884 885
		$slice->Delete();
		$instance->Delete();
		UserError($errmsg);
	    }
	}
886
    }
887
    if ($aptaggregate->adminonly() &&
888 889
        !(defined($this_user) &&
	  ($this_user->IsAdmin() || $this_user->stud()))) {
890 891
	$slice->Delete();
	$instance->Delete();
892
        UserError("Only administrators may use the $aggregate_name cluster.");
893
    }
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    my $authority = GeniAuthority->Lookup($aggregate_urn);
    if (!defined($authority)) {
	$authority = GeniAuthority->CreateFromRegistry("cm", $aggregate_urn);
	if (!defined($authority)) {    
	    fatal("Could not load CM authority object for $aggregate_urn");
	}
    }
    my $aggobj = $instance->AddAggregate($aggregate_urn);
    if (!defined($aggobj)) {
	fatal("Could not create aggregate object for $aggregate_urn");
    }
    $aggobj->_authority($authority);
    push(@aggregate_list, $aggobj);
}

909 910 911 912 913 914 915 916 917 918 919 920 921
# Must create a webtask if we did not get one on the command line.
if (!defined($webtask)) {
    $webtask = WebTask->Create($quickvm_uuid);
    if (!defined($webtask)) {
	fatal("Could not create a webtask!");
    }
    $webtask_id = $webtask->task_id();
    $webtask->AutoStore(1);
}
# The instance now owns this webtask, even if it was a command line arg.
# The caller is not allowed to delete it.
$instance->Update({'webtask_id' => $webtask_id});

Leigh Stoller's avatar
Leigh Stoller committed
922 923
# To keep stuff happy until multisite support finished.
$instance->Update({'aggregate_urn' => $aggregate_urns[0]});
924 925
# Officially used now. Even if it fails later.
$profile->BumpLastUsed();
Leigh Stoller's avatar
Leigh Stoller committed
926

927 928 929 930 931 932 933 934
print STDERR "\n";
print STDERR "User:    $user_urn\n";
print STDERR "Email:   $user_email" . (!$localuser ? " (guest)" : "") . "\n";
if (defined($profile)) {
    print STDERR "Profile: " . $profile->name() . ":${version}\n";
}
print STDERR "Slice:   $slice_urn\n";
print STDERR "Server:  $SERVER_NAME\n";
935 936 937 938 939 940 941 942 943
if (defined($start_at)) {
    print STDERR "Start at: ".
	POSIX::strftime("%m/%d/20%y %H:%M:%S", localtime($start_at)) . "\n";
}
if (defined($stop_at)) {
    print STDERR "Stop at: ".
	POSIX::strftime("%m/%d/20%y %H:%M:%S", localtime($stop_at)) . "\n";
}
print STDERR "Duration: $duration hours\n";
944 945 946 947
print STDERR "Cluster: ";
print STDERR join(",", map($_->aggregate_urn(), @aggregate_list))  . "\n";
print STDERR "\n";
print STDERR "$rspecstr\n";
948 949

#
950 951 952 953 954 955 956 957 958 959 960
# If start is deferred, then mark it and exit immediately.
#
if (defined($start_at)) {
    $instance->Defer($start_at);
    $slice->UnLock();
    exit(0);
}

#
# Hand off to create slivers script. We have to fork/system cause
# of libaudit logging.
961 962
#
if (!$debug) {
963
    libaudit::AuditPrefork();
964 965 966 967 968 969 970 971
    my $child = fork();
    if ($child) {
	# Parent exits but avoid libaudit email.
	exit(0);
    }
    # All of the logging magic happens in here.
    libaudit::AuditFork();
}
972 973 974 975 976 977
system("$CREATESLIVERS -L -f " .
       ($debug ? "-d " : "") . ($usestitcher ? "-S " : "") . $quickvm_uuid);
if ($?) {
    my $code = $? >> 8;
    $code = -1
	if ($code == 255);
978
    #
979 980 981
    # If we did not use the stitcher, a positive exit code indicates
    # a user error, not a system error. We abort the logging so that
    # only the user sees the error. 
982
    #
983 984 985
    if (!$usestitcher && $code > 0) {
	AuditAbort()
	    if (!$debug);
986
    }
987
    exit($code);
988
}
989
exit(0);
990

991 992 993
sub fatal($) {
    my ($mesg) = $_[0];

994 995 996 997
    $slice->Delete()
	if (defined($slice));
    $instance->SetStatus("failed")
	if (defined($instance));
998 999 1000 1001
    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(-1);
    }
1002 1003 1004
    print STDERR Dumper($xmlparse)
	if (defined($xmlparse));

1005 1006 1007 1008 1009 1010 1011
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}
sub UserError($) {
    my($mesg) = $_[0];

1012 1013 1014 1015
    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(1);
    }
1016 1017
    AuditAbort()
	if (!$debug);
1018
    print $mesg . "\n";
1019 1020 1021
    exit(1);
}