GeniResource.pm.in 41.7 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# GENIPUBLIC-COPYRIGHT
4
# Copyright (c) 2008-2010 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
# All rights reserved.
#
package GeniResource;

#
# Mapping between geni resources and Emulab resources.
#
use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

use GeniDB;
use Genixmlrpc;
use GeniResponse;
use GeniRegistry;
use GeniTicket;
use GeniCredential;
use GeniAuthority;
use GeniComponent;
use GeniUser;
use GeniHRN;
use emutil qw(TBGetUniqueIndex);
use User;
use Project;
use Group;
use Node;
use Interface;
use English;
use XML::Simple;
37 38
use Date::Parse;
use Data::Dumper;
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
use POSIX qw(strftime);
use overload ('""' => 'Stringify');

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
my $SACERT         = "$TB/etc/genisa.pem";

#
# Lookup by uuid.
#
sub Lookup($$;$)
{
    my ($class, $arg1, $arg2) = @_;
    my $query_result;

    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
	    $query_result =
		DBQueryWarn("select * from geni_resources ".
			    "where idx='$arg1'");
	}
	else {
	    return undef;
	}
    }
    elsif (($arg1 =~ /^\d*$/) && GeniHRN::IsValid($arg2)) {
	$query_result =
	    DBQueryWarn("select * from geni_resources ".
			"where exptidx='$arg1' and manager_urn='$arg2'");
    }
    else {
	return undef;
    }
    return undef
	if (!$query_result || !$query_result->numrows);

    my $self              = {};
    $self->{'DBROW'}      = $query_result->fetchrow_hashref();
    $self->{'NEWTICKET'}  = undef;
83 84 85
    $self->{'manager_version'}    = undef;
    $self->{'rspec_fragment'}     = undef;
    $self->{'last_rpcerror'}	  = 0;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    bless($self, $class);

    return $self;
}

#
# Lookup by experiment.
#
sub LookupAll($$)
{
    my ($class, $arg1) = @_;

    if (ref($arg1)) {
	$arg1 = $arg1->idx();
    }
    my $query_result =
	DBQueryWarn("select idx from geni_resources where exptidx='$arg1'");

    return undef
	if (!$query_result);
    return ()
	if (!$query_result->numrows);

    my @result = ();

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $resource = GeniResource->Lookup($idx);
	if (!defined($resource)) {
	    print STDERR "Could not get GeniResource for $idx\n";
	    return undef
	}
	push(@result, $resource);
    }
    return @result;
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
sub SliceResources($)
{
    my ($class, $slice) = @_;
    my $slice_idx = $slice->idx();

    my $query_result =
	DBQueryWarn("select idx from geni_resources ".
		    "where slice_idx='$slice_idx'");

    return undef
	if (!$query_result);
    return ()
	if (!$query_result->numrows);

    my @result = ();

    while (my ($idx) = $query_result->fetchrow_array()) {
	my $resource = GeniResource->Lookup($idx);
	if (!defined($resource)) {
	    print STDERR "Could not get GeniResource for $idx\n";
	    return undef
	}
	push(@result, $resource);
    }
    return @result;
}

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $idx = $self->idx();
    my $urn = $self->manager_urn();

    return "[GeniResource: $idx, $urn]";
}

#
# Create a GeniResource in the DB.
#
sub Create($$$)
{
    my ($class, $experiment, $manager_urn) = @_;
    my @insert_data = ();

    my $slice = GeniSlice->LookupByExperiment($experiment);
    if (!defined($slice)) {
	print STDERR "*** GeniResource::Create: ".
	    "No slice registered for $experiment\n";
	return undef;
    }

    # Every one gets a new unique index.
    my $idx = TBGetUniqueIndex('next_geniidx', 1);

    my $safe_urn = DBQuoteSpecial($manager_urn);
    my $pid      = $experiment->pid();
    my $eid      = $experiment->eid();
    my $exptidx  = $experiment->idx();
    my $slice_idx= $slice->idx();
    
    # Now tack on other stuff we need.
    push(@insert_data, "idx='$idx'");
    push(@insert_data, "slice_idx='$slice_idx'");
    push(@insert_data, "created=now()");
    push(@insert_data, "manager_urn=$safe_urn");
    push(@insert_data, "pid='$pid'");
    push(@insert_data, "eid='$eid'");
    push(@insert_data, "exptidx=$exptidx");

    # Insert into DB.
    DBQueryWarn("replace into geni_resources set " . join(",", @insert_data))
	or return undef;

    return GeniResource->Lookup($idx);
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'DBROW'}->{$_[1]}); }
sub idx($)		{ return field($_[0], "idx"); }
sub exptidx($)		{ return field($_[0], "exptidx"); }
sub pid($)		{ return field($_[0], "pid"); }
sub eid($)		{ return field($_[0], "eid"); }
sub created($)          { return field($_[0], "created"); }
sub updated($)          { return field($_[0], "updated"); }
209
sub expires($)          { return field($_[0], "expires"); }
210 211 212 213 214 215
sub manager_urn($)      { return field($_[0], "manager_urn"); }
sub slice_idx($)        { return field($_[0], "slice_idx"); }
sub credential_idx($)   { return field($_[0], "credential_idx"); }
sub manifest_idx($)     { return field($_[0], "manifest_idx"); }
sub ticket_idx($)       { return field($_[0], "ticket_idx"); }
sub newticket_idx($)    { return field($_[0], "newticket_idx"); }
216 217
sub manager_version($)  { return $_[0]->{'manager_version'}; }
sub last_rpcerror($)    { return $_[0]->{'last_rpcerror'}; }
218 219

