create_instance.in 24.9 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2015 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 32 33
# 
# {{{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;
use Getopt::Std;
use XML::Simple;
34
use File::Temp qw(tempfile :POSIX );
35
use Data::Dumper;
36
use Cwd qw(realpath);
37 38 39 40 41 42

#
# Create a quick VM.
# 
sub usage()
{
43
    print "Usage: quickvm [-u uuid] [-a aggregate] <xmlfile>\n";
44 45
    exit(1);
}
46
my $optlist = "dvu:a:t:f";
47 48
my $debug   = 0;
my $verbose = 1;
49
my $DEFAULT_URN  = "urn:publicid:IDN+apt.emulab.net+authority+cm";
50
my $xmlfile;
51 52 53
my $webtask;
my $webtask_id;
my $foreground = 0;
54
my $localuser  = 0;
55
my $quickuuid;
56
my $aggregate;
57
my $this_user;
58
my $xmlparse;
59 60 61 62

# Protos
sub fatal($);
sub UserError($);
63
sub SnapShot($$$);
64
sub GenCredentials($$$$);
65
sub CreateDatasetCreds($$$$$);
66 67 68 69 70 71 72 73

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $OURDOMAIN     = "@OURDOMAIN@";
74
my $MAINSITE      = @TBMAINSITE@;
75 76 77 78
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
my $SACERT	  = "$TB/etc/genisa.pem";
my $CMCERT	  = "$TB/etc/genicm.pem";
my $SSHKEYGEN     = "/usr/bin/ssh-keygen";
79
my $SSHSETUP      = "$TB/sbin/aptssh-setup";
80
my $ADDPUBKEY     = "$TB/sbin/addpubkey";
81
my $UPDATEGENIUSER= "$TB/sbin/protogeni/updategeniuser";
82 83 84 85 86 87 88 89 90 91 92 93

# 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
#
$| = 1; 

# Load the Testbed support stuff.
use lib "@prefix@/lib";
94
use EmulabConstants;
95 96
use libtestbed;
use libaudit;
Leigh B Stoller's avatar
Leigh B Stoller committed
97
use APT_Profile;
Leigh B Stoller's avatar
Leigh B Stoller committed
98
use APT_Instance;
99
use APT_Geni;
100
use APT_Dataset;
101
use User;
102
use Project;
103 104 105 106 107 108 109 110 111 112 113
use OSinfo;
use emutil;
use GeniDB;
use GeniUser;
use GeniCertificate;
use GeniCredential;
use GeniSlice;
use GeniAuthority;
use GeniHRN;
use Genixmlrpc;
use GeniResponse;
114
use GeniXML;
115
use WebTask;
116 117 118 119 120 121 122 123 124

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
125 126 127
if (defined($options{"a"})) {
    $aggregate = $options{"a"};
}
128 129 130 131 132 133
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verbose = 1;
}
134 135 136 137 138 139
if (defined($options{"f"})) {
    $foreground = 1;
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
}
140 141 142
if (defined($options{"u"})) {
    $quickuuid = $options{"u"};
}
143
if (@ARGV < 1) {
144 145
    usage();
}
146
$xmlfile = shift(@ARGV);
147

148 149 150 151 152 153
#
# Check the filename when invoked from the web interface; must be a
# file in /tmp.
#
if (getpwuid($UID) ne "nobody") {
    $this_user = User->ThisUser();
154

155 156 157 158 159 160 161 162 163 164 165
    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
    $localuser = 1;
}
if (!defined($this_user) || !$this_user->IsAdmin()) {
    if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in pathname: $xmlfile");
166 167
    }

168 169 170 171 172 173 174
    # Use realpath to resolve any symlinks.
    my $translated = realpath($xmlfile);
    if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in translated pathname: $xmlfile");
175 176 177
    }
}

178 179 180
# Email record.
if (! $debug) {
    AuditStart(0, undef, LIBAUDIT_LOGTBLOGS()|LIBAUDIT_LOGONLY());
181
    AddAuditInfo("cc", "aptnet-logs\@flux.utah.edu");
182
}
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

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

#
# We want to contact our local CM to create the sliver.
# We use the normal XMLRPC route.
#
my $context = Genixmlrpc->Context($sa_certificate);
if (!defined($context)) {
    fatal("Could not create context to talk to CM");
}
Genixmlrpc->SetContext($context);

