APT_Instance.pm.in 81.1 KB
Newer Older
Leigh B Stoller's avatar
Leigh B Stoller committed
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2017 University of Utah and the Flux Group.
Leigh B Stoller's avatar
Leigh B 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 POSIX qw(tmpnam);
32
use JSON;
Leigh B Stoller's avatar
Leigh B Stoller committed
33
use Exporter;
34
use vars qw(@ISA @EXPORT $AUTOLOAD
35 36 37
	    $RECORDHISTORY_TERMINATED $RECORDHISTORY_EXPIRED
	    $APT_HOLDINGPROJECT $CLOUD_HOLDINGPROJECT);

Leigh B Stoller's avatar
Leigh B 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 B Stoller's avatar
Leigh B 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 B Stoller's avatar
Leigh B Stoller committed
62
use GeniCredential;
63
use GeniUser;
64
use GeniHRN;
65 66
use GeniXML;
use WebTask;
67
use Logfile;
Leigh B Stoller's avatar
Leigh B Stoller committed
68 69 70 71 72
use overload ('""' => 'Stringify');

# Configure variables
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
73
my $GENEXTENDCRED = "$TB/sbin/protogeni/genextendcred";
74
my $GENIUSER      = "geniuser";
75
my $MAINSITE      = @TBMAINSITE@;
Leigh B Stoller's avatar
Leigh B Stoller committed
76 77 78

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

82
# Debugging
Leigh B Stoller's avatar
Leigh B Stoller committed
83
my $usemydevtree  = 0;
84 85 86 87 88 89
sub devurl($)
{
    my ($cmurl) = @_;

    if ($usemydevtree) {
	$cmurl =~ s/protogeni/protogeni\/stoller/;
90
#	$cmurl =~ s/12369/12396/;
91 92 93
    }
    return $cmurl;
}
94

Leigh B Stoller's avatar
Leigh B Stoller committed
95 96 97
#
# Lookup by uuid.
#
98
sub Lookup($$)
Leigh B Stoller's avatar
Leigh B Stoller committed
99
{
100 101
    my ($class, $token) = @_;
    my $query_result;
Leigh B Stoller's avatar
Leigh B Stoller committed
102

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    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+$/) {
122 123 124
	# Look in cache first
	return $instances{$token}
            if (exists($instances{$token}));
Leigh B Stoller's avatar
Leigh B Stoller committed
125

126 127 128 129 130 131
	$query_result =
	    DBQueryWarn("select * from apt_instances where uuid='$token'");
    }
    else {
	return undef;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
132 133 134
    return undef
	if (!$query_result || !$query_result->numrows);

135 136 137 138
    my $self              = {};
    $self->{'INSTANCE'}   = $query_result->fetchrow_hashref();
    $self->{'BRAND'}      = Brand->Create($self->{'INSTANCE'}->{'servername'});
    $self->{'HASH'}       = {};
139
    $self->{'AGGREGATES'} = {};
140
    $self->{'WEBTASK'}    = undef;
Leigh B Stoller's avatar
Leigh B Stoller committed
141
    bless($self, $class);
142 143 144 145

    #
    # Lookup existing aggregates.
    #
146 147
    my $aggregates = APT_Instance::Aggregate->LookupForInstance($self);
    if (!keys(%{$aggregates}) && defined($self->aggregate_urn())) {
148 149 150 151
	#
	# Make up a fake one; eventually the old ones will die or
	# I will create entries for them. Not worrying about it now.
	#
152 153
	$aggregates = {$self->aggregate_urn() =>
			   APT_Instance::Aggregate->GenTemp($self)};
154
    }
155
    $self->{'AGGREGATES'} = $aggregates;
Leigh B Stoller's avatar
Leigh B Stoller committed
156 157
    
    # Add to cache. 
158
    $instances{$self->uuid()} = $self;
Leigh B Stoller's avatar
Leigh B Stoller committed
159 160 161 162 163 164
    
    return $self;
}

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

    # A DB row proxy method call.
    if (exists($self->{'INSTANCE'}->{$name})) {
	return $self->{'INSTANCE'}->{$name};
    }
