APT_Instance.pm.in 105 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2019 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh Stoller committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
package APT_Instance;

use strict;
use Carp;
28 29
use English;
use Data::Dumper;
30
use Date::Parse;
31
use File::Temp qw(tempfile tmpnam);
32
use JSON;
Leigh Stoller's avatar
Leigh Stoller committed
33
use Exporter;
34
use vars qw(@ISA @EXPORT $AUTOLOAD
35 36 37
	    $RECORDHISTORY_TERMINATED $RECORDHISTORY_EXPIRED
	    $APT_HOLDINGPROJECT $CLOUD_HOLDINGPROJECT);

Leigh Stoller's avatar
Leigh Stoller committed
38
@ISA    = "Exporter";
39 40 41 42 43

# RecordHistory flags.
$RECORDHISTORY_TERMINATED	= 0x00;
$RECORDHISTORY_EXPIRED		= 0x01;

44 45 46 47 48 49
# Names of the holding projects.
$APT_HOLDINGPROJECT   = "aptguests";
$CLOUD_HOLDINGPROJECT = "CloudLab";

@EXPORT = qw($RECORDHISTORY_TERMINATED $RECORDHISTORY_EXPIRED
             $APT_HOLDINGPROJECT $CLOUD_HOLDINGPROJECT);
Leigh Stoller's avatar
Leigh Stoller committed
50 51 52 53 54

# Must come after package declaration!
use EmulabConstants;
use emdb;
use libtestbed;
55
use Brand;
56
use APT_Profile;
57
use APT_Aggregate;
58 59 60 61
use APT_Geni;
use Genixmlrpc;
use GeniResponse;
use GeniCertificate;
Leigh Stoller's avatar
Leigh Stoller committed
62
use GeniCredential;
63
use GeniUser;
64
use GeniHRN;
65
use GeniXML;
66
use GeniImage;
67
use WebTask;
68
use Logfile;
Leigh Stoller's avatar
Leigh Stoller committed
69 70 71 72 73
use overload ('""' => 'Stringify');

# Configure variables
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
74
my $TBAUDIT       = "@TBAUDITEMAIL@";
75
my $OURDOMAIN     = "@OURDOMAIN@";
76
my $GENEXTENDCRED = "$TB/sbin/protogeni/genextendcred";
77
my $MANAGEDATASET = "$TB/bin/manage_dataset";
78
my $MANAGEIMAGES  = "$TB/bin/manage_images";
79
my $GENIUSER      = "geniuser";
80
my $MAINSITE      = @TBMAINSITE@;
81
my $PROTOGENI_LOCALUSER= @PROTOGENI_LOCALUSER@;
Leigh Stoller's avatar
Leigh Stoller committed
82 83 84

# Cache of instances to avoid regenerating them.
my %instances  = ();
85
BEGIN { use emutil; emutil::AddCache(\%instances); }
Leigh Stoller's avatar
Leigh Stoller committed
86 87
my $debug      = 0;

88
# Debugging
89
my $usemydevtree  = ($MAINSITE ? 0 : 0);
90 91 92 93 94 95
sub devurl($)
{
    my ($cmurl) = @_;

    if ($usemydevtree) {
	$cmurl =~ s/protogeni/protogeni\/stoller/;
96
#	$cmurl =~ s/12369/12396/;
97 98 99
    }
    return $cmurl;
}
100

Leigh Stoller's avatar
Leigh Stoller committed
101 102 103
#
# Lookup by uuid.
#
104
sub Lookup($$)
Leigh Stoller's avatar
Leigh Stoller committed
105
{
106 107
    my ($class, $token) = @_;
    my $query_result;
Leigh Stoller's avatar
Leigh Stoller committed
108

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    if ($token =~ /^([-\w]*),([-\w]*)$/ ||
	$token =~ /^([-\w]*)\/([-\w]*)$/) {

	$query_result =
	    DBQueryWarn("select uuid from apt_instances ".
			"where pid='$1' and name='$2'");
	return undef
	    if (! (defined($query_result) && $query_result->numrows));

	my ($uuid) = $query_result->fetchrow_array();
	
	# Look in cache first
	return $instances{$uuid}
	    if (exists($instances{$uuid}));
	
	$query_result =
	    DBQueryWarn("select * from apt_instances where uuid='$uuid'");
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
128 129 130
	# Look in cache first
	return $instances{$token}
            if (exists($instances{$token}));
Leigh Stoller's avatar
Leigh Stoller committed
131

132 133 134 135 136 137
	$query_result =
	    DBQueryWarn("select * from apt_instances where uuid='$token'");
    }
    else {
	return undef;
    }
Leigh Stoller's avatar
Leigh Stoller committed
138 139 140
    return undef
	if (!$query_result || !$query_result->numrows);

141 142 143 144
    my $self              = {};
    $self->{'INSTANCE'}   = $query_result->fetchrow_hashref();
    $self->{'BRAND'}      = Brand->Create($self->{'INSTANCE'}->{'servername'});
    $self->{'HASH'}       = {};
145
    $self->{'AGGREGATES'} = {};
146
    $self->{'WEBTASK'}    = undef;
Leigh Stoller's avatar
Leigh Stoller committed
147
    bless($self, $class);
148 149 150 151

    #
    # Lookup existing aggregates.
    #
152
    $self->{'AGGREGATES'} = APT_Instance::Aggregate->LookupForInstance($self);
Leigh Stoller's avatar
Leigh Stoller committed
153 154
    
    # Add to cache. 
155
    $instances{$self->uuid()} = $self;
Leigh Stoller's avatar
Leigh Stoller committed
156 157 158 159 160 161
    
    return $self;
}

AUTOLOAD {
    my $self  = $_[0];
162
    my $type  = ref($self) or confess "$self is not an object";
Leigh Stoller's avatar
Leigh Stoller committed
163 164 165 166 167 168 169
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'INSTANCE'}->{$name})) {
	return $self->{'INSTANCE'}->{$name};
    }
170 171 172 173 174 175 176 177 178
    # Or it is for a local storage slot.
    if ($name =~ /^_.*$/) {
	if (scalar(@_) == 2) {
	    return $self->{'HASH'}->{$name} = $_[1];
	}
	elsif (exists($self->{'HASH'}->{$name})) {
	    return $self->{'HASH'}->{$name};
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
179 180 181
    carp("No such slot '$name' field in class $type");
    return undef;
}
182 183 184
sub Brand($)	{ return $_[0]->{'BRAND'}; }
sub isAPT($)	{ return $_[0]->Brand()->isAPT() ? 1 : 0; }
sub isCloud($)	{ return $_[0]->Brand()->isCloud() ? 1 : 0; }
185
sub isPNet($)	{ return $_[0]->Brand()->isPNet() ? 1 : 0; }
186
sub isPowder($)	{ return $_[0]->Brand()->isPowder() ? 1 : 0; }
187 188
sub AggregateList($) { return values(%{ $_[0]->{'AGGREGATES'} }); }
sub AggregateHash($) { return $_[0]->{'AGGREGATES'}; }
Leigh Stoller's avatar
Leigh Stoller committed
189

190 191 192 193 194 195 196 197 198 199 200 201
sub Start($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();

    DBQueryWarn("update apt_instances set started=now() ".
		"where uuid='$uuid'")
	or return -1;

    return Refresh($self);
}

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
#
# Grab the webtask. Backwards compat mode, see if there is one associated
# with the object, use that. Otherwise create a new one.
#
sub webtask($)
{
    my ($self) = @_;
    my $webtask;

    return $self->{'WEBTASK'}
        if (defined($self->{'WEBTASK'}));

    if (defined($self->webtask_id())) {
	$webtask = WebTask->Lookup($self->webtask_id());
    }
    if (!defined($webtask)) {
	$webtask = WebTask->LookupByObject($self->uuid());
	if (!defined($webtask)) {
	    $webtask = WebTask->Create();
	    return undef
		if (!defined($webtask));
	}
	$self->Update({"webtask_id" => $webtask->task_id()}) == 0
	    or return undef;
    }
    $self->{'WEBTASK'} = $webtask;
    return $webtask;
}

Leigh Stoller's avatar
Leigh Stoller committed
231 232 233 234
# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

235 236 237 238
    $self->{'INSTANCE'}   = undef;
    $self->{'BRAND'}      = undef;
    $self->{'AGGREGATES'} = undef;
    $self->{'HASH'}       = undef;
239
    $self->{'WEBTASK'}    = undef;
Leigh Stoller's avatar
Leigh Stoller committed
240 241
}