#
210
# Load the CM authority, since that is who we talk to.
211
#
212 213
my $CMURN;

214 215 216
if (defined($aggregate)) {
    $CMURN = $aggregate;
}
217
else {
218
    $CMURN = $DEFAULT_URN;
219 220
}
my $cm_authority = GeniAuthority->Lookup($CMURN);
221
if (!defined($cm_authority)) {
222 223 224 225
    $cm_authority = GeniAuthority->CreateFromRegistry("cm", $CMURN);
    if (!defined($cm_authority)) {    
	fatal("Could not load CM authority object");
    }
226
}
227
my $cmurl = $cm_authority->url();
228
#$cmurl =~ s/protogeni/protogeni\/stoller/;
229

230 231 232
my $iscloudlab =
    ($CMURN eq "urn:publicid:IDN+utah.cloudlab.us+authority+cm" ? 1 : 0);

233 234 235
#
# Must wrap the parser in eval since it exits on error.
#
236 237 238 239
$xmlparse = eval { XMLin($xmlfile,
			 VarAttr => 'name',
			 ContentKey => '-content',
			 SuppressEmpty => undef); };
240 241 242 243 244 245
fatal($@)
    if ($@);

#
# Make sure all the required arguments were provided.
#
246
foreach my $key ("username", "email", "profile") {
247 248 249 250 251 252 253 254 255
    fatal("Missing required attribute '$key'")
	if (! (exists($xmlparse->{'attribute'}->{"$key"}) &&
	       defined($xmlparse->{'attribute'}->{"$key"}) &&
	       $xmlparse->{'attribute'}->{"$key"} ne ""));
}

#
# Gather up args and sanity check.
#
256
my ($value, $user_urn, $user_uid, $user_hrn, $user_email, $project, $pid,
257
    $sshkey, $profile, $profileid, $version, $rspecstr, $errmsg);
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

#
# Username and email has to be acceptable to Emulab user system.
#
$value = $xmlparse->{'attribute'}->{"username"}->{'value'};
if (! TBcheck_dbslot($value, "users", "usr_name",
		     TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
    fatal("Illegal username: $value");
}
$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;

#
279
# Profile.
280
#
281
# This is a safe lookup.
282 283 284
$value = $xmlparse->{'attribute'}->{"profile"}->{'value'};
$profile = APT_Profile->Lookup($value);
if (!defined($profile)) {
Leigh B Stoller's avatar
Leigh B Stoller committed
285
    fatal("No such profile: $value");
286
}
287 288
$profileid = $profile->profileid();
$version   = $profile->version();
289

290
#
291
# Optional rspec, as for a Parameterized Profile.
292
#
293 294
if (exists($xmlparse->{'attribute'}->{"rspec"})) {
    $rspecstr  = $xmlparse->{'attribute'}->{"rspec"}->{'value'};
295
}
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
else {
    $rspecstr  = $profile->CheckFirewall(!$localuser);
    #
    # Temp hack; replace URNs with URLs.
    #
    if (1 && $profile->ConvertDiskImages()) {
	fatal("Not able to convert disk_image URNs to URLs.");
    }
    #
    # Look for datasets; need to verify that the datasets being referenced
    # still exist and are still permissible to use, and we have to generate
    # credentials for those datasets (if not a global dataset). The tricky
    # aspect is that while a dataset and a profile have project permissions,
    # the experiment has no project association, so if the profile/dataset
    # perms are okay, then we send over a credential that tells the CM to
    # allow this experiment to use that dataset in that project. 
    #
    $errmsg = "Bad dataset";
    if (APT_Profile::CheckDatasets($rspecstr, $profile->pid(), \$errmsg)) {
	UserError($errmsg);
    }
    #
    # A temporary hack to make sure that the user does not try to run
    # an x386 image on the Cloudlab cluster (ARMs). This will eventually
    # get replaced with Jon's constraint checking code.
    #
    if ($profile->CheckNodeConstraints($iscloudlab, \$errmsg)) {
	UserError($errmsg);
    }
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
#
# 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!");
	}
    }
348 349
    close($fh);
    unlink($keyfile);
350
}
351 352
chomp($sshkey)
    if (defined($sshkey));
353 354 355 356 357 358