173 174 175 176 177 178 179 180 181
    # 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 B Stoller's avatar
Leigh B Stoller committed
182 183 184
    carp("No such slot '$name' field in class $type");
    return undef;
}
185 186 187
sub Brand($)	{ return $_[0]->{'BRAND'}; }
sub isAPT($)	{ return $_[0]->Brand()->isAPT() ? 1 : 0; }
sub isCloud($)	{ return $_[0]->Brand()->isCloud() ? 1 : 0; }
188
sub isPNet($)	{ return $_[0]->Brand()->isPNet() ? 1 : 0; }
189 190
sub AggregateList($) { return values(%{ $_[0]->{'AGGREGATES'} }); }
sub AggregateHash($) { return $_[0]->{'AGGREGATES'}; }
Leigh B Stoller's avatar
Leigh B Stoller committed
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
#
# 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 B Stoller's avatar
Leigh B Stoller committed
221 222 223 224
# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

225 226 227 228
    $self->{'INSTANCE'}   = undef;
    $self->{'BRAND'}      = undef;
    $self->{'AGGREGATES'} = undef;
    $self->{'HASH'}       = undef;
229
    $self->{'WEBTASK'}    = undef;
Leigh B Stoller's avatar
Leigh B Stoller committed
230 231
}

232 233 234 235 236 237 238
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

239 240 241 242 243 244 245 246 247 248 249
    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) = @_;

250 251
    #
    # Break circular dependency so that the object is released
252
    # (the aggregate objects point back to the instance).
253
    #
254 255
    $self->{'AGGREGATES'} = undef;
    $self->Flush();
256 257
}

Leigh B Stoller's avatar
Leigh B Stoller committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
#
# 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
#
284
sub Create($$$)
Leigh B Stoller's avatar
Leigh B Stoller committed
285
{
286
    my ($class, $argref, $perrmsg) = @_;
Leigh B Stoller's avatar
Leigh B Stoller committed
287 288 289 290 291 292 293 294 295
    my $uuid;

    if (exists($argref->{'uuid'})) {
	$uuid = $argref->{'uuid'};
	delete($argref->{'uuid'});
    }
    else {
	$uuid = NewUUID();
    }
296 297
    my $pid_idx = $argref->{'pid_idx'};
    my $name    = $argref->{'name'};
Leigh B Stoller's avatar
Leigh B Stoller committed
298 299 300 301 302 303 304 305 306 307 308 309

    #
    # 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");
310 311 312 313 314 315 316 317 318 319
	$$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 B Stoller's avatar
Leigh B Stoller committed
320 321 322 323 324 325 326 327 328
	return undef;
    }

    my $query = "insert into apt_instances set created=now(),uuid='$uuid', ".
	join(",", map("$_=" .
		      DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
329
	$$perrmsg = "Error inserting new apt_instance record for $uuid!";
Leigh B Stoller's avatar
Leigh B Stoller committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343
	return undef;
    }
    DBQueryWarn("unlock tables");
    return Lookup($class, $uuid);
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uuid  = $self->uuid();
344 345
    my $pid   = $self->pid();
    my $name  = $self->name();
Leigh B Stoller's avatar
Leigh B Stoller committed
346

347
    return "[APT_Instance: $pid,$name]";
Leigh B Stoller's avatar
Leigh B Stoller committed
348 349
}

350 351
sub LookupBySlice($$)
{
352 353
    my ($class, $token) = @_;
    my $slice_uuid;
354

355 356 357 358 359 360 361 362 363
    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);
364
	return undef
365 366
	    if (!defined($slice));
	$slice_uuid = $slice->uuid();
367
	$slice->Flush();
368 369 370
    }
    else {
	return undef;
371
    }
372

373 374 375
    my $query_result =
	DBQueryWarn("select uuid from apt_instances ".
		    "where slice_uuid='$slice_uuid'");
376
	
377 378 379 380
    return undef
	if (!$query_result || !$query_result->numrows);

    my ($uuid) = $query_result->fetchrow_array();