#
220
# Delete a resource record from the DB.
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 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 284 285 286 287 288 289 290 291 292 293 294 295 296
#
sub Delete($)
{
    my ($self) = @_;

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

    my $idx = $self->idx();
    DBQueryWarn("delete from geni_resources ".
		"where idx='$idx'")
	or return -1;

    return 0;
}

#
# Compare two refs.
#
sub SameResource($$)
{
    my ($self, $other) = @_;

    return 0
	if (! (ref($self) && ref($other)));

    return $self->idx() eq $other->idx();
}

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

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

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

    my $query_result =
	DBQueryWarn("select * from geni_resources where idx='$idx'");

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

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

#
# Update Fields.
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

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

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

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

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

    return Refresh($self);
}

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
#
# Set the expiration time.
#
sub SetExpiration($$)
{
    my ($self, $expires) = @_;
    my $idx = $self->idx();

    if (!defined($expires)) {
	$expires = "NULL";
    }
    elsif ($expires =~ /^\d+$/) {
	$expires = "FROM_UNIXTIME($expires)";
    }
    else {
	$expires = "'$expires'";
    }
    my $query_result =
	DBQueryWarn("update geni_resources set expires=$expires " .
		    "where idx='$idx'");
    
    return -1
	if (!$query_result);

    # Has to be in the correct format.
    $query_result =
	DBQueryWarn("select expires from geni_resources where idx='$idx'");
    return -1
	if (!$query_result || !$query_result->numrows);
    ($expires) = $query_result->fetchrow_array();
    
    $self->{'DBROW'}->{'expires'} = $expires;
    return 0;
}

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
#
# Return the ticket.
#
sub Ticket($)
{
    my ($self) = @_;

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

    if (!$self->newticket_idx()) {
	print STDERR "*** No new ticket defined for $self.\n";
	return undef;
    }
    my $ticket = GeniTicket->Lookup($self->newticket_idx());
    if (!defined($ticket)) {
	print STDERR "*** Could not get new ticket for $self.\n";
	return undef;
    }
    $self->{'NEWTICKET'} = $ticket;
    return $ticket;
}

sub Manifest($)
{
    my ($self) = @_;

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

    if (!$self->manifest_idx()) {
	print STDERR "*** No manifest defined for $self.\n";
	return undef;
    }
    my $manifest_idx = $self->manifest_idx();

    my $query_result =
	DBQueryWarn("select manifest from geni_manifests ".
		    "where idx=$manifest_idx");
    if (!$query_result || !$query_result->numrows) {
	print STDERR "Could not locate manifest for $self\n";
	return undef;
    }
    my ($manifest_string) = $query_result->fetchrow_array();
376 377 378 379
    my $manifest = XMLin($manifest_string, KeyAttr => [],
			 ForceArray => ["node", "link", "interface",
					"interface_ref", "linkendpoints",
					"component_manager"]);
380

381 382
    $self->{'MANIFEST'}    = $manifest;
    $self->{'MANIFESTSTR'} = $manifest_string;
383 384 385
    return $manifest;
}

386 387 388 389 390 391 392 393 394
sub UpdateManifest($$)
{
    my ($self, $manifest) = @_;

    if (! $self->manifest_idx()) {
	print STDERR "No manifest to update for $self\n";
	return -1;
    }
    my $manifest_idx = $self->manifest_idx();
395 396 397 398 399 400 401
    my $manifest_string =
	eval { XMLout($manifest, "NoAttr" => 1, RootName => "manifest") };
    if ($@) {
	print STDERR "UpdateManifest: XMLout error: $@\n";
	print STDERR Dumper($manifest);
	return -1;
    }
402 403 404 405 406 407 408 409 410 411 412 413 414
    my $query_result =
	DBQueryWarn("update geni_manifests set ".
		    "  manifest=". DBQuoteSpecial($manifest_string) . ", " .
		    "  created=now() ".
		    "where idx=$manifest_idx");
    return -1
	if (!defined($query_result));

    $self->{'MANIFEST'}    = $manifest;
    $self->{'MANIFESTSTR'} = $manifest_string;
    return 0;
}

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
#
# Get Version. Ask the CM what version it is running. 
#
sub ManagerVersion($)
{
    my ($self) = @_;

    return $self->manager_version()
	if (defined($self->manager_version()));

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

    #
    # Load the SA cert to act as caller context.
    #
    my $certificate = GeniCertificate->LoadFromFile($SACERT);
    if (!defined($certificate)) {
	print STDERR "*** Could not load certificate from $SACERT\n";
	return undef;
    }
    my $context = Genixmlrpc->Context($certificate);
    if (!defined($context)) {
	print STDERR "*** Could not create context to talk to clearinghouse\n";
	return undef;
    }
    #
    # Set the default RPC context. 
    #
    Genixmlrpc->SetContext($context);

    my $authority = GeniAuthority->Lookup($manager_urn);
    if (!defined($authority)) {
	$authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
	if (!defined($authority)) {
	    print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	    return undef;
	}
    }
    $self->{'manager_version'} = $authority->Version();
    return $self->{'manager_version'};
}
456

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
#
# Add Resources. We get an rspec to replace the current rspec.
# Ask for a ticket, and then redeem it.
#
sub GetTicket($$$$)
{
    my ($self, $user, $rspec, $impotent) = @_;
    my $ticket;
    my $response;

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "*** AddResources: No slice for $self\n";
	return -1;
    }
    my $manager_urn = $self->manager_urn();