#
# 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).
#
359 360 361 362 363 364 365
# 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) {
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    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");
    }
    # Now this will work; without a certificate, this would fail.
    if (defined($emulab_user)) {
	$geniuser = GeniUser::LocalUser->Create($emulab_user);
    }
386 387 388 389
}
else {
    $geniuser = GeniUser->Lookup($user_urn);

390 391 392
    #
    # In Utah, check for alternate SA
    #
393
    if (!defined($geniuser) && $MAINSITE) {
394 395
	$user_urn = GeniHRN::Generate("aptlab.net", "user", $user_uid);
	$user_hrn = "aptlab.${user_uid}";
396
	$geniuser = GeniUser->Lookup($user_urn, 0);
397 398
    }
}
399
if (!defined($geniuser)) {
400 401 402
    if ($localuser) {
	fatal("Could not lookup local user $user_urn");
    }
403
    
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    #
    # 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");
    }
421 422 423 424 425 426 427 428
    my $blob = {"urn"      => $user_urn,
		"hrn"      => $user_hrn,
		"email"    => $user_email,
		"showuuid" => 1};
    if ($MAINSITE) {
	$blob->{'useaptca'} = 1;
    }
    my $certificate = GeniCertificate->Create($blob);
429 430 431 432 433 434 435 436 437 438
    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 B Stoller's avatar
Leigh B Stoller committed
439
    # Setup browser ssh.
440
    #
441 442 443
    system("$SSHSETUP " . $geniuser->uuid());
    fatal("Could not create ssh key pair")
	if ($?);
444 445 446 447
}
my $user_uuid = $geniuser->uuid();
# So we know this user has dome something lately.
$geniuser->BumpActivity();
448

449 450 451
if ($localuser) {
    my $emulab_user = $geniuser->emulab_user();
    if ($emulab_user->IsNonLocal()) {
452 453
	#
	# A user created from a Geni certificate via geni-login. We
454 455
	# asked for the current ssh keys from the MA when they logged
	# in, but we ask again to make sure have the latest keys.
456
	#
457
	system("$UPDATEGENIUSER -s " . $emulab_user->uid());
458
	if (0) {
459 460
	    fatal("Could not update ssh keys for nonlocal user");
	}
461 462 463

	# Nonlocal users get the holding project.
	$pid = "CloudLab";
464
    }
465
    elsif (defined($sshkey) && !$emulab_user->LookupSSHKey($sshkey)) {
466 467 468 469 470 471
	#
	# 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.
	#
	
472
	#
473 474 475 476
	# 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
477 478 479 480 481
	# 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.
482
	#
483 484 485
	my ($fh, $keyfile) = tempfile(UNLINK => 0);
	print $fh $sshkey;

486
	if (system("$ADDPUBKEY -a -u $user_uid -f $keyfile")) {
487 488 489 490 491
	    fatal("Could not add new ssh pubkey");
	}
	close($fh);
	unlink($keyfile);
    }
492 493 494 495 496 497 498 499 500 501 502 503 504 505
    #
    # 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");
    }
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

    # 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");
    }
    if (!$project->AccessCheck($emulab_user, TB_PROJECT_CREATEEXPT)) {
	fatal("No permission to create experiments in project $pid");
    }
    $pid = $project->pid();
}
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
524
	# interface. We allow key reuse for existing users, see above.
525 526 527 528 529 530
	#
	$geniuser->DeleteKeys();
	$geniuser->AddKey($sshkey);
    }
    # Guest users get a holding project.
    $pid = "aptguests";
531
}
Leigh B Stoller's avatar
Leigh B Stoller committed
532
# There will be "internal" keys cause we pass the flag asking for them.
533
my @sshkeys;
Leigh B Stoller's avatar
Leigh B Stoller committed
534
if ($geniuser->GetKeyBundle(\@sshkeys, 1) < 0 || !@sshkeys) {
535 536 537
    fatal("No ssh keys to use for $geniuser!");
}

538 539 540
# Generate the extra credentials that tells the backend this experiment
# can access the datasets.
my @dataset_credentials = ();
541 542 543 544 545 546 547
if (defined($profile)) {
    my $retval = CreateDatasetCreds($rspecstr,
				    $profile->pid(), $geniuser, 
				    \$errmsg, \@dataset_credentials);
    if ($retval) {
	($retval < 0 ? fatal($errmsg) : UserError($errmsg));
    }
548 549
}