242 243 244 245 246 247 248
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

249 250 251 252 253 254 255 256 257 258 259
    delete($instances{$self->uuid()});
}
#
# We use this in long running daemons, since we have a circular dependency
# that causes the perl GC to leak memory. Normally not a problem, but the
# aptevent_daemon runs for a long time! 
#
sub Purge($)
{
    my ($self) = @_;

260 261
    #
    # Break circular dependency so that the object is released
262
    # (the aggregate objects point back to the instance).
263
    #
264 265
    $self->{'AGGREGATES'} = undef;
    $self->Flush();
266 267
}

Leigh Stoller's avatar
Leigh Stoller committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $uuid = $self->uuid();
    
    my $query_result =
	DBQueryWarn("select * from apt_instances where uuid='$uuid'");

    return -1
	if (!$query_result || !$query_result->numrows);

    $self->{'INSTANCE'} = $query_result->fetchrow_hashref();

    return 0;
}

#
# Create an Instance
#
294
sub Create($$$)
Leigh Stoller's avatar
Leigh Stoller committed
295
{
296
    my ($class, $argref, $perrmsg) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
297 298 299 300 301 302 303 304 305
    my $uuid;

    if (exists($argref->{'uuid'})) {
	$uuid = $argref->{'uuid'};
	delete($argref->{'uuid'});
    }
    else {
	$uuid = NewUUID();
    }
306 307
    my $pid_idx = $argref->{'pid_idx'};
    my $name    = $argref->{'name'};
Leigh Stoller's avatar
Leigh Stoller committed
308 309 310 311 312 313 314 315 316 317 318 319

    #
    # The uuid has to be unique, so lock the table for the check/insert.
    #
    DBQueryWarn("lock tables apt_instances write")
	or return undef;

    my $query_result =
	DBQueryWarn("select uuid from apt_instances where uuid='$uuid'");

    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
320 321 322 323 324 325 326 327 328 329
	$$perrmsg = "Instance uuid $uuid already exists!";
	return undef;
    }
    $query_result =
	DBQueryWarn("select name from apt_instances ".
		    "where name='$name' and pid_idx='$pid_idx'");

    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
	$$perrmsg = "Instance name already in use!";
Leigh Stoller's avatar
Leigh Stoller committed
330 331
	return undef;
    }
332 333 334 335 336 337 338 339 340
    my $sets = "created=now(),uuid='$uuid'";
    if (exists($argref->{"start_at"}) && defined($argref->{"start_at"})) {
	$sets .= ", start_at=FROM_UNIXTIME(" . $argref->{"start_at"} . ")";
	delete($argref->{"start_at"});
    }
    else {
	$sets .= ", started=created";
    }
    my $query = "insert into apt_instances set ${sets}, ".
Leigh Stoller's avatar
Leigh Stoller committed
341 342 343 344 345
	join(",", map("$_=" .
		      DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
346
	$$perrmsg = "Error inserting new apt_instance record for $uuid!";
Leigh Stoller's avatar
Leigh Stoller committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360
	return undef;
    }
    DBQueryWarn("unlock tables");
    return Lookup($class, $uuid);
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uuid  = $self->uuid();
361 362
    my $pid   = $self->pid();
    my $name  = $self->name();
Leigh Stoller's avatar
Leigh Stoller committed
363

364
    return "[APT_Instance: $pid,$name]";
Leigh Stoller's avatar
Leigh Stoller committed
365 366
}

367 368
sub LookupBySlice($$)
{
369 370
    my ($class, $token) = @_;
    my $slice_uuid;
371

372 373 374 375 376 377 378 379 380
    if ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$slice_uuid = $token;
    }
    elsif (GeniHRN::IsValid($token)) {
	#
	# We should put the slice_urn into the apt_instances table.
	#
	require GeniSlice;
	my $slice = GeniSlice->Lookup($token);
381
	return undef
382 383
	    if (!defined($slice));
	$slice_uuid = $slice->uuid();
384
	$slice->Flush();
385 386 387
    }
    else {
	return undef;
388
    }
389

390 391 392
    my $query_result =
	DBQueryWarn("select uuid from apt_instances ".
		    "where slice_uuid='$slice_uuid'");
393
	
394 395 396 397
    return undef
	if (!$query_result || !$query_result->numrows);

    my ($uuid) = $query_result->fetchrow_array();
398 399
    my $foo = APT_Instance->Lookup($uuid);
    return $foo;
400 401
}

Leigh Stoller's avatar
Leigh Stoller committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415
#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid = $self->uuid();

    my $query = "update apt_instances set ".
416 417 418 419
	join(",", map("$_=" .
		      (defined($argref->{$_}) ?
		       DBQuoteSpecial($argref->{$_}) : "NULL"),
		      keys(%{$argref})));
Leigh Stoller's avatar
Leigh Stoller committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433

    $query .= " where uuid='$uuid'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