474 475 476 477 478
    my $rspec_string = eval { XMLout($rspec, "NoAttr" => 1) };
    if ($@) {
	print STDERR "GetTicket: XMLout error: $@\n";
	print STDERR Dumper($rspec);
	return -1;
479
    }
480
    $rspec_string =~ s/opt\>/rspec\>/g;
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

    #
    # Load the SA cert to act as caller context.
    #
    my $certificate = GeniCertificate->LoadFromFile($SACERT);
    if (!defined($certificate)) {
	print STDERR "*** Could not load certificate from $SACERT\n";
	return -1;
    }
    my $context = Genixmlrpc->Context($certificate);
    if (!defined($context)) {
	print STDERR "*** Could not create context to talk to clearinghouse\n";
	return -1;
    }
    #
    # Set the default RPC context. 
    #
    Genixmlrpc->SetContext($context);

500
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
501
    if (!defined($authority)) {
502 503
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
504
    }
505
    my $manager_version = $self->ManagerVersion();
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

    #
    # Generate a slice credential for the user. 
    #
524 525 526 527
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    if (!defined($slice_credential)) {
	print STDERR
	    "*** Could not create a slice credential for $slice/$geniuser!\n";
	return -1;
    }

    #
    # Load sliver credential if we have it.
    #
    my $sliver_credential;
    if ($self->credential_idx()) {
	$sliver_credential = GeniCredential->Lookup($self->credential_idx());
	if (!defined($sliver_credential)) {
	    print STDERR "*** Could not get sliver credential for $self.\n";
	    return -1;
	}
    }

546 547 548
    my $method_name = undef;
    my $method_args = {};

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    #
    # Already have a credential for a sliver, then we want to update
    # the existing ticket we also have on file, and then redeem that.
    #
    if (defined($sliver_credential)) {
	if ($self->newticket_idx()) {
	    print STDERR "*** Still have a new ticket defined for $self.\n";
	    return -1;
	}
	if (!$self->ticket_idx()) {
	    print STDERR "*** No ticket defined for $self.\n";
	    return -1;
	}
	$ticket = GeniTicket->Lookup($self->ticket_idx());
	if (!defined($ticket)) {
	    print STDERR "*** Could not get ticket for $self.\n";
	    return -1;
	}
567 568
	$method_name = "UpdateTicket";
	$method_args->{'ticket'} = $ticket->asString();
569 570
    }
    else {
571
	$method_name = "GetTicket";
572
    }
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    $method_args->{'impotent'} = $impotent;
    $method_args->{'rspec'}    = $rspec_string;
    if ($manager_version == 1.0) {
	$method_args->{'credential'} = $slice_credential->asString();
    }
    elsif ($manager_version == 2.0) {
	$method_args->{'credentials'} = [$slice_credential->asString()];
	$method_args->{'slice_urn'}   = $slice->urn();
    }
    else {
	print STDERR "GeniResource::GetTicket Unknown version at $authority\n";
	return -1;
    }
    $response =
	Genixmlrpc::CallMethod($authority->url(), $usercontext,
			       $method_name, $method_args);
589
    if (!defined($response)) {
590
	$self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
591 592 593
	print STDERR "*** Internal error getting/updating ticket for $self\n";
	return -1;
    }
594
    $self->{'last_rpcerror'} = $response->code();
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	if ($ticket) {
	    print STDERR "Could not update ticket $ticket. Error: ";
	}
	else {
	    print STDERR "Could not get new ticket. Error: ";
	}
	print STDERR "  " . $response->output() . "\n";
	return -1;
    }
    my $newticket = GeniTicket->CreateFromSignedTicket($response->value());
    if (!defined($newticket)) {
	print STDERR "*** Cannot create new ticket object from:\n";
	print STDERR $response->value() . "\n";
	return -1;
    }
611
    $newticket->SetSlice($slice);
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    if ($newticket->Store(TICKET_NOSTATS) != 0) {
	print STDERR "*** Could not store $newticket\n";
	return -1;
    }
    $self->Update({"newticket_idx" => $newticket->idx()});
    $self->{'NEWTICKET'} = $newticket;

    return 0;
}

#
# Redeem the ticket.
#
sub RedeemTicket($$)
{
    my ($self, $user) = @_;
    my $response;

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "*** AddResources: No slice for $self\n";
	return -1;
    }
    my $manager_urn = $self->manager_urn();

    #
    # Load the SA cert to act as caller context.
    #
    my $certificate = GeniCertificate->LoadFromFile($SACERT);
    if (!defined($certificate)) {
	print STDERR "*** Could not load certificate from $SACERT\n";
	return -1;
    }
    my $context = Genixmlrpc->Context($certificate);
    if (!defined($context)) {
	print STDERR "*** Could not create context to talk to clearinghouse\n";
	return -1;
    }
    #
    # Set the default RPC context. 
    #
    Genixmlrpc->SetContext($context);

655
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
656
    if (!defined($authority)) {
657 658
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
659
    }