550
#
551 552 553
#
# Now generate a slice registration and credential
#
554 555
my $safe_uid    = $user_uid; $safe_uid =~ s/_/-/;
my $slice_id    = $safe_uid . "-QV" . TBGetUniqueIndex('next_quickvm', 1);
556
my $slice_urn   = GeniHRN::Generate("${OURDOMAIN}:${pid}", "slice", $slice_id);
557 558
my $slice_hrn   = "${PGENIDOMAIN}.${slice_id}";
my $SERVER_NAME = (exists($ENV{"SERVER_NAME"}) ? $ENV{"SERVER_NAME"} : "");
559

560
print STDERR "\n";
561 562
print STDERR "User:    $user_urn\n";
print STDERR "Email:   $user_email" . (!$localuser ? " (guest)" : "") . "\n";
563 564 565
if (defined($profile)) {
    print STDERR "Profile: " . $profile->name() . ":${version}\n";
}
566 567
print STDERR "Slice:   $slice_urn\n";
print STDERR "Server:  $SERVER_NAME\n";
568
print STDERR "Cluster: $CMURN\n";
Leigh B Stoller's avatar
Leigh B Stoller committed
569
print STDERR "\n";
570 571
print STDERR "$rspecstr\n";

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
#
# Make sure slice is unique. Probably retry here at some point. 
#
if (GeniSlice->Lookup($slice_hrn) || GeniSlice->Lookup($slice_urn)) {
    fatal("Could not form a unique slice name");
}
	    
#
# 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.
my $slice = GeniSlice->Create($slice_certificate,
			      $geniuser, $sa_authority, undef, 1);
if (!defined($slice)) {
    $slice_certificate->Delete();
    fatal("Could not create new slice object for $slice_urn");
}
598 599
# These get quick expirations, unless it is a real user.
if ($slice->SetExpiration(time() + (($localuser ? 16 : 3) * 3600)) != 0) {
600 601 602 603 604
    $slice->Delete();
    fatal("Could not set the slice expiration for $slice_urn");
}
my $slice_uuid = $slice->uuid();

605
#
606
# Generate credentials we need.
607
#
608
my ($slice_credential, $speaksfor_credential) =
609
    APT_Geni::GenCredentials($slice, $geniuser);
610 611
if (! (defined($speaksfor_credential) &&
       defined($slice_credential))) {
612
    $slice->Delete();
613
    fatal("Could not generate credentials");
614 615
}

616
#
617
# Got this far, lets create a quickvm record.
618
#
619
my $quickvm_uuid = (defined($quickuuid) ? $quickuuid : NewUUID());
620 621 622
if (!defined($quickvm_uuid)) {
    fatal("Could not generate a new uuid");
}
623 624 625 626 627 628 629 630 631
my $blob = {'uuid'         => $quickvm_uuid,
	    'profile_id'   => $profileid,
	    'profile_version' => $version,
	    'slice_uuid'   => $slice_uuid,
	    'creator'      => $geniuser->uid(),
	    'creator_idx'  => $geniuser->idx(),
	    'creator_uuid' => $geniuser->uuid(),
	    'aggregate_urn'=> $CMURN,
	    'status'       => "created",
632 633
	    'servername'   => $SERVER_NAME,
	    'rspec'        => $rspecstr,
634 635 636 637 638 639
};
if (defined($project)) {
    $blob->{"pid"}     = $project->pid();
    $blob->{"pid_idx"} = $project->pid_idx();
}
my $instance = APT_Instance->Create($blob);
Leigh B Stoller's avatar
Leigh B Stoller committed
640
if (!defined($instance)) {
641
    $slice->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
642
    fatal("Could not create instance record for $quickvm_uuid");
643
}
644 645 646 647 648 649 650
#
# Create a webtask so that we can store additional information about
# the sliver while we wait. No worries if this fails.
#
$webtask = WebTask->Create($instance->uuid());
$webtask->AutoStore(1)
    if (defined($webtask));
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

#
# Exit and let caller poll for status.
#
if (!$debug) {
    my $child = fork();
    if ($child) {
	# Parent exits but avoid libaudit email.
	exit(0);
    }
    # Let parent exit;
    sleep(2);
    # All of the logging magic happens in here.
    libaudit::AuditFork();
}
666 667 668
# Bind the process id.
$webtask->SetProcessID($PID)
    if (defined($webtask));