sub Delete($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();

434
    foreach my $agg ($self->AggregateList()) {
435 436 437
	$agg->Delete() == 0
	    or return -1;
    }
438 439 440
    DBQueryWarn("delete from apt_deferred_instances where uuid='$uuid'") or
	return -1;

441 442
    # We do not "own" the webtask until create_sliver exits successfully.
    $self->webtask()->Delete() if (defined($self->{'WEBTASK'}));
443
    
Leigh Stoller's avatar
Leigh Stoller committed
444 445 446 447 448 449
    DBQueryWarn("delete from apt_instances where uuid='$uuid'") or
	return -1;

    return 0;
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
#
# Lock and unlock operate on the underlying slice.
#
sub Lock($)
{
    my ($self) = @_;
    my $slice  = $self->GetGeniSlice();
    if (!defined($slice)) {
	return -1;
    }
    return $slice->Lock();
}
sub Unlock($)
{
    my ($self) = @_;
    my $slice  = $self->GetGeniSlice();
    if (!defined($slice)) {
	return -1;
    }
    return $slice->UnLock();
}
471 472 473 474 475 476 477 478 479
sub Locked($)
{
    my ($self) = @_;
    my $slice  = $self->GetGeniSlice();
    if (!defined($slice)) {
	return 0;
    }
    return $slice->locked();
}
480

Leigh Stoller's avatar
Leigh Stoller committed
481 482 483 484 485 486 487 488 489 490
sub SetStatus($$)
{
    my ($self,$status) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid = $self->uuid();

491 492 493 494
    DBQueryWarn("update apt_instances set ".
		"  status='$status',status_timestamp=now() ".
		"where uuid='$uuid'")
	or return -1;
Leigh Stoller's avatar
Leigh Stoller committed
495 496 497 498

    $self->{'INSTANCE'}->{'status'} = $status;
    return 0;
    
Leigh Stoller's avatar
Leigh Stoller committed
499
}
500

501 502 503 504 505 506 507 508 509 510
sub SetAggregateStatus($$)
{
    my ($self, $status) = @_;

    foreach my $agg ($self->AggregateList()) {
	$agg->SetStatus($status);
    }
    return 0;
}

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
sub ActiveAggregateList($)
{
    my ($self) = @_;
    my @result = ();

    foreach my $agg ($self->AggregateList()) {
	push(@result, $agg)
	    if ($agg->status() ne "terminated" &&
		$agg->status() ne "deferred");
    }
    return @result;
}
sub DeferredAggregateList($)
{
    my ($self) = @_;
    my @result = ();

    foreach my $agg ($self->AggregateList()) {
	push(@result, $agg)
	    if ($agg->status() eq "deferred");
    }
    return @result;
}

Leigh Stoller's avatar
Leigh Stoller committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
sub SetPublicURL($$)
{
    my ($self,$url) = @_;
    my $safe_url = DBQuoteSpecial($url);

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid = $self->uuid();

    DBQueryWarn("update apt_instances set public_url=$safe_url ".
		"where uuid='$uuid'") or
	return -1;

    $self->{'INSTANCE'}->{'public_url'} = $url;
    return 0;
    
Leigh Stoller's avatar
Leigh Stoller committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
}
sub SetManifest($$)
{
    my ($self,$manifest) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid = $self->uuid();
    my $safe_manifest = DBQuoteSpecial($manifest);    

    DBQueryWarn("update apt_instances set manifest=$safe_manifest ".
		"where uuid='$uuid'") or
	return -1;

    $self->{'INSTANCE'}->{'manifest'} = $manifest;
    return 0;
571 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 598 599 600 601 602 603 604 605 606 607 608
sub MarkCanceled($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid = $self->uuid();

    DBQueryWarn("update apt_instances set ".
		"  canceled=1,canceled_timestamp=now() ".
		"where uuid='$uuid'")
	or return -1;

    $self->{'INSTANCE'}->{'canceled'} = 1;
    return 0;
}
# We need to bypass the in memory state for this.
sub IsCanceled($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();

    my $query_result =
	DBQueryWarn("select canceled from apt_instances ".
		    "where uuid='$uuid'");
	
    return -1
	if (!$query_result);
    return 0
	if (!$query_result->numrows);
    my ($canceled) = $query_result->fetchrow_array();
    return $canceled;
}

609 610 611 612 613 614 615 616 617 618 619 620 621
#
# Set to use the logfile. 
#
sub SetLogFile($$)
{
    my ($self, $logfile) = @_;

    return -1
	if ($self->Update({'logfileid' => $logfile->logid()}));

    return 0;
}

622 623 624 625 626
#
# Set/Clear the lockdown bits.
#
sub SetLockdown($$$)
{
627
    my ($self,$admin,$user) = @_;
628 629 630 631 632 633

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid = $self->uuid();
634 635
    $admin = ($admin ? 1 : 0);
    $user  = ($user ? 1 : 0);
636

637 638
    DBQueryWarn("update apt_instances set ".
		" admin_lockdown='$admin',user_lockdown='$user' ".
639 640 641
		"where uuid='$uuid'") or
	return -1;

642 643
    $self->{'INSTANCE'}->{"admin_lockdown"} = $admin;
    $self->{'INSTANCE'}->{"user_lockdown"}  = $user;
644 645 646
    return 0;
}

647 648 649 650 651 652 653 654 655 656 657 658 659
#
# Set/Clear the panic flag.
#
sub SetPanic($$)
{
    my ($self,$clear) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uuid  = $self->uuid();
    my $value = ($clear ? 0 : 1);
660
    my $stamp = ($clear ? "NULL" : "now()");
661

662 663
    DBQueryWarn("update apt_instances set ".
		"  paniced=${value},paniced_timestamp=${stamp} ".
664 665 666 667
		"where uuid='$uuid'") or
	return -1;

    $self->{'INSTANCE'}->{"paniced"} = $value;
668
    $self->{'INSTANCE'}->{"paniced_timestamp"} = ($clear ? undef : time());
669 670 671
    return 0;
}

672 673 674 675 676 677 678 679
# Return a URL for the status page.
sub webURL($)
{
    my ($self) = @_;
    my $link = $self->Brand()->wwwBase();
    $link    = $link . "/status.php?uuid=" . $self->uuid();

    return $link;
Leigh Stoller's avatar
Leigh Stoller committed
680
}
681 682 683 684 685 686 687 688
sub adminURL($)
{
    my ($self) = @_;
    my $link = $self->Brand()->wwwBase();
    $link    = $link . "/adminextend.php?uuid=" . $self->uuid();

    return $link;
}
Leigh Stoller's avatar
Leigh Stoller committed
689

690 691 692 693 694 695 696 697 698 699 700
#
# Find the profile for this instance.
#
sub Profile($)
{
    my ($self) = @_;
    
    return APT_Profile->Lookup($self->profile_id(),
			       $self->profile_version());
}

701 702 703 704
#
# Record a history entry.
# We do this when the instance is terminated. 
#
705
sub RecordHistory($$)
706
{
707
    my ($self, $flags) = @_;
708
    my $uuid = $self->uuid();
709
    my $expired = ($flags ? 1 : 0);
710

711 712 713 714
    DBQueryWarn("replace into apt_instance_aggregate_history ".
		"select * from apt_instance_aggregates where uuid='$uuid'")
	or return -1;

715
    DBQueryWarn("replace into apt_instance_history ".
716
		"select uuid,name,profile_id,profile_version,slice_uuid, ".
717
		"       creator,creator_idx,creator_uuid,pid,pid_idx, ".
718
		"       gid,gid_idx, ".
719
		"       aggregate_urn,public_url,logfileid, ".
720
		"       created,start_at,started,stop_at,now(),$expired, ".
721
		"       extension_count,extension_days,extension_hours, ".
722
		"       physnode_count,virtnode_count, ".
723
		"       servername,portal,repourl,reponame,reporef,repohash, ".
724
		"       rspec,script,params,manifest ".
725 726 727 728 729 730
		" from apt_instances where uuid='$uuid'")
	or return -1;

    return 0;
}

731 732 733 734 735 736 737 738 739
sub RecordError($$$)
{
    my ($self, $exitcode, $message) = @_;
    my $uuid = $self->uuid();
    my $safe_message = DBQuoteSpecial($message);

    DBQueryWarn("replace into apt_instance_failures ".
		"select uuid,name,profile_id,profile_version,slice_uuid, ".
		"       creator,creator_idx,creator_uuid,pid,pid_idx, ".
740
		"       gid,gid_idx, ".
741
		"       created,start_at,started,stop_at,'$exitcode', ".
742
		"       $safe_message,public_url,logfileid,portal ".
743 744 745 746 747 748
		" from apt_instances where uuid='$uuid'")
	or return -1;

    return 0;
}

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
#
# Locate Geni objects for creator and slice.
#
sub GetGeniSlice($)
{
    my ($self) = @_;
    require GeniSlice;
    
    return GeniSlice->Lookup($self->slice_uuid());
}

sub GetGeniUser($)
{
    my ($self) = @_;
    require GeniUser;
    
    return GeniUser->Lookup($self->creator_uuid(), 1);
}

sub GetGeniAuthority($)
{
    my ($self) = @_;
    require GeniAuthority;

    return APT_Geni::GetAuthority($self->aggregate_urn());
}

776 777 778 779 780 781 782 783
sub GetProject($)
{
    my ($self) = @_;
    require Project;
    
    return Project->Lookup($self->pid_idx());
}

784 785 786 787 788 789 790 791
sub GetGroup($)
{
    my ($self) = @_;
    require Group;
    
    return Group->Lookup($self->gid_idx());
}

792 793 794 795 796 797 798 799 800 801 802
#
# Map an instance to the local experiment (when its running locally)
#
sub LocalExperiment($)
{
    my ($self) = @_;
    require Experiment;
    
    return Experiment->Lookup($self->slice_uuid());
}

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
#
# Warn creator that the experiment is going to expire. This is hooked
# in from the sa_daemon, so we can send a message that is less geni like
# and more APT/Cloud.
#
sub WarnExpiring($$)
{
    my ($self, $when) = @_;
    require GeniDB;
    require GeniSlice;

    my $slice     = GeniSlice->Lookup($self->slice_uuid());;
    if (!defined($slice)) {
	print STDERR "WarnExpiring: No slice for $self\n";
	return -1;
    }
    my $slicename = $slice->slicename();
    my $geniuser  = GeniUser->Lookup($slice->creator_uuid(), 1);
    if (!defined($geniuser)) {
	print STDERR "WarnExpiring: No creator for $self\n";
	return -1;
    }
    if (!defined($geniuser->email())) {
	print STDERR "WarnExpiring: no email address for $geniuser\n";
	return 0;
    }
829
    my $link = $self->webURL();
830 831 832 833 834 835 836 837 838
    
    $self->Brand()->SendEmail($geniuser->email(),
		     "Your experiment is expiring soon!",
		     "Your experiment $slicename is going to expire in ${when}.\n".
		     "If you want to extend this experiment, please go to:\n\n".
		     "    $link\n\n".
		     "and click on the Extend button.\n".
		     "\n".
		     "Thanks!",
839
		     $self->Brand()->LogsEmailAddress());
840 841 842 843
    
    return 0;
}

844 845 846
#
# Go through all the manifests and count up nodes.
#
847 848 849 850 851
sub ComputeNodeCounts($)
{
    my ($self) = @_;
    my $physnode_count = 0;
    my $virtnode_count = 0;
852
    my @slivers = $self->AggregateList();
853 854
    if (!@slivers) {
	print STDERR "No slivers for $self\n";
855 856
	return -1;
    }
857
    foreach my $sliver (@slivers) {
858 859 860
	next
	    if ($sliver->status() eq "deferred");
	
861 862 863 864 865
	my $manifest = GeniXML::Parse($sliver->manifest());
	if (! defined($manifest)) {
	    print STDERR "Could not parse manifest for $sliver\n";
	    return -1;
	}
866 867 868
	my $pcount = 0;
	my $vcount = 0;
	
869
	foreach my $ref (GeniXML::FindNodes("n:node",
870 871 872 873
					    $manifest)->get_nodelist(),
			 GeniXML::FindNodesNS("n:vhost",
				      $manifest,
				      $GeniXML::EMULAB_NS)->get_nodelist()) {
874
	    my $virtualization_type = GeniXML::GetVirtualizationSubtype($ref);
875 876 877 878 879 880
	    my $manager_urn = GetManagerId($ref);

	    # Combined rspec.
	    next
		if (!defined($manager_urn) ||
		    $manager_urn ne $sliver->aggregate_urn());
881 882

	    if (defined($virtualization_type) &&
883
		($virtualization_type eq "emulab-xen" ||
884 885
		 $virtualization_type eq "emulab-blockstore" ||
		 $virtualization_type eq "emulab-docker")) {
886
		$vcount++;
887 888
		next;
	    }
889
	    $pcount++;
890
	}
891 892 893 894 895 896
	$sliver->Update({"physnode_count" => $pcount,
			 "virtnode_count" => $vcount})
	    == 0 or return -1;
	    
	$physnode_count += $pcount;
	$virtnode_count += $vcount;
897 898 899 900 901 902 903
    }
    $self->Update({"physnode_count" => $physnode_count,
		   "virtnode_count" => $virtnode_count})
	== 0 or return -1;
    return 0;
}

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
#
# Go through all the manifests and return a list of nodes.
#
sub GetNodeDetails($)
{
    my ($self) = @_;
    my $rval   = {};

    my @slivers = $self->AggregateList();
    if (!@slivers) {
	print STDERR "No slivers for $self\n";
	return undef;
    }
    foreach my $sliver (@slivers) {
	my $manifest = GeniXML::Parse($sliver->manifest());
	if (! defined($manifest)) {
	    print STDERR "Could not parse manifest for $sliver\n";
	    return undef;
	}
	my $nodes = {};
	
	foreach my $ref (GeniXML::FindNodes("n:node",
					    $manifest)->get_nodelist(),
			 GeniXML::FindNodesNS("n:vhost",
				      $manifest,
				      $GeniXML::EMULAB_NS)->get_nodelist()) {
	    my $virtualization_type = GeniXML::GetVirtualizationSubtype($ref);
	    my $manager_urn = GetManagerId($ref);
	    my $isvnode = 0;

	    # Combined rspec.
	    next
		if (!defined($manager_urn) ||
		    $manager_urn ne $sliver->aggregate_urn());

	    if (defined($virtualization_type) &&
		($virtualization_type eq "emulab-xen" ||
		 $virtualization_type eq "emulab-blockstore")) {
		$isvnode = 1;
	    }
	    my $client_id = GetVirtualId($ref);
	    my $node_id   = GetVnodeId($ref);
	    if (GeniHRN::IsValid($node_id)) {
		my $hrn = GeniHRN->new($node_id);
		if (!$hrn->IsNode()) {
		    print STDERR "$node_id is not a node\n";
		    return undef;
		}
		$node_id = $hrn->id();
	    }
	    $nodes->{$node_id} = {
		"client_id"  => $client_id,
		"isvirtnode" => $isvnode,
	    };
	}
	$rval->{$sliver->aggregate_urn()} = $nodes;
    }
    return $rval;
}

964
#
965
# Add an aggregate to an instance.
966
#
967
sub AddAggregate($$)
968
{
969 970 971
    my ($self, $aggregate_urn) = @_;

    my $aggobj = APT_Instance::Aggregate->Create($self, $aggregate_urn);
972
    return undef
973
	if (!defined($aggobj));
974

975
    $self->{'AGGREGATES'}->{$aggregate_urn} = $aggobj;
976 977 978 979 980 981 982 983 984
    return $aggobj;
}

#
# Locate the aggregate for a nodeid
#
sub FindAggregateByNodeId($$)
{
    my ($self, $node_id) = @_;
985
    my @slivers = $self->AggregateList();
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    if (!@slivers) {
	return undef;
    }
    foreach my $sliver (@slivers) {
	my $manifest = GeniXML::Parse($sliver->manifest());
	if (! defined($manifest)) {
	    print STDERR "Could not parse manifest for $sliver\n";
	    return -1;
	}
	foreach my $ref (GeniXML::FindNodes("n:node",
					    $manifest)->get_nodelist()) {
	    my $client_id = GeniXML::GetVirtualId($ref);
	    if (defined($client_id) && $client_id eq $node_id) {
		if (wantarray) {
		    return ($sliver, $manifest);
		}
		return $sliver;
	    }
	}
    }
    return undef;
}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
sub WriteCredentials($$)
{
    my ($self, $directory) = @_;
    my $geniuser  = $self->GetGeniUser();
    my $slice     = $self->GetGeniSlice();
    my $context   = APT_Geni::GeniContext();

    if (! (defined($geniuser) && defined($slice))) {
	fatal("Could not lookup geniuser or slice");
    }

    my ($slice_credential, $speaksfor_credential) =
	APT_Geni::GenCredentials($slice, $geniuser);
    if (! (defined($speaksfor_credential) &&
	   defined($slice_credential))) {
	fatal("Could not create credentials");
    }

    my $credfile = "$directory/slicecred.xml";
    unlink($credfile)
	if (-e $credfile);
    open(XML, ">$credfile") or
	fatal("Could not create $credfile");
    print XML $slice_credential->asString();
    close(XML);
    
    $credfile = "$directory/speaksforcred.xml";
    unlink($credfile)
	if (-e $credfile);
    open(XML, ">$credfile") or
	fatal("Could not create $credfile");
    print XML $speaksfor_credential->asString();
    close(XML);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

    #
    # We do not generally need this, but might as well generate it,
    # since we do not easily know if the stitcher is going to contact
    # the AL2S aggregate, which does not support speaksfor.
    #
    $credfile = "$directory/al2scred.xml";
    my $authcred = APT_Geni::GenAuthCredential($slice);
    if (!defined($authcred)) {
	print STDERR "Could not general auth cred!\n";
	return -1;
    }
    unlink($credfile)
	if (-e $credfile);
    open(XML, ">$credfile") or
	fatal("Could not create $credfile");
    print XML $authcred->asString();
    close(XML);
1060 1061 1062 1063
    
    return 0;
}

1064 1065 1066
#
# Build a set of sshkeys.
#
1067
sub GetSSHKeys($$;$)
1068
{
1069
    my ($self, $pref, $target_user) = @_;
1070 1071 1072
    my $rval;
    my @keys;

1073
    my $geniuser = $target_user || $self->GetGeniUser();
1074 1075 1076 1077 1078
    return -1
	if (!defined($geniuser));
    my $project  = $self->GetProject();
    return -1
	if (!defined($project));
1079 1080 1081
    my $group = $self->GetGroup();
    return -1
	if (!defined($group));
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

    if ($geniuser->GetKeyBundle(\@keys, 1) < 0 || !@keys) {
	print STDERR "No ssh keys for $geniuser\n";
	return -1;
    }

    #
    # CM format.
    #
    $rval = [{'urn'   => $geniuser->urn(),
	      'login' => $geniuser->uid(),
1093 1094
	      # Creator clearly has root privs!
	      'privs' => 'root',
1095 1096 1097
	      'keys'  => [ @keys ]
	     }];

1098 1099 1100 1101
    # Want keys for single user.
    goto done
	if (defined($target_user));

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    if (! ($project->pid() eq $APT_HOLDINGPROJECT ||
	   $project->pid() eq $CLOUD_HOLDINGPROJECT)) {
	#
	# Get other users from the project. Real local users are easy,
	# nonlocal users from the GPO portal are messy.
	#
	my @members;
	if ($project->GetProjectGroup()->MemberList(\@members)) {
	    print STDERR "Error getting memberlist for $project\n";
	}
	else {
	    foreach my $member (@members) {
		next
		    if ($member->SameUser($geniuser->emulab_user()));
	    
		my $guser = GeniUser->CreateFromLocal($member);
		next
		    if (!defined($guser));

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
		#
		# Watch for local Emulab users with user privs.
		# Only Emulab based CMs will do anything with this,
		# but that is all we talk to.
		#
		my $privs = "root";

		if ($guser->IsLocal()) {
		    my $trust = $group->Trust($guser->emulab_user());
		    if (! TBMinTrust($trust, PROJMEMBERTRUST_LOCALROOT())) {
			$privs = "user";
		    }
		}

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
		#
		# So, users coming in from the trusted signer have their keys
		# at their home portal. We download those keys whenever they
		# log in, and cache them in their local stub account, but they
		# could be out of date. But in order to refresh those keys, we
		# would need a valid (not expired) speaks-for credential, which
		# we might have, but typically not since they have short expire
		# times. So, lets not worry about this right now, just use the
		# cached keys and see who complains.
		#
		@keys = ();
		if ($guser->GetKeyBundle(\@keys, 1) < 0 || !@keys) {
		    print STDERR "No ssh keys for $guser\n";
		    next;
		}
		push(@{$rval}, {'urn'   => $guser->urn(),
				'login' => $guser->uid(),
1152
				'privs' => $privs,
1153 1154 1155 1156 1157
				'keys'  => [ @keys ]
		               });
	    }
	}
    }
1158
  done:
1159 1160 1161 1162
    $$pref = $rval;
    return 0;
}

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
#
# Update the image status in the webtask for the instance. This is not
# clean at all, need a better way to do this.
#
sub UpdateImageStatus($$)
{
    my ($self, $details) = @_;

    DBQueryWarn("lock tables web_tasks write, apt_instances write, ".
		"            apt_instance_aggregates write")
	or return {};

    $self->Refresh();
    if ($self->status() ne "imaging") {
	goto done;
    }
1179
    my $webtask = $self->webtask();
1180 1181 1182
    if (!defined($webtask)) {
	goto done;
    }
1183 1184 1185
    # This could be really stale, must refresh.
    $webtask->Refresh();
    
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    #
    # This will need to change; we can get updates from polling or
    # from the event stream. The events are processed out of band from
    # from the polling, so we have a consistency problem. In addition,
    # the event stream is sending status for just a single node since
    # events are bounded in size.
    #
    # In other words, the new image status has to be merged into the
    # existing status. We have use some kind of lock to avoid scrambling
    # the json data, and for now it is a table lock.
    #
    # Also, the blob has a timestamp in it, so we can sorta tell which
    # is most recent (not perfect, but does not really need to be).
    #
    if (defined($webtask->image_stamp()) &&
	defined($details->{'utc'}) &&
	$details->{'utc'} < $webtask->image_stamp()) {
	goto done;
    }
    $webtask->image_size($details->{'size'});
    $webtask->image_status($details->{'status'});
    $webtask->image_stamp($details->{'utc'});
    $webtask->Store();
  done:
    DBQueryWarn("unlock tables");
    return 0;
}

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
sub AddExtensionHistory($$)
{
    my ($self, $reason) = @_;
    my $uuid = $self->uuid();
    my $safe_text = DBQuoteSpecial($reason);

    return DBQueryWarn("update apt_instances set ".
		       "  extension_history=CONCAT($safe_text,".
		       "                     IFNULL(extension_history,'')) ".
		       "where uuid='$uuid'");
}

sub ExtensionRequested($$$)
{
    my ($self, $reason, $granted) = @_;
    my $uuid = $self->uuid();
    my $safe_text = DBQuoteSpecial($reason);

    return DBQueryWarn("update apt_instances set ".
		       "  extension_reason=$safe_text,".
		       "  extension_requested=1, ".
		       "  extension_count=extension_count+1, ".
1236
		       "  extension_hours=extension_hours+${granted} ".
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
		       "where uuid='$uuid'");
}

sub BumpExtensionCount($$)
{
    my ($self, $granted) = @_;
    my $uuid = $self->uuid();

    return DBQueryWarn("update apt_instances set ".
		       "  extension_count=extension_count+1, ".
1247
		       "  extension_hours=extension_hours+${granted} ".
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
		       "where uuid='$uuid'");
}

#
# Return the list APT_Aggregate objects for an instance.
#
sub AptAggregateList($)
{
    my ($self)  = @_;
    my @results = ();

    foreach my $agg ($self->AggregateList()) {
	my $aptagg = APT_Aggregate->Lookup($agg->aggregate_urn());
	if (!defined($aptagg)) {
	    print STDERR "Could not get APT_Aggregate object for $agg\n";
	    return ();
	}
	push(@results, $aptagg);
    }
    return @results;
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
#
# Apply extension policies.
#
sub ApplyExtensionPolicies($)
{
    my ($self)   = @_;
    my $uuid     = $self->uuid();
    my $pid      = $self->pid();
    my $name     = $self->name();
    my $pid_idx  = $self->pid_idx();
    my $gid_idx  = $self->gid_idx();
    my $uid_idx  = $self->creator_idx();
1282 1283
    my $current_disable = $self->extension_disabled();
    my $current_limit   = $self->extension_limit();
1284 1285
    my $policy;
    my $disabled = 0;
1286 1287
    my $limit    = 0;
    my $admin_after_limit = 0;
1288 1289 1290 1291 1292 1293
    my $reason;

    #
    # Apply in order project, group, then user.
    #
    my $query_result =
1294 1295
	DBQueryWarn("select disabled,reason,`limit`,admin_after_limit ".
		    " from apt_extension_group_policies ".
1296 1297 1298 1299
		    "where pid_idx='$pid_idx' and gid_idx=pid_idx");
    return -1
	if (!defined($query_result));
    if ($query_result->numrows) {
1300 1301 1302
	($disabled,$reason,
	 $limit,$admin_after_limit) = $query_result->fetchrow_array();
	if (($disabled || $limit) && !defined($reason)) {
Leigh Stoller's avatar
Leigh Stoller committed
1303
	    $reason = "because of a project restriction";
1304 1305 1306 1307
	}
	$policy = "Project";
    }
    $query_result =
1308 1309
	DBQueryWarn("select disabled,reason,`limit`,admin_after_limit ".
		    "  from apt_extension_group_policies ".
1310 1311 1312 1313
		    "where pid_idx='$pid_idx' and gid_idx='$gid_idx'");
    return -1
	if (!defined($query_result));
    if ($query_result->numrows) {
1314 1315 1316 1317 1318 1319
	my ($d,$r,$l,$admin_after_limit) = $query_result->fetchrow_array();
	$disabled = $d;
	$limit    = $l;
	$reason   = $r;
	$policy   = "Group";
	if (($disabled || $limit) && !defined($reason)) {
Leigh Stoller's avatar
Leigh Stoller committed
1320
	    $reason = "because of a group restriction";
1321 1322 1323
	}
    }
    $query_result =
1324 1325
	DBQueryWarn("select disabled,reason,`limit`,admin_after_limit ".
		    "  from apt_extension_user_policies ".
1326 1327 1328 1329
		    "where uid_idx='$uid_idx'");
    return -1
	if (!defined($query_result));
    if ($query_result->numrows) {
1330 1331 1332 1333 1334 1335
	my ($d,$r,$l,$admin_after_limit) = $query_result->fetchrow_array();
	$disabled = $d;
	$limit    = $l;
	$reason   = $r;
	$policy   = "User";
	if (($disabled || $limit) && !defined($reason)) {
Leigh Stoller's avatar
Leigh Stoller committed
1336
	    $reason = "because of user restriction";
1337 1338
	}
    }
1339 1340 1341 1342 1343 1344
    # Apply flags
    $self->Update({"extension_disabled" => $disabled,
		   "extension_limit"    => $limit,
		   "extension_admin_after_limit" => $admin_after_limit})
	== 0 or return -1;
    
1345
    # Set the reason only if disabled, clear otherwise.
1346 1347
    if ($disabled) {
	$self->Update({"extension_disabled_reason" => $reason}) == 0	
1348 1349 1350
	    or return -1;
    }
    else {
1351
	$self->Update({"extension_disabled_reason" => undef}) == 0	
1352 1353
	    or return -1;
    }
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    # Ditto the limit.
    if ($limit) {
	$self->Update({"extension_limit_reason" => $reason}) == 0	
	    or return -1;
    }
    else {
	$self->Update({"extension_limit_reason" => undef}) == 0	
	    or return -1;
    }
    #
    # Basically, disable overrides limit when requesting an extension.
    #
    $current_limit = -1 if (!defined($current_limit));
    $limit         = -1 if (!defined($limit));
    
    if ($disabled != $current_disable || $limit != $current_limit) {
	my $message = "$policy policy applied to $pid/$name:\n";
1371

1372 1373 1374 1375 1376
	if ($disabled != $current_disable) {
	    my $which = ($disabled ? "disabled" : "enabled");
	    $message .= "Extensions have been ${which}.\n";
	}
	if ($limit != $current_limit) {
1377 1378
	    my $which = ($limit ?
			 "limited to " .  HoursToEnglish($limit) :
1379 1380 1381 1382 1383 1384 1385 1386
			 "set to unlimited");
	    $message .= "Extensions have been ${which}.\n";
	    if ($limit && $admin_after_limit) {
		$message .=
		    "Additional extension requests will require ".
		    "admin approval.\n";
	    }
	}
1387
	SENDMAIL($TBAUDIT,
1388 1389
		 "Portal experiment $uuid extension policy changed",
		 $message . "\n" .
1390 1391 1392 1393 1394 1395 1396
		 (defined($reason) ? "Reason:\n$reason\n\n" : "").
		 $self->adminURL() . "\n",
		 $TBOPS);
    }
    return 0;
}

1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
#
# Convert hours to days and hours string.
#
sub HoursToEnglish($)
{
    my ($hours) = @_;
    my $string;
    
    my $wdays  = int($hours / 24);
    my $whours = $hours % 24;
    if ($wdays) {
	$string = "$wdays day";
	$string .= "s" if ($wdays > 1);
	if ($whours) {
	    $string .= " ${whours} hour";
	    $string .= "s" if ($whours > 1);
	}
    }
    elsif ($whours) {
	$string = "$whours hour";
	$string .= "s" if ($whours > 1);
    }
    else {
	$string = "nothing";
    }
    return $string;
}

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
#
# Check to see if all aggregates provisioned, and update node counts.
#
sub CheckProvisioned($)
{
    my ($self) = @_;
    my $provisioned = 1;

    DBQueryWarn("lock tables apt_instances write, ".
		"            apt_instance_aggregates write, ".
		"            web_tasks read")
	or return -1;

    #print STDERR "CheckProvisioned: " . $self->status() . "\n";

    # We only do this while we are provisioning.
    $self->Refresh();
    goto done
	if ($self->status() ne "provisioning");

    foreach my $agg ($self->AggregateList()) {
	$agg->Refresh();

1448 1449 1450 1451
	# Skip deferred for now, not sure how to handle this.
	next
	    if ($agg->status() eq "deferred");

1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
	$provisioned = 0
	    if (!defined($agg->manifest()));
    }
    if ($provisioned) {
	#print STDERR "CheckProvisioned: provisioned\n";
	
	$self->SetStatus("provisioned");
	$self->ComputeNodeCounts();
    }
  done:
    DBQueryWarn("unlock tables");
    return 0;
}

1466 1467 1468 1469 1470 1471 1472 1473 1474
#
# Create credentials required by this instance, to access its datasets.
#
sub CreateDatasetCreds($$$)
{
    my ($self, $pmsg, $pref) = @_;
    my $rspecstr = $self->rspec();
    my $project  = $self->GetProject();
    my $geniuser = $self->GetGeniUser();
1475
    my %credentials = ();
1476 1477 1478 1479 1480 1481 1482 1483
    
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
	print STDERR "CreateDatasetCreds: Could not parse rspec\n";
	return -1;
    }

    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
1484
	my $manager_urn = GeniHRN->new(GetManagerId($ref));
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
	
	foreach my $blockref (GeniXML::FindNodesNS("n:blockstore", $ref,
				   $GeniXML::EMULAB_NS)->get_nodelist()) {
	    my $dataset_id = GeniXML::GetText("persistent", $blockref);
	    if (!defined($dataset_id)) {
		# persistent is deprecated.
		$dataset_id = GeniXML::GetText("dataset", $blockref);
	    }

	    #
	    # We only care about datasets here, we let the backend
	    # do the error checking on ephemeral blockstores.
	    #
	    next
		if (!defined($dataset_id));

	    my $class = GeniXML::GetText("class", $blockref);
	    if (!defined($class)) {
		$class = "remote";
	    }
	    # Image backed referenced by URL. No checking since the
	    # image has to be global anyway. Needs more thought.
	    next
		if ($class eq "local" && $dataset_id =~ /^(http|https):/);

	    my $dataset_urn = GeniHRN->new($dataset_id);
	    my $dataset = APT_Dataset->LookupByRemoteURN($dataset_urn);
	    if (!defined($dataset)) {
1513
		if ($dataset_urn->IsOurDomain()) {
1514 1515 1516 1517
		    #
		    # Local image backed dataset or lease.
		    #
		    my ($image,$lease);
1518 1519
		    my $pid = $dataset_urn->dsetpid();
		    my $id  = $dataset_urn->dsetname();
1520

1521
		    if ($dataset_urn->IsIMDataset()) {
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
			$image = Image->Lookup($pid, $id);
			if ($image && !$image->isdataset()) {
			    $$pmsg = "$dataset_urn is an image not a dataset ";
			    return 1;
			}
			#
			# Do a partial permission check here to catch
			# errors early.  The CM will do its own check
			# of course.
			#
			if (!$image->global() &&
			    $PROTOGENI_LOCALUSER && $geniuser->IsLocal() &&
			    !$image->AccessCheck($geniuser->emulab_user(),
1535
						   TB_IMAGEID_READINFO())) {
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
			    $$pmsg = "No permission to use $dataset_urn";
			    return 1;
			}
		    }
		    else {
			$lease = Lease->Lookup($pid, $id);
		    }
		    # We cannot generate a credential for "legacy" datasets.
		    # So if it is not global, it cannot be transferred. Maybe
		    # this is okay, we will find out. We could generate a
		    # credential if we needed to.
		    next
			if ($image || $lease);
		}
		$$pmsg = "Dataset '$dataset_urn' does not exist";
		return 1;
	    }
	    #
	    # We do not need a credential for leases, only real users
	    # can use those, and so standard emulab permission checks
	    # are applied at the CM.
	    #
	    next
Leigh Stoller's avatar
Leigh Stoller committed
1559
		if (!$dataset_urn->IsIMDataset());
1560

1561 1562 1563 1564 1565 1566 1567 1568 1569
	    #
	    # No need for a credential if the dataset is local and the
	    # node is local; normal permissions apply.
	    #
	    next
		if ($manager_urn->IsOurDomain() &&
		    $dataset_urn->IsOurDomain());

	    # Generate per manager credential lists.
1570 1571 1572 1573
	    next
		if (exists($credentials{$manager_urn}) &&
		    exists($credentials{$manager_urn}->{$dataset_urn}));

1574
	    # Generate each credential once.
1575 1576 1577 1578
	    if (!exists($credentials{$manager_urn})) {
		$credentials{$manager_urn} = {};
	    }

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
	    #
	    # For image backed datasets, we need to send along a credential
	    # that allows the remote CM to securely download the dataset if
	    # it does not already have it. To do that we need to send it a
	    # credential from the CM where the dataset lives. We do that by
	    # requesting a credential, and delegating it to the target CM.
	    #
	    my $pid = $dataset->pid();
	    my $id  = $dataset->dataset_id();
	    my $cmd = "$MANAGEDATASET getcredential -a $manager_urn $pid/$id";
	    my $output = emutil::ExecQuiet($cmd);
	    if ($?) {
		$$pmsg = "Could not generate credential for $dataset_urn";
		if (($? >> 8) > 0) {
		    if ($output ne "") {
			$$pmsg = "$dataset_urn" . ": " . $output;
		    }
		    return 1;
		}
		return -1;
	    }
1600
	    $credentials{$manager_urn}->{$dataset_urn} = $output;
1601 1602
	}
    }
1603 1604 1605 1606 1607 1608 1609
    #
    # Convert to hash of lists instead of hash of hashes.
    #
    foreach my $urn (keys(%credentials)) {
	my %creds = %{$credentials{$urn}};
	$credentials{$urn} = [ values(%creds) ];
    }
1610
    $$pref = \%credentials;
1611 1612 1613
    return 0;
}

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
#
# Create credentials required by this instance, to access restricted images.
# Access means import and/or use the image.
#
sub CreateImageCreds($$$;$)
{
    my ($self, $pmsg, $pref) = @_;
    my $rspecstr = $self->rspec();
    my $project  = $self->GetProject();
    my $geniuser = $self->GetGeniUser();
    my %imagecache  = ();
    my %credentials = ();
    
    my $rspec = GeniXML::Parse($rspecstr);
    if (! defined($rspec)) {
	print STDERR "CreateDatasetCreds: Could not parse rspec\n";
	return -1;
    }

    foreach my $ref (GeniXML::FindNodes("n:node", $rspec)->get_nodelist()) {
	my $manager_urn = GeniHRN->new(GetManagerId($ref));
	my $diskref     = GeniXML::GetDiskImage($ref);
	my $credstr;

	if (! (defined($manager_urn) && $manager_urn->IsCM())) {
	    $$pmsg = "$manager_urn is not a valid CM URN";
	    return 1;
	}

	# Using the default (system) image. 
	next
	    if (!defined($diskref));

	my $image_url = GeniXML::GetText("url", $diskref);
	my $image_urn = GeniXML::GetText("name", $diskref);
	next
	    if (!defined($image_urn));
Leigh Stoller's avatar
Leigh Stoller committed
1651 1652 1653
	# Yep, people put the URL in the URN spot. We should throw an error.
	next
	    if ($image_urn =~ /^(http|https):/);
1654 1655

	if (!GeniHRN::IsValid($image_urn)) {
1656 1657 1658
	    $$pmsg = "$image_urn is not a valid URN";
	    return 1;
	}
1659
	$image_urn = GeniHRN->new($image_urn);
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

	# System images are global (well, it would be rare if not).
	next
	    if ($image_urn->ospid() eq TBOPSPID());

	#
	# If the image is local, then local permissions apply to the
	# user. Implicit assumption: PROTOGENI_LOCALUSER=1. We do the
	# check here to catch permission errors early. 
	#
	# If the manager is the local aggregate, then no credential
	# is needed, the CM is going to do a local permission check too.
	#
	if ($image_urn->IsOurDomain()) {
	    my $image = Image->Lookup($image_urn->ospid(), $image_urn->osname());
	    if (!defined($image)) {
		$$pmsg = "Could not lookup local image $image_urn";
		return 1;
	    }
	    if (! ($image->global() ||
		   $image->AccessCheck($geniuser->emulab_user(),
				       TB_IMAGEID_READINFO()))) {
		$$pmsg = "No permission to use $image_urn";
		return 1;
	    }
	    #
	    # If the image is restricted, the experiment has to be created
	    # in the same project as the image, or in a project that has
	    # been granted permission to use the image.
	    #
	    if (!$image->global() && $image->pid() ne $project->pid()) {
		my $allowed = 0;
		if ($image->LookupAccess($project->GetProjectGroup(),
					 \$allowed) != 0) {
		    $$pmsg = "Could not lookup access for $image";
		    return -1;
		}
		if (!$allowed) {
		    $$pmsg = "Not allowed to use restricted image $image_urn ".
			"in project " . $project->pid();
		    return 1;
		}
	    }
	    # No cred needed for local image at local CM.
	    next
		if ($manager_urn->IsOurDomain());
	}

	#
	# Basically, only the Mothership will get this far, every other
	# site is going to be talking to the local portal only, not
	# a remote cluster. No IMS either.
	#
	next
1714 1715 1716 1717 1718 1719
	    if (exists($credentials{$manager_urn}) &&
		exists($credentials{$manager_urn}->{$image_urn}));

	if (!exists($credentials{$manager_urn})) {
	    $credentials{$manager_urn} = {};
	}
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746

	#
	# Generate a credential that allows the user to use a local
	# image at a remote cluster (if it was the local cluster,
	# that case was handled above). We know this is allowed as
	# per the access check above.
	#
	if ($image_urn->IsOurDomain()) {
	    #
	    # We can generate the credential inline.
	    #
	    my $image = Image->Lookup($image_urn->ospid(),$image_urn->osname());
	    if (!defined($image)) {
		$$pmsg = "Could not lookup local image $image_urn";
		return 1;
	    }
	    my $authority = APT_Geni::GetAuthority($manager_urn);
	    if (!defined($authority)) {
		$$pmsg = "Could not look up authority $manager_urn";
		return -1;
	    }
	    my $credential = GeniImage::CreateImageCredential($image,
							      $authority);
	    if (!defined($credential)) {
		$$pmsg = "Could not create credential for $image_urn";
		return -1;
	    }
1747
	    $credentials{$manager_urn}->{$image_urn} = $credential->asString();
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
	    next;
	}
	    
	#
	# Temporary, need to talk IMS directly instead of issuing an RPC
	# for every image.
	#
	my $blob;
	if (exists($imagecache{$image_urn})) {
	    $blob = $imagecache{$image_urn};
	}
	else {
	    $blob = GeniImage::GetImageData($image_urn, $pmsg);
	    if (!defined($blob)) {
		print STDERR $pmsg . "\n";
		next;
	    }
	    $imagecache{$image_urn} = $blob;
	}
	# IMS says the image is public (global) so no credential needed.
	next
	    if ($blob->{"visibility"} eq "public");

	#
	# The IMS tells us the project urn of the image. 99% of the time,
	# that is for a project here (where the IMS is). The other 1% the
	# image was created by some other SA (say, ch.geni.net), and we
	# cannot do anything with those. Just throw an error, I doubt a
	# Portal user would be using one of those (and global=0), revisit
	# later if it happens.
	#
	my $project_urn = GeniHRN->new($blob->{'project_urn'});
	if ($project_urn->domain() ne $OURDOMAIN) {
	    $$pmsg = "Cannot create a credential for ".
		"external image: $image_urn";
	    return 1;
	}

	#
	# Since we are ignoring images created by other domains, and
	# since the image server is not giving us permission info, we
	# basically have to say that the experiment and the image have
	# to be in the same local project.
	#
Leigh Stoller's avatar
Leigh Stoller committed
1792 1793 1794
	# XXX Need to come back to this ...
	#
	if (lc($project_urn->project()) ne lc($project->pid())) {
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
	    $$pmsg = "No permission to use $image_urn in project ".
		$project->pid();
	    return 1;
	}
	
	#
	# Get a credential from the remote cluster via the admin path.
	#
	my $cmd = "$MANAGEIMAGES getcredential -a $manager_urn $image_urn";
	my $output = emutil::ExecQuiet($cmd);
	if ($?) {
	    $$pmsg = "Could not generate credential for $image_urn";
	    if (($? >> 8) > 0) {
		if ($output ne "") {
		    $$pmsg = "$image_urn" . ": " . $output;
		}
		return 1;
	    }
	    print STDERR "$cmd\n";
	    print STDERR $output . "\n";
	    return -1;
	}
1817
	$credentials{$manager_urn}->{$image_urn} = $output;	
1818
    }
1819 1820 1821 1822 1823 1824 1825 1826
    #
    # Convert to hash of lists instead of hash of hashes.
    #
    foreach my $urn (keys(%credentials)) {
	my %creds = %{$credentials{$urn}};
	$credentials{$urn} = [ values(%creds) ];
    }
    $$pref = \%credentials;
1827 1828 1829
    return 0;
}

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
#
# Defer aggregate setup until missing aggregates come online.
# Optional start time indicates we are deferring the entire experiment
# till a later time.
#
sub Defer($$)
{
    my ($self, $start) = @_;
    my $uuid   = $self->uuid();
    my $name   = $self->name();

    my $query_result =
	DBQueryWarn("select uuid from apt_deferred_instances ".
		    "where uuid='$uuid'");
    return -1
	if (!defined($query_result));

    if ($query_result->numrows) {
	DBQueryWarn("update apt_deferred_instances set ".
		    "  last_retry=now() ".
		    "where uuid='$uuid'")
	    or return -1;
    }
    else {
	DBQueryWarn("replace into apt_deferred_instances set ".
		    " uuid='$uuid', name='$name'" .
		    (defined($start) ?
		     ", start_at=FROM_UNIXTIME($start)" : ""))
	    or return -1;
	
	if (defined($start)) {
	    DBQueryWarn("update apt_instance_aggregates set status='deferred' ".
			"where uuid='$uuid'")
		or return -1;
	}
    }
    return 0;
}
sub ResolveDefer($)
{
    my ($self) = @_;
    my $uuid   = $self->uuid();

    DBQueryWarn("delete from apt_deferred_instances ".
		"where uuid='$uuid'")
	or return -1;

    return 0;
}