660
    my $manager_version = $self->ManagerVersion();
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

    my @keys;
677
    if ($geniuser->GetKeyBundle(\@keys) != 0) {
678 679 680 681 682 683 684
	print STDERR "Could not get keys for $geniuser\n";
	return -1;
    }

    #
    # Generate a slice credential for the user. 
    #
685 686 687 688
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    if (!defined($slice_credential)) {
	print STDERR
	    "*** Could not create a slice credential for $slice/$geniuser!\n";
	return -1;
    }

    #
    # Load sliver credential if we have it.
    #
    my $sliver_credential;
    if ($self->credential_idx()) {
	$sliver_credential = GeniCredential->Lookup($self->credential_idx());
	if (!defined($sliver_credential)) {
	    print STDERR "*** Could not get sliver credential for $self.\n";
	    return -1;
	}
    }

    if (!$self->newticket_idx()) {
	print STDERR "*** No ticket defined for $self.\n";
	return -1;
    }
    my $ticket = GeniTicket->Lookup($self->newticket_idx());
    if (!defined($ticket)) {
	print STDERR "*** Could not get new ticket for $self.\n";
	return -1;
    }
    my $oldticket;
    if ($self->ticket_idx()) {
	$oldticket = GeniTicket->Lookup($self->ticket_idx());
	if (!defined($oldticket)) {
	    print STDERR "*** Could not get old ticket for $self.\n";
	    return -1;
	}
    }
    
    #
    # Redeem it. 
    #
728 729 730 731 732 733 734 735 736 737 738 739
    my $method_name = "RedeemTicket";
    my $method_args = { "ticket"     => $ticket->asString(),
			"keys"       => \@keys };

    if ($manager_version == 1.0) {
	$method_name = "UpdateSliver"
	    if (defined($sliver_credential));
	$method_args->{'credential'} = $slice_credential->asString();
    }
    elsif ($manager_version == 2.0) {
	$method_args->{'credentials'} = [$slice_credential->asString()];
	$method_args->{'slice_urn'}   = $slice->urn();
740 741
    }
    else {
742 743 744
	print STDERR
	    "GeniResource::RedeemTicket Unknown version at $authority\n";
	return -1;
745
    }
746 747 748
    $response =
	Genixmlrpc::CallMethod($authority->url(), $usercontext,
			       $method_name, $method_args);
749
    if (!defined($response)) {
750
	$self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
751 752 753 754
	print STDERR
	    "*** Internal error redeeming/updating sliver for $self\n";
	return -1;
    }
755
    $self->{'last_rpcerror'} = $response->code();
756 757 758 759 760 761 762 763 764 765
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	if ($sliver_credential) {
	    print STDERR "Could not update sliver $sliver_credential Error: ";
	}
	else {
	    print STDERR "Could not redeem ticket $ticket. Error: ";
	}
	print STDERR "  " . $response->output() . "\n";
	return -1;
    }
766 767 768 769 770 771
    #
    # It worked, so mark the expiration time for the resource.
    #
    if ($self->SetExpiration($slice->expires())) {
	print STDERR "RenewAll: Could not set expiration for $self!\n";
    }
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 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 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

    #
    # Okay, so that worked. Store the new credential and the ticket and
    # the manifest.
    #
    my $manifest;
    if (!defined($sliver_credential)) {
	my $credstring;
	($credstring,$manifest) = @{ $response->value() };

	$sliver_credential = GeniCredential->CreateFromSigned($credstring);
	if (!defined($sliver_credential)) {
	    print STDERR
		"** Could not create new credential from $credstring\n";
	    return -1;
	}
	if ($sliver_credential->Store()) {
	    print STDERR "** Could not store $sliver_credential\n";
	    return -1;
	}
	$self->Update({"credential_idx" => $sliver_credential->idx()});
    }
    else {
	$manifest = $response->value();
    }
    if (defined($oldticket)) {
	$oldticket->Delete(TICKET_DELETED);
    }
    $self->Update({"newticket_idx" => 0,
		   "ticket_idx"    => $ticket->idx()});
	
    #
    # Move this elsewhere.
    #
    my $manifest_idx = ($self->manifest_idx() ?
			$self->manifest_idx() : "NULL");
    my $sliver_uuid  = $sliver_credential->uuid();
    my $query_result =
	DBQueryWarn("replace into geni_manifests set ".
		    "  manifest=". DBQuoteSpecial($manifest) . ", " .
		    "  idx=$manifest_idx, slice_uuid='$sliver_uuid', ".
		    "  created=now()");
    return -1
	if (!defined($query_result));

    if (!$self->manifest_idx()) {
	$manifest_idx = $query_result->insertid;
	
	$self->Update({"manifest_idx" => $manifest_idx});
    }
    return 0;
}

#
# Clear all resources. 
#
sub Clear($$)
{
    my ($self, $user) = @_;
    my $response;

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "*** ClearResources: No slice for $self\n";
	return -1;
    }
    my $manager_urn = $self->manager_urn();

    #
    # Load the SA cert to act as caller context.
    #
    my $certificate = GeniCertificate->LoadFromFile($SACERT);
    if (!defined($certificate)) {
	print STDERR "*** Could not load certificate from $SACERT\n";
	return -1;
    }
    my $context = Genixmlrpc->Context($certificate);
    if (!defined($context)) {
	print STDERR "*** Could not create context to talk to clearinghouse\n";
	return -1;
    }
    #
    # Set the default RPC context. 
    #
    Genixmlrpc->SetContext($context);