381 382
    my $foo = APT_Instance->Lookup($uuid);
    return $foo;
383 384
}

Leigh B Stoller's avatar
Leigh B Stoller committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
#
# 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 ".
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

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

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

    return Refresh($self);
}

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

414
    foreach my $agg ($self->AggregateList()) {
415 416 417
	$agg->Delete() == 0
	    or return -1;
    }
418
    $self->webtask()->Delete();
Leigh B Stoller's avatar
Leigh B Stoller committed
419 420 421 422 423 424
    DBQueryWarn("delete from apt_instances where uuid='$uuid'") or
	return -1;

    return 0;
}

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
#
# 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();
}

Leigh B Stoller's avatar
Leigh B Stoller committed
447 448 449 450 451 452 453 454 455 456
sub SetStatus($$)
{
    my ($self,$status) = @_;

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

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

457 458 459 460
    DBQueryWarn("update apt_instances set ".
		"  status='$status',status_timestamp=now() ".
		"where uuid='$uuid'")
	or return -1;
Leigh B Stoller's avatar
Leigh B Stoller committed
461 462 463 464

    $self->{'INSTANCE'}->{'status'} = $status;
    return 0;
    
Leigh B Stoller's avatar
Leigh B Stoller committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
}
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 B Stoller's avatar
Leigh B Stoller committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
}
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;
502 503
}

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
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;
}

540 541 542 543 544 545 546 547 548 549 550 551 552
#
# Set to use the logfile. 
#
sub SetLogFile($$)
{
    my ($self, $logfile) = @_;

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

    return 0;
}

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
#
# Set/Clear the lockdown bits.
#
sub SetLockdown($$$)
{
    my ($self,$which,$clear) = @_;

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

    my $uuid = $self->uuid();
    if ($which eq "admin") {
	$which = "admin_lockdown";
    }
    elsif ($which eq "user") {
	$which = "user_lockdown";
    }
    else {
	return -1;
    }
    my $value = ($clear ? 0 : 1);

    DBQueryWarn("update apt_instances set ${which}=${value} ".
		"where uuid='$uuid'") or
	return -1;

    $self->{'INSTANCE'}->{$which} = $value;
    return 0;
}

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
#
# 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);

    DBQueryWarn("update apt_instances set paniced=${value} ".
		(!$clear ? ",paniced_timestamp=now() " : "") .
		"where uuid='$uuid'") or
	return -1;

    $self->{'INSTANCE'}->{"paniced"} = $value;
    return 0;
}

607 608 609 610 611 612 613 614
# 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 B Stoller's avatar
Leigh B Stoller committed
615 616
}

617 618 619 620 621 622 623 624 625 626 627
#
# Find the profile for this instance.
#
sub Profile($)
{
    my ($self) = @_;
    
    return APT_Profile->Lookup($self->profile_id(),
			       $self->profile_version());
}

628 629 630 631
#
# Record a history entry.
# We do this when the instance is terminated. 
#
632
sub RecordHistory($$)
633
{
634
    my ($self, $flags) = @_;
635
    my $uuid = $self->uuid();
636
    my $expired = ($flags ? 1 : 0);
637

638 639 640 641
    DBQueryWarn("replace into apt_instance_aggregate_history ".
		"select * from apt_instance_aggregates where uuid='$uuid'")
	or return -1;

642
    DBQueryWarn("replace into apt_instance_history ".
643
		"select uuid,name,profile_id,profile_version,slice_uuid, ".
644
		"       creator,creator_idx,creator_uuid,pid,pid_idx, ".
645
		"       gid,gid_idx, ".
646 647
		"       aggregate_urn,public_url,logfileid, ".
		"       created,now(),$expired, ".
648
		"       extension_count,extension_days, ".
649
		"       physnode_count,virtnode_count, ".
650 651
		"       servername,repourl,reponame,reporef,repohash, ".
		"       rspec,script,params,manifest ".
652 653 654 655 656 657
		" from apt_instances where uuid='$uuid'")
	or return -1;

    return 0;
}