669 670

#
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
# This creates the sliver and starts it. We have to watch for the server
# being to busy.
#
my $tries = 15;
my $response;

while (1) {
    $response =
	Genixmlrpc::CallMethod($cmurl, undef,
			       "CreateSliver",
			       { "slice_urn"   => $slice_urn,
				 "rspec"       => $rspecstr,
				 "keys"        =>
				     [{'urn'   => $user_urn,
				       'login' => $user_uid,
				       'keys'  => \@sshkeys }],
				     "credentials" =>
				     [$slice_credential->asString(),
				      $speaksfor_credential->asString(),
				      @dataset_credentials
				     ]});

    if (!defined($response) || $response->code() != GENIRESPONSE_SUCCESS) {
	if (defined($response) &&
	    $response->code() == GENIRESPONSE_SERVER_UNAVAILABLE &&
	    $tries >= 0) {
	    print STDERR "Server reports too busy, waiting a while ...\n";
	    sleep(int(rand(20)) + 10);
	    $tries--;
	    next;
701
	}
702 703 704 705 706 707 708 709 710 711
	$slice->Delete();
	$instance->SetStatus("failed");
	if (defined($webtask)) {
	    if (defined($response)) {
		$webtask->output($response->output());
		$webtask->Exited($response->code());
	    }
	    else {
		$webtask->Exited(1);
	    }
712
	}
713 714
	fatal("CreateSliver failed: ".
	      (defined($response) ? $response->output() : "") . "\n");
715
    }
716
    last;
717 718 719 720 721 722 723 724
}

#
# We are going to use the manifests table.
#
my $manifest = $response->value()->[1];
if (!defined($manifest)) {
    $slice->UnLock();
725
    $webtask->Exited(1) if (defined($webtask));
Leigh B Stoller's avatar
Leigh B Stoller committed
726
    $instance->SetStatus("failed");
727 728
    fatal("Could not find the manifest in the response!");
}
Leigh B Stoller's avatar
Leigh B Stoller committed
729 730
$instance->SetStatus("provisioned");
$instance->SetManifest($manifest);
731 732 733 734

#
# but have to wait for the sliver to be ready, which means polling.
#
Leigh B Stoller's avatar
Leigh B Stoller committed
735
my $seconds  = 1500;
736 737 738
my $interval = 15;
my $ready    = 0;
my $failed   = 0;
739
my $public_url;
740 741
# Shorten default timeout now.
Genixmlrpc->SetTimeout(60);
742 743 744 745 746 747

while ($seconds > 0) {
    sleep($interval);
    $seconds -= $interval;
    
    my $response =
748
	Genixmlrpc::CallMethod($cmurl, undef,
749 750 751 752 753 754 755 756
			       "SliverStatus",
			       { "slice_urn"   => $slice_urn,
				 "credentials" =>
				     [$slice_credential->asString(),
				      $speaksfor_credential->asString()]});

    if (!defined($response) || !defined($response->value()) ||
	($response->code() != GENIRESPONSE_SUCCESS &&
757
	 $response->code() != GENIRESPONSE_SERVER_UNAVAILABLE &&
758
	 $response->code() != GENIRESPONSE_BUSY)) {
759 760 761
	print STDERR "SliverStatus failed";
	if (defined($response)) {
	    print STDERR ": " . $response->output();
762
	    if (defined($webtask)) {
763 764 765 766 767 768 769 770
		if ($response->output() =~ /read timeout/) {
		    $webtask->output("Lost contact with the aggregate. " .
				     "Possibly a network failure, ".
				     "please try again later.");
		}
		else {
		    $webtask->output($response->output());
		}
771
	    }
772 773 774 775
	}
	print STDERR "\n";
	$failed = 1;
	last;
776 777
    }
    next
778 779
	if ($response->code() == GENIRESPONSE_BUSY ||
	    $response->code() == GENIRESPONSE_SERVER_UNAVAILABLE);
780 781

    my $blob = $response->value();
782 783 784 785 786 787 788 789 790 791 792 793 794
    #
    # Convert to something smaller, with info the web interface
    # cares about. 
    #
    if (defined($webtask)) {
	my $statusblob = {};
	foreach my $urn (keys(%{$blob->{'details'}})) {
	    my $details = $blob->{'details'}->{$urn};
	    my $node_id = $details->{'client_id'};
	    $statusblob->{$node_id} = $details;
	}
	$webtask->sliverstatus($statusblob)
    }
795 796 797
    if (exists($blob->{'public_url'})) {
	$public_url = $blob->{'public_url'};
    }
798 799 800 801 802 803
    if ($blob->{'status'} eq "ready") {
	$ready = 1;
	last;
    }
    elsif ($blob->{'status'} eq "failed") {
	$failed = 1;
804 805
	$webtask->output("Experiment setup on $aggregate failed")
	    if (defined($webtask));
806 807 808
	last;
    }
}
809