858
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
859
    if (!defined($authority)) {
860 861
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
862
    }
863
    my $manager_version = $self->ManagerVersion();
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

879 880 881 882 883 884 885 886 887 888 889 890 891 892
    #
    # Generate a slice credential for the user. 
    #
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
    if (!defined($slice_credential)) {
	print STDERR
	    "*** Could not create a slice credential for ".
	    "$slice/$geniuser!\n";
	return -1;
    }

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    #
    # Load sliver credential if we have it.
    #
    my $sliver_credential;
    if ($self->credential_idx()) {
	$sliver_credential = GeniCredential->Lookup($self->credential_idx());
	if (!defined($sliver_credential)) {
	    print STDERR "*** Could not get sliver credential for $self.\n";
	    return -1;
	}
    }
    my $newticket;
    if ($self->newticket_idx()) {
	$newticket = GeniTicket->Lookup($self->newticket_idx());
	if (!defined($newticket)) {
	    print STDERR "*** Could not get new ticket for $self.\n";
	    return -1;
	}
    }
    my $oldticket;
    if ($self->ticket_idx()) {
	$oldticket = GeniTicket->Lookup($self->ticket_idx());
	if (!defined($oldticket)) {
	    print STDERR "*** Could not get old ticket for $self.\n";
	    return -1;
	}
    }

    if (defined($sliver_credential)) {
922 923
	my $method_name = "DeleteSlice";
	my $method_args = undef;
924

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
	if ($manager_version == 1.0) {
	    $method_args->{'credential'} = $slice_credential->asString();
	}
	elsif ($manager_version == 2.0) {
	    $method_args->{'credentials'} = [$slice_credential->asString()];
	    $method_args->{'slice_urn'}   = $slice->urn();
	}
	else {
	    print STDERR
		"GeniResource::Clear Unknown version at $authority\n";
	    return -1;
	}
	print STDERR "Deleting sliver on $authority\n";
	$response =
	    Genixmlrpc::CallMethod($authority->url(), $usercontext,
				   $method_name, $method_args);
941
	if (!defined($response)) {
942
	    $self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
943 944 945
	    print STDERR "*** Internal error deleting sliver for $self\n";
	    return -1;
	}
946
	$self->{'last_rpcerror'} = $response->code();
947 948 949 950 951 952 953 954 955
	if ($response->code() != GENIRESPONSE_SUCCESS &&
	    $response->code() != GENIRESPONSE_SEARCHFAILED) {
	    print STDERR "Could not delete sliver for $self. Error: ";
	    print STDERR "  " . $response->output() . "\n";
	    return -1;
	}
	$sliver_credential->Delete();
	$self->Update({"credential_idx" => 0});

956
	#
957
	# Delete this now; no point in waiting for the CM to tell us.
958
	#
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
	# Needs to move elsewhere I think.
	#
	my $clientsliver =
	    GeniRegistry::ClientSliver->LookupByAuthority($slice,
							  $manager_urn);
	$clientsliver->Delete()
	    if (defined($clientsliver));
    }

    if (defined($newticket)) {
	my $method_name = "ReleaseTicket";
	my $method_args = { "ticket" => $newticket->asString() };

	if ($manager_version == 1.0) {
	    $method_args->{'credential'} = $slice_credential->asString();
	}
	elsif ($manager_version == 2.0) {
	    $method_args->{'credentials'} = [$slice_credential->asString()];
	    $method_args->{'slice_urn'}   = $slice->urn();
	}
	else {
980
	    print STDERR
981
		"GeniResource::Clear Unknown version at $authority\n";
982 983
	    return -1;
	}
984
	print STDERR "Deleting $newticket on $authority\n";
985
	$response =
986 987
	    Genixmlrpc::CallMethod($authority->url(), $usercontext,
				   $method_name, $method_args);
988
	if (!defined($response)) {
989
	    $self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
990 991 992
	    print STDERR "*** Internal error releasing ticket for $self\n";
	    return -1;
	}
993
	$self->{'last_rpcerror'} = $response->code();
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 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
	if ($response->code() != GENIRESPONSE_SUCCESS &&
	    $response->code() != GENIRESPONSE_SEARCHFAILED) {
	    print STDERR "Could not release ticket for $self. Error: ";
	    print STDERR "  " . $response->output() . "\n";
	    return -1;
	}
	$newticket->Delete(TICKET_DELETED);
	$self->Update({"newticket_idx" => 0});
    }
    if (defined($oldticket)) {
	$oldticket->Delete(TICKET_DELETED);
	$self->Update({"ticket_idx" => 0});
    }

    #
    # Move this elsewhere.
    #
    if ($self->manifest_idx()) {
	my $manifest_idx = $self->manifest_idx();

	DBQueryWarn("delete from geni_manifests ".
		    "where idx=$manifest_idx");
	
	$self->Update({"manifest_idx" => 0});
    }
    return 0;
}

#
# Purge all resources. 
#
sub Purge($$)
{
    my ($self, $user) = @_;
    my $response;

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "*** ClearResources: No slice for $self\n";
	return -1;
    }
    my $manager_urn = $self->manager_urn();