658 659 660 661 662 663 664 665 666
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, ".
667
		"       gid,gid_idx, ".
668 669
		"       created,'$exitcode',$safe_message,public_url, ".
		"       logfileid ".
670 671 672 673 674 675
		" from apt_instances where uuid='$uuid'")
	or return -1;

    return 0;
}

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

703 704 705 706 707 708 709 710
sub GetProject($)
{
    my ($self) = @_;
    require Project;
    
    return Project->Lookup($self->pid_idx());
}

711 712 713 714 715 716 717 718
sub GetGroup($)
{
    my ($self) = @_;
    require Group;
    
    return Group->Lookup($self->gid_idx());
}

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
#
# 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;
    }
745
    my $link = $self->webURL();
746 747 748 749 750 751 752 753 754
    
    $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!",
755
		     $self->Brand()->LogsEmailAddress());
756 757 758 759
    
    return 0;
}

760 761 762
#
# Go through all the manifests and count up nodes.
#
763 764 765 766 767
sub ComputeNodeCounts($)
{
    my ($self) = @_;
    my $physnode_count = 0;
    my $virtnode_count = 0;
768
    my @slivers = $self->AggregateList();
769 770
    if (!@slivers) {
	print STDERR "No slivers for $self\n";
771 772
	return -1;
    }
773 774 775 776 777 778
    foreach my $sliver (@slivers) {
	my $manifest = GeniXML::Parse($sliver->manifest());
	if (! defined($manifest)) {
	    print STDERR "Could not parse manifest for $sliver\n";
	    return -1;
	}
779 780 781
	my $pcount = 0;
	my $vcount = 0;
	
782
	foreach my $ref (GeniXML::FindNodes("n:node",
783 784 785 786
					    $manifest)->get_nodelist(),
			 GeniXML::FindNodesNS("n:vhost",
				      $manifest,
				      $GeniXML::EMULAB_NS)->get_nodelist()) {
787
	    my $virtualization_type = GeniXML::GetVirtualizationSubtype($ref);
788 789 790 791 792 793
	    my $manager_urn = GetManagerId($ref);

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

	    if (defined($virtualization_type) &&
796 797
		($virtualization_type eq "emulab-xen" ||
		 $virtualization_type eq "emulab-blockstore")) {
798
		$vcount++;
799 800
		next;
	    }
801
	    $pcount++;
802
	}
803 804 805 806 807 808
	$sliver->Update({"physnode_count" => $pcount,
			 "virtnode_count" => $vcount})
	    == 0 or return -1;
	    
	$physnode_count += $pcount;
	$virtnode_count += $vcount;
809 810 811 812 813 814 815
    }
    $self->Update({"physnode_count" => $physnode_count,
		   "virtnode_count" => $virtnode_count})
	== 0 or return -1;
    return 0;
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 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 875
#
# 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;
}

876
#
877
# Add an aggregate to an instance.
878
#
879
sub AddAggregate($$)
880
{
881 882 883
    my ($self, $aggregate_urn) = @_;

    my $aggobj = APT_Instance::Aggregate->Create($self, $aggregate_urn);
884
    return undef
885
	if (!defined($aggobj));
886

887
    $self->{'AGGREGATES'}->{$aggregate_urn} = $aggobj;
888 889 890 891 892 893 894 895 896
    return $aggobj;
}

#
# Locate the aggregate for a nodeid
#
sub FindAggregateByNodeId($$)
{
    my ($self, $node_id) = @_;
897
    my @slivers = $self->AggregateList();
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    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;
}

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
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);
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

    #
    # 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);
972 973 974 975
    
    return 0;
}

976 977 978
#
# Build a set of sshkeys.
#
979
sub GetSSHKeys($$;$)
980
{
981
    my ($self, $pref, $target_user) = @_;
982 983 984
    my $rval;
    my @keys;

985
    my $geniuser = $target_user || $self->GetGeniUser();
986 987 988 989 990
    return -1
	if (!defined($geniuser));
    my $project  = $self->GetProject();
    return -1
	if (!defined($project));
991 992 993
    my $group = $self->GetGroup();
    return -1
	if (!defined($group));
994 995 996 997 998 999 1000 1001 1002 1003 1004

    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(),
1005 1006
	      # Creator clearly has root privs!
	      'privs' => 'root',
1007 1008 1009
	      'keys'  => [ @keys ]
	     }];