810
# Print this message first so its obvious.
811
if ($failed || !$ready) {
Leigh B Stoller's avatar
Leigh B Stoller committed
812
    $instance->SetStatus("failed");
Leigh B Stoller's avatar
Leigh B Stoller committed
813 814 815 816
    if ($failed) {
	print STDERR "*** $slice_urn failed.\n\n"; 	
    }
    elsif (!$ready) {
817
	print STDERR "*** $slice_urn timed out.\n\n";
818 819
	$webtask->output("Experiment setup on $aggregate timed out")
	    if (defined($webtask));
820
    }
821
    $webtask->Exited(1) if (defined($webtask));
822 823 824
}
else {
    $instance->SetStatus("ready");
825
    $webtask->Exited(0) if (defined($webtask));
826
}
827 828 829 830 831 832 833 834
print STDERR "$slice_urn\n";
if (defined($public_url)) {
    print STDERR "$public_url\n";
    $instance->SetPublicURL($public_url);
}
print STDERR "\n";
print STDERR "$manifest\n\n";

835 836 837
$slice->UnLock();
exit(0);

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
#
# Create credentials to access datasets.
#
sub CreateDatasetCreds($$$$$)
{
    my ($xml, $pid, $user, $pmsg, $pref) = @_;
    my @credentials = ();
    
    my $rspec = GeniXML::Parse($xml);
    if (! defined($rspec)) {
	print STDERR "CreateDatasetCreds: Could not parse rspec\n";
	return -1;
    }
    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	foreach my $blockref (GeniXML::FindNodesNS("n:blockstore",
						   $ref,
				   $GeniXML::EMULAB_NS)->get_nodelist()) {
	    my $leaseurn = GeniXML::GetText("persistent", $blockref);

	    #
	    # We only care about datasets here, we let the backend
	    # do the error checking on ephemeral blockstores.
	    #
	    next
		if (!defined($leaseurn));
	    
	    my ($authority, $type, $id) = GeniHRN::Parse($leaseurn);
	    #
	    # Separate project from name; this is how the rspec specifies
	    # the dataset they want, since it might be in another project
	    #
	    if ($id =~ /^([-\w]+)\/\/(.+)$/) {
		$pid = $1;
		$id  = $2;
	    }
	    my $dataset = APT_Dataset->Lookup("$pid/$id");
	    if (!defined($dataset)) {
875 876 877 878 879
		$dataset = APT_Dataset->LookupByRemoteURN($leaseurn);
		if (!defined($dataset)) {
		    $$pmsg = "Persistent dataset '$pid/$id' does not exist";
		    return 1;
		}
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	    }
	    my $certificate = $dataset->GetCertificate();
	    if (!defined($certificate)) {
		$$pmsg = "No certificate for dataset '$pid/$id'";
		return -1;
	    }
	    my $credential =
		APT_Geni::GenCredentials($certificate, $geniuser,
					 ["blockstores"]);
	    if (!defined($credential)) {
		$$pmsg = "Could not create credential for dataset '$pid/$id'";
		return -1;
	    }
	    push(@credentials, $credential->asString());
	}
    }
    @$pref = @credentials;
    return 0;
}

900 901 902
sub fatal($) {
    my ($mesg) = $_[0];

903 904 905
    print STDERR Dumper($xmlparse)
	if (defined($xmlparse));

906 907 908 909 910 911 912 913 914 915 916 917 918
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}
sub UserError($) {
    my($mesg) = $_[0];

    AuditAbort()
	if (!$debug);
    print $mesg;
    exit(1);
}

919