1036
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
1037
    if (!defined($authority)) {
1038 1039
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
1040
    }
1041
    my $manager_version = $self->ManagerVersion();
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

    #
    # Generate a slice credential for the user. 
    #
1060 1061 1062 1063
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    if (!defined($slice_credential)) {
	print STDERR
	    "*** Could not create a slice credential for $slice/$geniuser!\n";
	return -1;
    }

    if ($self->credential_idx()) {
	my $sliver_credential =
	    GeniCredential->Lookup($self->credential_idx());
	if (defined($sliver_credential)) {
	    $sliver_credential->Delete();	
	    $self->Update({"credential_idx" => 0});
	}
    }
    if ($self->newticket_idx()) {
	my $newticket = GeniTicket->Lookup($self->newticket_idx());
	if (defined($newticket)) {
	    $newticket->Delete(TICKET_DELETED);
	    $self->Update({"newticket_idx" => 0});
	}
    }
    if ($self->ticket_idx()) {
	my $ticket = GeniTicket->Lookup($self->ticket_idx());
	if (defined($ticket)) {
	    $ticket->Delete(TICKET_DELETED);
	    $self->Update({"ticket_idx" => 0});
	}
    }
    #
    # Move this elsewhere.
    #
    if ($self->manifest_idx()) {
	my $manifest_idx = $self->manifest_idx();

	DBQueryWarn("delete from geni_manifests ".
		    "where idx=$manifest_idx");
	
	$self->Update({"manifest_idx" => 0});
    }
1103 1104
    my $method_name = "DeleteSlice";
    my $method_args = {};
1105

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    if ($manager_version == 1.0) {
	$method_args->{'credential'} = $slice_credential->asString();
    }
    elsif ($manager_version == 2.0) {
	$method_args->{'credentials'} = [$slice_credential->asString()];
	$method_args->{'slice_urn'}   = $slice->urn();
    }
    else {
	print STDERR
	    "GeniResource::Purge Unknown version at $authority\n";
	return -1;
    }
1118
    $response =
1119 1120
	Genixmlrpc::CallMethod($authority->url(), $usercontext,
			       $method_name, $method_args);
1121
    if (!defined($response)) {
1122
	$self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
1123 1124 1125
	print STDERR "*** Internal error deleting sliver for $self\n";
	return -1;
    }
1126
    $self->{'last_rpcerror'} = $response->code();
1127 1128 1129 1130 1131 1132
    if ($response->code() != GENIRESPONSE_SUCCESS &&
	$response->code() != GENIRESPONSE_SEARCHFAILED) {
	print STDERR "Could not delete sliver for $self. Error: ";
	print STDERR "  " . $response->output() . "\n";
	return -1;
    }
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    #
    # Delete this now; no point in waiting for the CM to tell us.
    #
    # Needs to move elsewhere I think.
    #
    my $clientsliver =
	GeniRegistry::ClientSliver->LookupByAuthority($slice,
						      $manager_urn);
    $clientsliver->Delete()
	if (defined($clientsliver));
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
    return 0;
}

#
# Start a sliver. Optionally one part of it, but ignoring that for now.
#
sub StartSliver($$$)
{
    my ($self, $user, $urn) = @_;
    my $response;

    #
    # Load sliver credential if we have it.
    #
    my $sliver_credential;
    if ($self->credential_idx()) {
	$sliver_credential = GeniCredential->Lookup($self->credential_idx());
	if (!defined($sliver_credential)) {
	    print STDERR "*** Could not get sliver credential for $self.\n";
	    return -1;
	}
    }
    else {
	print STDERR "*** No sliver credential for $self.\n";
	return -1;
    }

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "*** AddResources: No slice for $self\n";
	return -1;
    }
    my $manager_urn = $self->manager_urn();
1176
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
1177
    if (!defined($authority)) {
1178 1179
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
1180
    }
1181
    my $manager_version = $self->ManagerVersion();
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

    #
    # Generate a slice credential for the user. 
    #
1200 1201 1202 1203
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
1204 1205 1206 1207 1208
    if (!defined($slice_credential)) {
	print STDERR
	    "*** Could not create a slice credential for $slice/$geniuser!\n";
	return -1;
    }
1209
    if (!defined($self->Manifest())) {
1210 1211 1212
	print STDERR "*** Could not load manifest\n";
	return -1;
    }
1213 1214 1215 1216

    #
    # Do it. 
    #
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    my $method_name = "StartSliver";
    my $method_args = { "manifest" => $self->{'MANIFESTSTR'} };

    if ($manager_version == 1.0) {
	$method_args->{'credential'} = $sliver_credential->asString();
    }
    elsif ($manager_version == 2.0) {
	$method_args->{'credentials'} = [$slice_credential->asString()];
	$method_args->{'slice_urn'}   = $slice->urn();
    }
    else {
	print STDERR
	    "GeniResource::StartSliver Unknown version at $authority\n";
	return -1;
    }
1232
    $response =
1233 1234
	Genixmlrpc::CallMethod($authority->url(), $usercontext,
			       $method_name, $method_args);
1235
    if (!defined($response)) {
1236
	$self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
1237 1238 1239 1240
	print STDERR
	    "*** Internal error starting sliver for $self\n";
	return -1;
    }
1241
    $self->{'last_rpcerror'} = $response->code();
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	print STDERR "Could not start sliver $sliver_credential Error: ";
	print STDERR "  " . $response->output() . "\n";
	return -1;
    }
    return 0;
}