1010 1011 1012 1013
    # Want keys for single user.
    goto done
	if (defined($target_user));

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    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));

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
		#
		# 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";
		    }
		}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
		#
		# 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(),
1064
				'privs' => $privs,
1065 1066 1067 1068 1069
				'keys'  => [ @keys ]
		               });
	    }
	}
    }
1070
  done:
1071 1072 1073 1074
    $$pref = $rval;
    return 0;
}

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
#
# 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;
    }
1091
    my $webtask = $self->webtask();
1092 1093 1094
    if (!defined($webtask)) {
	goto done;
    }
1095 1096 1097
    # This could be really stale, must refresh.
    $webtask->Refresh();
    
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    #
    # 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;
}

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
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, ".
		       "  extension_days=extension_days+${granted} ".
		       "where uuid='$uuid'");
}

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

    return DBQueryWarn("update apt_instances set ".
		       "  extension_count=extension_count+1, ".
		       "  extension_days=extension_days+${granted} ".
		       "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;
}

1182 1183 1184 1185 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 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
###################################################################
package APT_Instance::ExtensionInfo;
use emdb;
use Carp;
use English;
use GeniHRN;
use Data::Dumper;
use vars qw($AUTOLOAD);
use overload ('""' => 'Stringify');

#
# Lookup and create a class instance to return.
#
sub Lookup($$$)
{
    my ($class, $instance, $idx) = @_;
    my $uuid = $instance->uuid();

    my $query_result =
	DBQueryWarn("select * from apt_instance_extension_info ".
		    "where uuid='$uuid' and idx='$idx'");
    return undef
	if (! (defined($query_result) && $query_result->numrows));

    my $self            = {};
    $self->{'DBROW'}    = $query_result->fetchrow_hashref();
    $self->{'INSTANCE'} = $instance;
    bless($self, $class);

    return $self;
}

#
# Lookup the latest extension request, which is mostly what we want
# anytime we need one.
#
sub LookupMostRecent($$)
{
    my ($class, $instance) = @_;
    my $uuid = $instance->uuid();

    my $query_result =
	DBQueryWarn("select idx from apt_instance_extension_info ".
		    "where uuid='$uuid' ".
		    "order by idx desc limit 1");
    return undef
	if (! (defined($query_result) && $query_result->numrows));
    my ($idx) = $query_result->fetchrow_array();
    return Lookup($class, $instance, $idx);
}

AUTOLOAD {
    my $self  = $_[0];
    my $type  = ref($self) or confess "$self is not an object";
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
    }
    carp("No such slot '$name' field in class $type");
    return undef;
}
sub instance($)	        { return $_[0]->{'INSTANCE'}; }

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{'INSTANCE'} = undef;
    $self->{'DBROW'}    = undef;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uuid  = $self->uuid();
    my $idx   = $self->idx();

    return "[APT_Instance::ExtensionInfo: $uuid, $idx]";
}

#
# Create an Extension Info entry for an instance
#
sub Create($$$)
{
    my ($class, $instance, $argref) = @_;
    my $instance_uuid = $instance->uuid();
    my $instance_name = $instance->name();
    my $sets = join(",", map("$_=" . DBQuoteSpecial($argref->{$_}),
			     keys(%{$argref})));
    my $query = "insert into apt_instance_extension_info set tstamp=now(), ".
	"uuid='$instance_uuid',idx=NULL,name='$instance_name', $sets";
    
    DBQueryWarn($query)
	or return undef;

    return LookupMostRecent($class, $instance);
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;
    my $uuid = $self->uuid();
    my $idx  = $self->name();

    my $query = "update apt_instance_extension_info set ".
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

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

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

    return Refresh($self);
}

1308 1309 1310
###################################################################
package APT_Instance::Aggregate;
use emdb;
1311
use EmulabConstants;
1312
use WebTask;
1313
use libtestbed;
1314 1315
use Carp;
use POSIX qw(tmpnam);
1316
use JSON;
1317 1318 1319
use English;
use GeniResponse;
use Genixmlrpc;
1320 1321
use GeniXML;
use GeniHRN;
1322
use APT_Geni;
1323
use Date::Parse;
1324
use Data::Dumper;
1325 1326
use vars qw($AUTOLOAD);
use overload ('""' => 'Stringify');
1327
sub devurl($) { return APT_Instance::devurl($_[0]); }
1328

1329 1330 1331
my $OURDOMAIN = "@OURDOMAIN@";
my $MYURN     = "urn:publicid:IDN+$OURDOMAIN+authority+cm";

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
#
# Lookup and create a class instance to return.
#
sub Lookup($$$)
{
    my ($class, $instance, $urn) = @_;
    my $uuid = $instance->uuid();

    my $query_result =
	DBQueryWarn("select * from apt_instance_aggregates ".
		    "where uuid='$uuid' and aggregate_urn='$urn'");
1343
    return undef
1344
	if (! (defined($query_result) && $query_result->numrows));
1345

1346 1347 1348 1349 1350
    my $self            = {};
    $self->{'FAKE'}     = 0;
    $self->{'DBROW'}    = $query_result->fetchrow_hashref();
    $self->{'HASH'}     = {};
    $self->{'INSTANCE'} = $instance;
1351 1352
    $self->{'WEBTASK'}  = undef;
    $self->{'STATUS'}   = undef;
1353 1354
    bless($self, $class);

1355 1356 1357 1358 1359
    # Handy;
    $self->{'AGGURN'}   = GeniHRN->new($self->aggregate_urn());

    # Kludge
    $self->{'ISAL2S'}   = ($self->aggregate_urn() =~ /al2s/ ? 1 : 0);
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    return $self;
}

AUTOLOAD {
    my $self  = $_[0];
    my $type  = ref($self) or confess "$self is not an object";
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'DBROW'}->{$name})) {
	return $self->{'DBROW'}->{$name};
    }
    # 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};
	}
    }
    carp("No such slot '$name' field in class $type");
    return undef;
}
sub instance($)	        { return $_[0]->{'INSTANCE'}; }
1386 1387
sub domain($)		{ return $_[0]->{'AGGURN'}->domain(); }
sub isAL2S($)           { return $_[0]->{'ISAL2S'}; }
1388

1389 1390 1391 1392 1393 1394 1395 1396 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 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
#
# Grab the webtask.
#
sub webtask($)
{
    my ($self) = @_;

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

    my $webtask = WebTask->Lookup($self->webtask_id());
    return undef
	if (!defined($webtask));
    $self->{'WEBTASK'} = $webtask;
    $webtask->AutoStore(1);
    return $webtask;
}

#
# Get sliver status rows. Turn into a class at some point.
#
sub SliverStatus($)
{
    my ($self) = @_;
    my $result        = {};
    my $uuid          = $self->uuid();
    my $aggregate_urn = $self->aggregate_urn();

    my $query_result = 
	DBQueryWarn("select * from apt_instance_sliver_status ".
		    "where uuid='$uuid' and aggregate_urn='$aggregate_urn'");
    return $result
	if (!$query_result);

    while (my $row = $query_result->fetchrow_hashref()) {
	my $json = $row->{"sliver_data"};
	my $hash = eval { decode_json($json) };
	if ($@) {
	    print STDERR "Could not decode json data: $json\n";
	    next;
	}
	$row->{"sliver_data"} = $hash;
	$result->{$row->{"client_id"}} = $row;
    }
    return $result;
}