#
# Call the sliver status function, returning an array.
#
sub SliverStatus($$$$)
{
    my ($self, $user, $pref, $urn) = @_;
1256
    my ($response);
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279

    #
    # Load sliver credential if we have it.
    #
    my $sliver_credential;
    if ($self->credential_idx()) {
	$sliver_credential = GeniCredential->Lookup($self->credential_idx());
	if (!defined($sliver_credential)) {
	    print STDERR "*** Could not get sliver credential for $self.\n";
	    return -1;
	}
    }
    else {
	print STDERR "*** No sliver credential for $self.\n";
	return -1;
    }

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "*** SliverStatus: No slice for $self\n";
	return -1;
    }
    my $manager_urn = $self->manager_urn();
1280
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
1281
    if (!defined($authority)) {
1282 1283
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
1284
    }
1285
    my $manager_version = $self->ManagerVersion();
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

    #
    # Do it. 
    #
1304 1305
    my $method_name = "SliverStatus";
    my $method_args = {};
1306

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    if ($manager_version == 1.0) {
	$method_args->{'credential'} = $sliver_credential->asString();
    }
    elsif ($manager_version == 2.0) {
	$method_args->{'credentials'} = [$sliver_credential->asString()];
	$method_args->{'slice_urn'}   = $slice->urn();
    }
    else {
	print STDERR
	    "GeniResource::SliverStatus Unknown version at $authority\n";
	return -1;
    }
    $response =
	Genixmlrpc::CallMethod($authority->url(), $usercontext,
			       $method_name, $method_args);
1322
    if (!defined($response)) {
1323
	$self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
1324 1325 1326 1327
	print STDERR
	    "*** Internal error getting sliver status for $self\n";
	return -1;
    }
1328
    $self->{'last_rpcerror'} = $response->code();
1329 1330 1331 1332
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	print STDERR "Could not get sliver status $sliver_credential Error: ";
	print STDERR "  " . $response->output() . "\n";
	return -1;
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    } 
    my $blob = {
	"state"   => "unknown",
	"status"  => $response->value()->{'status'},
    };
    if ($manager_version == 1.0) {
	$blob->{'details'} = $response->value()->{'detailsNew'};
    }
    elsif ($manager_version == 2.0) {
	$blob->{'details'} = $response->value()->{'details'};
    }
    $$pref = $blob
1345 1346 1347 1348 1349
	if (defined($pref));
    
    return 0;
}

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
#
# Call the Discover function, returning the advertisement (xml string).
#
sub Discover($$$)
{
    my ($self, $user, $pref) = @_;
    my $response;

    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
1360
	print STDERR "*** Discover: No slice for $self\n";
1361 1362 1363
	return -1;
    }
    my $manager_urn = $self->manager_urn();
1364
    my $authority = GeniAuthority->CreateFromRegistry("cm", $manager_urn);
1365
    if (!defined($authority)) {
1366 1367
	print STDERR "*** Could not find $manager_urn at ClearingHouse\n";
	return -1;
1368
    }
1369
    my $manager_version = $self->ManagerVersion();
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

    #
    # Create a Geni user from current user doing the operation.
    #
    my $geniuser = GeniUser->CreateFromLocal($user);
    if (!defined($geniuser)) {
	print STDERR "*** Could not create a geni user from $user\n";
	return -1;
    }
    my $usercontext = Genixmlrpc->UserContext($geniuser);
    if (!defined($usercontext)) {
	print STDERR "*** Could not create user context from $geniuser\n";
	return -1;
    }

    #
    # Generate a slice credential for the user. 
    #
1388 1389 1390 1391
    my $slice_credential =
	GeniCredential->CreateSigned($slice,
				     $geniuser,
				     $GeniCredential::LOCALSA_FLAG);
1392 1393 1394 1395 1396 1397 1398 1399 1400
    if (!defined($slice_credential)) {
	print STDERR
	    "*** Could not create a slice credential for $slice/$geniuser!\n";
	return -1;
    }

    #
    # Do it. 
    #
1401 1402
    my $method_name = "DiscoverResources";
    my $method_args = { "available" => "true" };
1403

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    if ($manager_version == 1.0) {
	$method_args->{'credential'} = $slice_credential->asString();
    }
    elsif ($manager_version == 2.0) {
	$method_args->{'credentials'} = [$slice_credential->asString()];
    }
    else {
	print STDERR
	    "GeniResource::DiscoverResources Unknown version at $authority\n";
	return -1;
    }
    $response =
	Genixmlrpc::CallMethod($authority->url(), $usercontext,
			       $method_name, $method_args);
1418
    if (!defined($response)) {
1419
	$self->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
1420 1421 1422 1423
	print STDERR
	    "*** Internal error doing DiscoverResources for $self\n";
	return -1;
    }
1424
    $self->{'last_rpcerror'} = $response->code();
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	print STDERR "Could not discover resources $slice_credential Error: ";
	print STDERR "  " . $response->output() . "\n";
	return -1;
    }
    $$pref = $response->value()
	if (defined($pref));
    
    return 0;
}

1436
#
1437
# Class method to renew resources for an experiment/slice.
1438
#
1439
sub RenewExperimentResources($;$)
1440
{
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    my ($experiment, $force) = @_;

    my $slice = GeniSlice->LookupByExperiment($experiment);
    if (!defined($slice)) {
	print STDERR
	    "*** RenewExperimentResources: No slice for $experiment\n";
	return -1;
    }
    return RenewSliceResources($slice, $force);
}

sub RenewSliceResources($;$)
{
    my ($slice, $force) = @_;

    $force = 0
	if (!defined($force));

    #
    # Get the resource objects.
    #
    my @resources = GeniResource->SliceResources($slice);
1463
    return 0
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 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
	if (!@resources);

    #
    # If the expiration is more then 30 days out, do not bother.
    #
    my $when = str2time($slice->expires());
    return 0
	if (!$force && $when > time() + (3600 * 24 * 30));

    # Good default
    my $expires = time() + (3600 * 24 * 90);

    if ($slice->SetExpiration($expires)) {
	print STDERR "RenewSliceResources: ".
	    "Could not set expiration for $slice!\n";
	return -1
    }

    #
    # Cull out resources that are more then 30 days out.
    #
    if (!$force) {
	my @tmp = ();
	foreach my $resource (@resources) {
	    # Nothing to renew yet
	    next
		if ($resource->credential_idx());
	    
	    if (!defined($resource->expires())) {
		push(@tmp, $resource);
		next;
	    }
	    my $resource_expires = str2time($resource->expires());
	    push(@tmp, $resource)
		if (time() + (3600 * 24 * 30) > $resource_expires);
	}
	@resources = @tmp;
	return 0
	    if (!@resources);
    }
    return RenewResources(@resources);
}

#
# Class method to renew a set of resources.
#
sub RenewResources(@)
{
    my @resources = @_;
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

    #
    # Load the SA cert to act as caller context.
    #
    my $certificate = GeniCertificate->LoadFromFile($SACERT);
    if (!defined($certificate)) {
	print STDERR "*** Could not load certificate from $SACERT\n";
	return -1;
    }
    my $context = Genixmlrpc->Context($certificate);
    if (!defined($context)) {
	print STDERR "*** Could not create context to talk to clearinghouse\n";
	return -1;
    }
    
    #
    # Set the default RPC context. 
    #
    Genixmlrpc->SetContext($context);

    # Hash the slice credentials so we generate them only once.
    my %credentials;

1536
    foreach my $resource (@resources) {
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	# No sliver, skip.
	next
	    if (! $resource->credential_idx());

	my $slice = GeniSlice->Lookup($resource->slice_idx());
	if (!defined($slice)) {
	    print STDERR "RenewAll: No slice for $resource\n";
	    next;
	}

	my $manager_urn = $resource->manager_urn();
	my $authority   = GeniAuthority->Lookup($manager_urn);
	if (!defined($authority)) {
	    print STDERR "RenewAll: Could not locate $manager_urn\n";
	    next;
	}
1553
	my $manager_version = $resource->ManagerVersion();
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

	#
	# Generate a slice credential.
	#
	if (!exists($credentials{$slice->uuid()})) {
	    my $credential = GeniCredential->Create($slice, $certificate);
	    if (!defined($credential)) {
		print STDERR
		    "RenewAll: Could not create credential for $slice!\n";
		next;
	    }
	    if ($credential->Sign($GeniCredential::LOCALSA_FLAG) != 0) {
		print STDERR
		    "RenewAll: Could not sign credential $credential!\n";
		next;
	    }
	    $credentials{$slice->uuid()} = $credential;
	}
	my $slice_credential = $credentials{$slice->uuid()};
	
	#
	# Do it. 
	#
	print STDERR "Renewing $slice on $authority\n";
	
1579 1580
	my $method_name = "RenewSlice";
	my $method_args = { };
1581

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
	if ($manager_version == 1.0) {
	    $method_args->{'credential'} = $slice_credential->asString();
	}
	elsif ($manager_version == 2.0) {
	    $method_args->{'credentials'} = [$slice_credential->asString()];
	    $method_args->{'slice_urn'}   = $slice->urn();
	}
	else {
	    print STDERR
		"GeniResource::RenewAll Unknown version at $authority\n";
	    return -1;
	}
	my $response =
	    Genixmlrpc::CallMethod($authority->url(), $context,
				   $method_name, $method_args);
1597
	if (!defined($response)) {
1598
	    $resource->{'last_rpcerror'} = GENIRESPONSE_RPCERROR();
1599 1600 1601 1602
	    print STDERR
		"RenewAll: Internal error doing renew for $resource\n";
	    next;
	}
1603
	$resource->{'last_rpcerror'} = $response->code();
1604
	if ($response->code() != GENIRESPONSE_SUCCESS) {
1605
	    print STDERR "RenewAll: Could not renew $slice_credential Error: ";
1606 1607 1608
	    print STDERR "  " . $response->output() . "\n";
	    next;
	}
1609 1610 1611 1612 1613 1614 1615 1616 1617
	#
	# It worked, so mark this resource as renewed. Since an individual
	# resource could fail to renew, we want to know which ones to come
	# back to later.
	#
	if ($resource->SetExpiration($slice->expires())) {
	    print STDERR "RenewAll: Could not set expiration for $resource!\n";
	    next;
	}
1618 1619 1620 1621
    }
    return 0;
}

1622 1623 1624
# _Always_ make sure that this 1 is at the end of the file...
1;