#
# Delete sliver status for a node.
#
sub DeleteSliverStatus($$)
{
    my ($self, $client_id) = @_;
    my $uuid          = $self->uuid();
    my $aggregate_urn = $self->aggregate_urn();
    my $safe_clientid = DBQuoteSpecial($client_id);

    DBQueryWarn("delete from apt_instance_sliver_status ".
		"where uuid='$uuid' and aggregate_urn='$aggregate_urn' and ".
		"      client_id=$safe_clientid")
	or return -1;

    return 0;
}

1454 1455 1456 1457
# Backwards compat for a while
sub GenTemp($$)
{
    my ($class, $instance) = @_;
1458
    my $webtask = $instance->webtask();
1459 1460 1461
    if (!defined($webtask)) {
	$webtask = WebTask->Create($instance->uuid());
    }
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    $webtask->AutoStore(1);
    
    my $self            = {};
    $self->{'FAKE'}     = 1;
    $self->{'DBROW'}    = {
	"uuid" => $instance->uuid(),
	"name" => $instance->name(),
	"aggregate_urn" => $instance->aggregate_urn(),
	"status" => $instance->status(),
	"public_url" => $instance->public_url(),
	"manifest" => $instance->manifest(),
	"webtask_id" => $webtask->task_id(),
1474
    };
1475 1476 1477
    $self->{'INSTANCE'} = $instance;
    $self->{'WEBTASK'}  = $webtask;
    $self->{'HASH'}     = {};
1478
    $self->{'ISAL2S'}   = 0;
1479 1480 1481 1482
    bless($self, $class);
    
    return $self;
}
1483

1484 1485 1486 1487 1488 1489
#
# Lookup all aggregates for an instance
#
sub LookupForInstance($$)
{
    my ($class, $instance) = @_;
1490
    my $result = {};
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
    my $uuid   = $instance->uuid();

    my $query_result =
	DBQueryWarn("select aggregate_urn from apt_instance_aggregates ".
		    "where uuid='$uuid'");
    return ()
	if (! (defined($query_result) && $query_result->numrows));

    while (my ($aggregate_urn) = $query_result->fetchrow_array()) {
	my $agg = Lookup($class, $instance, $aggregate_urn);
	if (!defined($agg)) {
	    print STDERR "No apt_instance_aggregate for $uuid/$aggregate_urn\n";
	    return ();
	}
1505
	$result->{$aggregate_urn} = $agg;
1506
    }
1507
    return $result;
1508
}
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{'INSTANCE'} = undef;
    $self->{'DBROW'}    = undef;
    $self->{'WEBTASK'}  = undef;
    $self->{'HASH'}     = undef;
}

#
# Stringify for output.
#
sub Stringify($)
1524
{
1525 1526 1527 1528
    my ($self) = @_;
    
    my $uuid  = $self->uuid();
    my $urn   = $self->aggregate_urn();
1529

1530
    return "[APT_Instance::Aggregate: $uuid, $urn]";
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
}

#
# Create an Instance Aggregate.
#
sub Create($$$)
{
    my ($class, $instance, $aggregate_urn) = @_;
    my $instance_uuid = $instance->uuid();
    my $instance_name = $instance->name();

1542 1543
    # XXX Anonymous is the wrong thing to do here, but we do not have
    # a unique uuid to use.
1544
    my $webtask = WebTask->Create(undef);
1545
    return undef
1546 1547
	if (!defined($webtask));
    my $webtask_id = $webtask->task_id();
1548

1549 1550 1551 1552 1553
    DBQueryWarn("insert into apt_instance_aggregates set ".
		"  uuid='$instance_uuid', name='$instance_name', ".
		"  webtask_id='$webtask_id', ".
		"  aggregate_urn='$aggregate_urn', status='created'")
	or return undef;
1554

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    return Lookup($class, $instance, $aggregate_urn);
}

#
# Delete by instance aggregate
#
sub Delete($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();
    my $urn  = $self->aggregate_urn();
    
1567 1568 1569
    $self->webtask()->Delete()
	if ($self->webtask()->Delete());
    
1570 1571 1572
    return 0
	if ($self->{'FAKE'});
    
1573 1574 1575 1576 1577 1578 1579 1580
    DBQueryWarn("delete from apt_instance_slice_status ".
		"where uuid='$uuid' and aggregate_urn='$urn'")
	or return -1;

    DBQueryWarn("delete from apt_instance_sliver_status ".
		"where uuid='$uuid' and aggregate_urn='$urn'")
	or return -1;

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    DBQueryWarn("delete from apt_instance_aggregates ".
		"where uuid='$uuid' and aggregate_urn='$urn'")
	or return -1;

    return 0;
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    my $uuid = $self->uuid();
    my $urn  = $self->aggregate_urn();
    
    my $query_result =
	DBQueryWarn("select * from apt_instance_aggregates ".
		    "where uuid='$uuid' and aggregate_urn='$urn'");

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

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

    return -1
1608
	if (defined($self->{'WEBTASK'}) && $self->webtask()->Refresh());
1609 1610 1611 1612

    return 0;
}

1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

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

    my $query = "update apt_instance_aggregates set ".
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

    $query .= " where uuid='$uuid' and aggregate_urn='$urn'";

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

    return Refresh($self);
}

1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
#
# Is the sliver on the local cluster.
#
sub OnLocalCluster($)
{
    my ($self) = @_;

    return $self->aggregate_urn() eq $MYURN ? 1 : 0;
}

1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
sub SetStatus($$)
{
    my ($self,$status) = @_;

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

    DBQueryWarn("update apt_instance_aggregates set status='$status' ".
		"where uuid='$uuid' and aggregate_urn='$urn'") or
	return -1;

    $self->{'DBROW'}->{'status'} = $status;
    return 0;
    
}
sub SetPublicURL($$)
{
    my ($self,$url) = @_;
    my $safe_url = DBQuoteSpecial($url);

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

    DBQueryWarn("update apt_instance_aggregates set public_url=$safe_url ".
		"where uuid='$uuid' and aggregate_urn='$urn'") or
	return -1;

    $self->{'DBROW'}->{'public_url'} = $url;
    return 0;
    
}
sub SetManifest($$)
{
1681
    my ($self,$manifest_string) = @_;
1682 1683 1684

    my $uuid = $self->uuid();
    my $urn  = $self->aggregate_urn();
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

    #
    # Jacks cannot handle the stitching section, so remove it for now.
    #
    my $manifest = GeniXML::Parse($manifest_string);
    if (! defined($manifest)) {
	print STDERR "Could not parse manifest for $urn\n";
	print STDERR $manifest_string;
	return -1;
    }
    my $stitching = GeniXML::FindNodesNS("n:stitching",
					 $manifest, $GeniXML::STITCH_NS)->pop();
    if (defined($stitching)) {
	$manifest->removeChild($stitching);
	$manifest_string = GeniXML::Serialize($manifest);
    }
    my $safe_manifest = DBQuoteSpecial($manifest_string);
1702 1703 1704 1705 1706

    DBQueryWarn("update apt_instance_aggregates set manifest=$safe_manifest ".
		"where uuid='$uuid' and aggregate_urn='$urn'") or
	return -1;

1707
    $self->{'DBROW'}->{'manifest'} = $manifest_string;
1708 1709 1710 1711 1712 1713 1714 1715 1716
    return 0;
}

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

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

1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
#
# Update the sliverstatus in the webtask. 
#
sub UpdateWebStatus($$)
{
    my ($self, $hash) = @_;

    DBQueryWarn("lock tables web_tasks write")
	or return {};

    $self->webtask()->Refresh();
    my $current = $self->webtask()->sliverstatus();
    if (!defined($current)) {
	$current = {};
    }

1735 1736 1737
#    print Dumper($hash);
#    print Dumper($current);

1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    #
    # 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 node state 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).
    #
    foreach my $urn (keys(%{ $hash })) {
	my $details = $hash->{$urn};
	my $node_id = $details->{'client_id'};
	
	if (!exists($current->{$node_id}) ||
	    !exists($current->{$node_id}->{"utc"}) ||
	    !exists($details->{"utc"}) ||
	    $details->{"utc"} >= $current->{$node_id}->{"utc"}) {