GeniSlice.pm.in 38 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2008-2015 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
29 30 31 32 33
#
package GeniSlice;

use strict;
use Exporter;
34
use vars qw(@ISA);
35
@ISA = "Exporter";
Leigh Stoller's avatar
Leigh Stoller committed
36 37 38

# Must come after package declaration!
use GeniDB;
Leigh Stoller's avatar
Leigh Stoller committed
39
use GeniRegistry;
Leigh Stoller's avatar
Leigh Stoller committed
40 41
use GeniAuthority;
use GeniCredential;
42
use GeniCertificate;
43
use GeniUser;
44
use GeniHRN;
Leigh Stoller's avatar
Leigh Stoller committed
45
use English;
46
use libEmulab;
47
use emutil;
48
use Date::Parse;
Leigh Stoller's avatar
Leigh Stoller committed
49
use Data::Dumper;
Leigh Stoller's avatar
Leigh Stoller committed
50
use vars qw();
51
use overload ('""' => 'Stringify');
Leigh Stoller's avatar
Leigh Stoller committed
52 53 54 55 56 57 58 59 60

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $CONTROL	   = "@USERNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
61
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh Stoller's avatar
Leigh Stoller committed
62 63 64

# Cache of instances to avoid regenerating them.
my %slices     = ();
65
BEGIN { use GeniUtil; GeniUtil::AddCache(\%slices); }
Leigh Stoller's avatar
Leigh Stoller committed
66 67 68 69 70 71 72 73 74 75 76 77 78
my $debug      = 0;

# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if ($debug);
    return system($command);
}

#
79
# Lookup by idx, URN or uuid.
Leigh Stoller's avatar
Leigh Stoller committed
80 81 82 83
#
sub Lookup($$)
{
    my ($class, $token) = @_;
84 85
    my $query_result;
    my $idx;
Leigh Stoller's avatar
Leigh Stoller committed
86

87 88
    return $slices{"$token"}
        if (exists($slices{"$token"}));
Leigh Stoller's avatar
Leigh Stoller committed
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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    if( GeniHRN::IsValid( $token ) ) {
	my ($authority, $type, $id) = GeniHRN::Parse( $token );

	return undef if $type ne "slice";
	
	if( GeniHRN::Authoritative( $token, "@OURDOMAIN@" ) ) {
	    # Good: this is one of our slices, and we can confidently
	    # transform the name for direct lookup.  This method is
	    # very general, and will even resolve a URN to a (deprecated)
	    # pre-URN slice.
	    $query_result =
		DBQueryWarn("select idx from geni_slices ".
			    "where hrn='@PROTOGENI_DOMAIN@.$id'");
	} else {
	    # Somebody else's slice.  We'll have to look up the slice
	    # by its certificate, which will work only for post-URN slices.
	    $query_result = DBQueryWarn(
		"SELECT geni_slices.idx FROM geni_slices, geni_certificates " .
		"WHERE geni_slices.uuid = geni_certificates.uuid AND " .
		"geni_certificates.urn='$token';" );
	}

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

	($idx) = $query_result->fetchrow_array();
    }
    elsif ($token =~ /^\d+$/) {
	$idx = $token;
    }
    elsif ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$query_result =
	    DBQueryWarn("select idx from geni_slices ".
			"where uuid='$token'");
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
    }
    elsif ($token =~ /^[-\w\.]*$/) {
	$query_result =
	    DBQueryWarn("select idx from geni_slices ".
			"where hrn='$token'");
	    return undef
		if (! $query_result || !$query_result->numrows);

	    ($idx) = $query_result->fetchrow_array();
    }
    else {
	return undef;
    }

    $query_result =
	DBQueryWarn("select * from geni_slices where idx='$idx'");
Leigh Stoller's avatar
Leigh Stoller committed
143
    return undef
144
	if (!$query_result || !$query_result->numrows);
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    my $self         = {};
    $self->{'SLICE'} = $query_result->fetchrow_hashref();
    bless($self, $class);

    #
    # Grab the certificate, since we will probably want it.
    #
    my $uuid = $self->{'SLICE'}->{'uuid'};
    my $certificate = GeniCertificate->Lookup($uuid);
    if (!defined($certificate)) {
	print STDERR "Could not find certificate for slice $idx ($uuid)\n";
	return undef;
    }
    $self->{'CERT'}     = $certificate;
    $self->{'BINDINGS'} = undef;
    $self->{'LOCKED'}   = 0;
162
    $self->{'STITCHLOCKED'} = 0;
163
    
Leigh Stoller's avatar
Leigh Stoller committed
164
    # Add to cache. 
165 166 167 168
    $slices{$self->idx()}  = $self;
    $slices{$self->urn()}  = $self;
    $slices{$self->uuid()} = $self;
    $slices{$self->hrn()}  = $self;
169 170 171 172 173

    # Convert URNs to objects.
    $self->{'SLICE'}->{'creator_urnOBJ'} = GeniHRN->new($self->creator_urn());
    $self->{'SLICE'}->{'speaksfor_urnOBJ'} = GeniHRN->new($self->speaksfor_urn())
	if (defined($self->speaksfor_urn()));
174
    
175
    return $self;
176 177 178 179 180
}

#
# Class function to create new Geni slice and return the object.
#
181
sub Create($$$$;$$)
182
{
183
    my ($class, $certificate, $creator, $authority, $exptidx, $lock) = @_;
184
    my @insert_data = ();
185 186 187 188 189 190 191
    # This is in hours.
    my $default_slice_lifetime;
    if (!libEmulab::GetSiteVar('protogeni/default_slice_lifetime', 
			       \$default_slice_lifetime)) {
	# Cannot get the value, default it to 6 hours
	$default_slice_lifetime = 6;
    }
192

193 194
    # Every slice gets a new unique index.
    my $idx = TBGetUniqueIndex('next_exptidx', 1);
195

196 197 198 199 200 201 202 203
    if (!defined($authority)) {
	print STDERR "Need to specify an authority!\n";
	return undef;
    }
    my $sa_uuid = $authority->uuid();

    # Now tack on other stuff we need.
    push(@insert_data, "created=now()");
204 205
    push(@insert_data, "expires=DATE_ADD(now(), ".
	                       "INTERVAL $default_slice_lifetime HOUR)");
206 207 208
    push(@insert_data, "sa_uuid='$sa_uuid'");
    push(@insert_data, "exptidx=$exptidx")
	if (defined($exptidx));
209 210 211 212 213 214 215

    # This is no good; should not create slices locked without
    # making sure this is really the creator. see below
    if (defined($lock) && $lock) {
	push(@insert_data, "locked=now()");
	push(@insert_data, "stitch_locked=now()");
    }
Leigh Stoller's avatar
Leigh Stoller committed
216
    
217 218 219 220
    my $safe_hrn   = DBQuoteSpecial($certificate->hrn());
    my $safe_uuid  = DBQuoteSpecial($certificate->uuid());
    push(@insert_data, "hrn=$safe_hrn");
    push(@insert_data, "uuid=$safe_uuid");
221 222 223 224 225 226 227 228 229 230 231 232

    if (defined($creator)) {
	my $safe_cuuid = DBQuoteSpecial($creator->uuid());
	my $safe_curn  = DBQuoteSpecial($creator->urn());
	push(@insert_data, "creator_uuid=$safe_cuuid");
	push(@insert_data, "creator_urn=$safe_curn");
    }
    else {
	# No creator means this did not come from the actual user.
	push(@insert_data, "creator_uuid=''");
	push(@insert_data, "isplaceholder='1'");
    }
233 234 235 236 237 238

    if ($certificate->Store() != 0) {
	print STDERR "Could not store certificate for new slice.\n";
	return undef;
    }

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
    #
    # Lock the table and look for an existing entry. If there is one,
    # and it is the placeholder entry, overwrite it.
    #
    DBQueryWarn("lock tables geni_slices write")
	or return undef;
    my $query_result =
	DBQueryWarn("select idx,isplaceholder from geni_slices " .
		    "where uuid=$safe_uuid or hrn=$safe_hrn");
    if (!$query_result) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    if ($query_result->numrows) {
	if ($query_result->numrows != 1) {
	    my $urn  = $certificate->urn();
	    my $uuid = $certificate->uuid();
	    my $hrn  = $certificate->hrn();
	    print STDERR "Too many rows for $uuid/$hrn/$urn\n";
	    DBQueryWarn("unlock tables");
	    return undef;
	}
	my ($curidx,$isplaceholder) = $query_result->fetchrow_array();
	#
	# If the existing entry is a placeholder, and we got the creator,
	# then replace the existing entry to make it a non-placeholder.
	#
	if ($isplaceholder && defined($creator)) {
	    push(@insert_data, "idx='$curidx'");
	    
	    if (! DBQueryWarn("replace into geni_slices set " .
			      "  isplaceholder=0, ".
			      join(",", @insert_data))) {
		DBQueryWarn("unlock tables");
		return undef;
	    }
	    $idx = $curidx;
	}
277 278
	# Slice exists, no inserts needed. Just lookup. 
	goto lookup;
279 280 281
    }
    # Do this after above code since we might need to overwrite entry.
    push(@insert_data, "idx='$idx'");
282

283 284 285 286 287 288
    # Insert into DB.
    if (! DBQueryWarn("insert into geni_slices set " .
		      join(",", @insert_data))) {
        DBQueryWarn("unlock tables");
	return undef;
    }
289
  lookup:
290
    DBQueryWarn("unlock tables");
291 292 293 294
    my $slice = GeniSlice->Lookup($idx);
    return undef
	if (!defined($slice));

295
    $slice->{'LOCKED'} = $slice->{'STITCHLOCKED'} = $$
296 297
	if (defined($lock) && $lock);
    return $slice;
298 299 300 301 302 303
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'SLICE'}->{$_[1]}); }
sub idx($)		{ return field($_[0], "idx"); }
sub hrn($)		{ return field($_[0], "hrn"); }
sub uuid($)		{ return field($_[0], "uuid"); }
304
sub publicid($)		{ return field($_[0], "publicid"); }
305 306
sub creator_uuid($)	{ return field($_[0], "creator_uuid"); }
sub creator_urn($)	{ return field($_[0], "creator_urn"); }
307
sub creator_urnOBJ($)	{ return field($_[0], "creator_urnOBJ"); }
308 309
sub created($)		{ return field($_[0], "created"); }
sub shutdown($)		{ return field($_[0], "shutdown"); }
310
sub isshutdown($)	{ return field($_[0], "isshutdown"); }
311 312 313 314
sub expires($)		{ return field($_[0], "expires"); }
sub sa_uuid($)		{ return field($_[0], "sa_uuid"); }
sub exptidx($)		{ return field($_[0], "exptidx"); }
sub needsfirewall($)	{ return field($_[0], "needsfirewall"); }
315
sub name($)		{ return field($_[0], "name"); }
316
sub registered($)	{ return field($_[0], "registered"); }
317
sub lockdown($)		{ return field($_[0], "lockdown"); }
318
sub isplaceholder($)	{ return field($_[0], "isplaceholder"); }
319
sub monitor_pid($)	{ return field($_[0], "monitor_pid"); }
320
sub speaksfor_urn($)	{ return field($_[0], "speaksfor_urn"); }
321
sub speaksfor_urnOBJ($)	{ return field($_[0], "speaksfor_urnOBJ"); }
322
sub speaksfor_uuid($)	{ return field($_[0], "speaksfor_uuid"); }
323 324
sub expiration_max($)	{ return field($_[0], "expiration_max"); }
sub renew_limit($)	{ return field($_[0], "renew_limit"); }
325
sub description($)      { return field($_[0], "description"); }
326 327 328
sub cert($)		{ return $_[0]->{'CERT'}->cert(); }
sub GetCertificate($)   { return $_[0]->{'CERT'}; }
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }
329
sub STITCHLOCKED($)     { return $_[0]->{'STITCHLOCKED'}; }
330

331 332 333 334 335 336 337 338 339
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $hrn = $self->hrn();
    my $idx = $self->idx();
340

341
    return "[GeniSlice: $hrn, IDX: $idx]";
Leigh Stoller's avatar
Leigh Stoller committed
342
}
Leigh Stoller's avatar
Leigh Stoller committed
343

Leigh Stoller's avatar
Leigh Stoller committed
344
#
345
# Delete the slice, as for registration errors.
Leigh Stoller's avatar
Leigh Stoller committed
346
#
347
sub Delete($)
Leigh Stoller's avatar
Leigh Stoller committed
348 349
{
    my ($self) = @_;
350 351 352 353 354 355 356

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

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

357 358
    DBQueryWarn("delete from geni_slicecerts where uuid='$uuid'")
	or return -1;
359 360
    DBQueryWarn("delete from geni_bindings where slice_uuid='$uuid'")
	or return -1;
361 362 363 364
    DBQueryWarn("delete from geni_certificates where uuid='$uuid'")
	or return -1;
    DBQueryWarn("delete from geni_slices where idx='$idx'")
	or return -1;
Leigh Stoller's avatar
Leigh Stoller committed
365

366 367
    # Delete from cache. 
    delete($slices{$idx});
368 369 370
    delete($slices{$self->urn()});
    delete($slices{$self->uuid()});
    delete($slices{$self->hrn()});
371

372
    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
373 374
}

375 376 377 378 379
# The slicename is the last token in the hrn.
sub slicename($)
{
    my ($self) = @_;

Leigh Stoller's avatar
Leigh Stoller committed
380
    my ($slicename) = ($self->hrn() =~ /^.*\.([-\w]*)$/);
381 382 383 384 385 386
    $slicename = $self->hrn()
	if (!defined($slicename));

    return $slicename;
}

Leigh Stoller's avatar
Leigh Stoller committed
387 388 389 390 391 392
#
# Return the URN. This is complicated by the fact that the DB does
# not store the urn, but is in the certificate. Further, it might
# be a slice from an SA not doing URNs yet, in which case set it to
# the uuid and hope for the best.
#
393 394 395
sub urn($)
{
    my ($self) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
396
    my $urn = $self->GetCertificate()->urn();
397

Leigh Stoller's avatar
Leigh Stoller committed
398 399 400 401
    return $urn
	if (defined($urn) && $urn ne "");

    return $self->uuid();
402 403
}

404 405 406 407 408 409 410
sub urnOBJ($)
{
    my ($self) = @_;

    return $self->GetCertificate()->urnOBJ();
}

Leigh Stoller's avatar
Leigh Stoller committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
#
# Lookup slice by the experiment it is related to.
#
sub LookupByExperiment($$)
{
    my ($class, $experiment) = @_;

    my $exptidx = $experiment->idx();
    my $query_result =
	DBQueryWarn("select idx from geni_slices ".
		    "where exptidx='$exptidx'");
    return undef
	if (!defined($query_result) || !$query_result->numrows);

    my ($idx) = $query_result->fetchrow_array();
    return GeniSlice->Lookup($idx);
}

429 430 431 432 433 434
#
# Lookup all slice(s) of a specified creator.
#
sub LookupByCreator($$)
{
    my ($class, $creator) = @_;
435
    
436 437 438 439 440 441
    my $creator_uuid = $creator->uuid();
    my $query_result =
	DBQueryWarn("select idx from geni_slices ".
		    "where creator_uuid='$creator_uuid'");
    return undef unless defined($query_result);

442 443 444 445 446 447 448
    my @result = ();
    while (my ($idx) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($idx);
	push(@result, $slice)
	    if (defined($slice));
    }
    return @result;
449 450
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

sub BoundToUser($$)
{
    my ($class, $user) = @_;

    my $uuid = $user->uuid();
    my $query_result = 
	DBQueryWarn("select slice_uuid from geni_bindings ".
		    "where user_uuid='$uuid'");
    return undef unless defined($query_result);

    my @result = ();
    while (my ($slice_uuid) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($slice_uuid);
	push(@result, $slice)
	    if (defined($slice));
    }
    return @result;
}

Leigh Stoller's avatar
Leigh Stoller committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
#
# We lock at a very coarse grain, mostly in the CM. When a slice is busy
# we cannot expire things from it.
#
sub Lock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    # We already have it locked.
    return 0
	if ($self->LOCKED());

    DBQueryWarn("lock tables geni_slices write")
	or return -1;

487
    # Slice lock always takes both locks. Holder can drop the stitch lock.
Leigh Stoller's avatar
Leigh Stoller committed
488
    my $query_result =
489 490 491
	DBQueryWarn("select locked,stitch_locked from geni_slices ".
		    "where idx='$idx' and ".
		    "      locked is null and stitch_locked is null");
Leigh Stoller's avatar
Leigh Stoller committed
492 493 494 495 496
    if (!$query_result || !$query_result->numrows) {
	DBQueryWarn("unlock tables");
	return 1;
    }
    $query_result =
497 498
	DBQueryWarn("update geni_slices set ".
		    "locked=now(),stitch_locked=now() where idx='$idx'");
Leigh Stoller's avatar
Leigh Stoller committed
499 500 501 502 503
    DBQueryWarn("unlock tables");

    return 1
	if (!$query_result);
    $self->{'LOCKED'} = $$;
504
    $self->{'STITCHLOCKED'} = $$;
Leigh Stoller's avatar
Leigh Stoller committed
505 506 507 508 509 510 511 512 513 514
    return 0;
}
sub UnLock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    return 1
	if (!$self->LOCKED());

515 516
    DBQueryWarn("update geni_slices set ".
		"locked=NULL,stitch_locked=NULL where idx='$idx'")
Leigh Stoller's avatar
Leigh Stoller committed
517 518 519
	or return -1;
    
    $self->{'LOCKED'} = 0;
520 521 522 523
    $self->{'STITCHLOCKED'} = 0;
    return 0;
}

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
#
# Wait for lock with timeout (in seconds).
#
sub WaitForLock($$)
{
    my ($self, $timeout) = @_;

    return $self->Lock()
	if (! $timeout);
	
    while ($timeout >= 0) {
	return 0
	    if ($self->Lock() == 0);
	
	$timeout--;
	sleep(1);
    }
    return -1;
}

544 545 546 547 548 549 550 551 552 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 584 585 586 587 588 589 590
#
# The stitching lock is used solely for controlling concurrency related
# to stitching.
#
sub StitchLock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    # We already have it locked.
    return 0
	if ($self->STITCHLOCKED());

    DBQueryWarn("lock tables geni_slices write")
	or return -1;

    my $query_result =
	DBQueryWarn("select stitch_locked from geni_slices ".
		    "where idx='$idx' and ".
		    "      stitch_locked is null");
    if (!$query_result || !$query_result->numrows) {
	DBQueryWarn("unlock tables");
	return 1;
    }
    $query_result =
	DBQueryWarn("update geni_slices set ".
		    " stitch_locked=now() where idx='$idx'");
    DBQueryWarn("unlock tables");

    return 1
	if (!$query_result);
    $self->{'STITCHLOCKED'} = $$;
    return 0;
}
sub StitchUnLock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    return 1
	if (!$self->STITCHLOCKED());

    DBQueryWarn("update geni_slices set ".
		" stitch_locked=NULL where idx='$idx'")
	or return -1;
    
    $self->{'STITCHLOCKED'} = 0;
Leigh Stoller's avatar
Leigh Stoller committed
591 592 593
    return 0;
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
#
# LockTables simply locks the geni_slices table.
#
sub LockTables($)
{
    my ($self) = @_;

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

    DBQueryWarn("lock tables geni_slices write")
	or return -1;
	
    return 0;
}
sub UnLockTables($)
{
    my ($self) = @_;

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

    DBQueryWarn("unlock tables")
	or return -1;
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
623 624
#
# Class function to create new Geni slice from a local experiment.
625
# We want to create the key pair so that we can sign credentials.
Leigh Stoller's avatar
Leigh Stoller committed
626
#
Leigh Stoller's avatar
Leigh Stoller committed
627
sub CreateFromLocal($$$)
Leigh Stoller's avatar
Leigh Stoller committed
628
{
629
    my ($class, $experiment, $geniuser) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
630

631 632 633 634 635 636
    #
    # So we know who/what we are acting as.
    #
    my $EMULAB_PEMFILE = "@prefix@/etc/genisa.pem";
    my $certificate = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
    if (!defined($certificate)) {
637
	print STDERR "Could not load certificate from $EMULAB_PEMFILE\n";
638 639
	return undef;
    }
Leigh Stoller's avatar
Leigh Stoller committed
640

641
    #
642
    # Need our own slice authority record.
643
    #
644
    my $authority = GeniAuthority->Lookup($certificate->uuid());
645 646 647 648
    if (!defined($authority)) {
	print STDERR "Could not find the local authority record\n";
	return undef;
    }
649 650

    #
651
    # This mirrors the code in GeniSA.pm
652
    #
653 654 655
    my $hrn = "CE" . $experiment->idx();
    my $urn = GeniHRN::Generate("@OURDOMAIN@", "slice", $hrn);
    $hrn = "${PGENIDOMAIN}.${hrn}";
Leigh Stoller's avatar
Leigh Stoller committed
656 657

    #
658
    # Generate a certificate.
Leigh Stoller's avatar
Leigh Stoller committed
659
    #
660 661
    $certificate = GeniCertificate->Create({'urn'  => $urn,
					    'hrn'  => $hrn,
662
					    'showuuid' => 1,
663
					    'email'=> $geniuser->email()});
664
    if (!defined($certificate)) {
665
	print STDERR "GeniSlice::CreateFromLocal: ".
666
	    "Could not generate new certificate $experiment\n";
Leigh Stoller's avatar
Leigh Stoller committed
667 668
	return undef;
    }
669
    # Create the slice as locked.
670
    my $slice = GeniSlice->Create($certificate, $geniuser,
671
				  $authority, $experiment->idx(), 1);
672 673 674 675
    $certificate->Delete()
	if (!defined($slice));

    return $slice;
Leigh Stoller's avatar
Leigh Stoller committed
676 677 678 679 680 681 682 683
}

#
# Register a local slice at the clearinghouse;
#
sub Register($)
{
    my ($self) = @_;
684
    my $idx    = $self->idx();
Leigh Stoller's avatar
Leigh Stoller committed
685 686 687 688

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

Leigh Stoller's avatar
Leigh Stoller committed
689 690 691
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
692

693 694 695 696 697
    my $creator = GeniUser->Lookup($self->creator_uuid(), 1);
    if (!defined($creator)) {
	print STDERR "Could not find creator for $self\n";
	return -1;
    }
698 699 700 701 702 703 704 705
    if (!$clearinghouse->RegisterSlice($creator->urn(), $self->expires(),
				       $self->cert(), {})) {
	DBQueryWarn("update geni_slices set registered=1 where idx='$idx'")
	    or return -1;
	return 0;
    }
    $self->SetRegisteredFlag(1);
    return -1;
Leigh Stoller's avatar
Leigh Stoller committed
706 707
}

Leigh Stoller's avatar
Leigh Stoller committed
708
#
709
# Remove a local slice at the clearinghouse;
Leigh Stoller's avatar
Leigh Stoller committed
710
#
711
sub UnRegister($)
Leigh Stoller's avatar
Leigh Stoller committed
712 713 714 715
{
    my ($self) = @_;

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

Leigh Stoller's avatar
Leigh Stoller committed
718 719 720
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
721

722 723 724 725 726
    return -1
	if ($clearinghouse->RemoveSlice($self->urn()));
    $self->SetRegisteredFlag(0);

    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
727 728
}

Leigh Stoller's avatar
Leigh Stoller committed
729 730 731 732 733 734 735 736 737 738
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

    delete($slices{$self->idx()});
}

Leigh Stoller's avatar
Leigh Stoller committed
739
#
Leigh Stoller's avatar
Leigh Stoller committed
740
# Return the emulab experiment for this slice.
Leigh Stoller's avatar
Leigh Stoller committed
741
#
Leigh Stoller's avatar
Leigh Stoller committed
742
sub GetExperiment($)
Leigh Stoller's avatar
Leigh Stoller committed
743
{
Leigh Stoller's avatar
Leigh Stoller committed
744
    my ($self) = @_;
745
    require Experiment;
Leigh Stoller's avatar
Leigh Stoller committed
746

Leigh Stoller's avatar
Leigh Stoller committed
747 748
    return undef
	if (!ref($self));
Leigh Stoller's avatar
Leigh Stoller committed
749

Leigh Stoller's avatar
Leigh Stoller committed
750
    return Experiment->Lookup($self->uuid());
Leigh Stoller's avatar
Leigh Stoller committed
751 752
}

Leigh Stoller's avatar
Leigh Stoller committed
753 754 755 756 757 758 759 760 761 762 763 764 765
#
# Return the slice authority for this slice.
#
sub SliceAuthority($)
{
    my ($self) = @_;

    return undef
	if (!ref($self));

    return GeniAuthority->Lookup($self->sa_uuid());
}

Leigh Stoller's avatar
Leigh Stoller committed
766
#
Leigh Stoller's avatar
Leigh Stoller committed
767
# Check if the given SA is the actual SA for the slice.
Leigh Stoller's avatar
Leigh Stoller committed
768
#
Leigh Stoller's avatar
Leigh Stoller committed
769
sub IsSliceAuthority($$)
Leigh Stoller's avatar
Leigh Stoller committed
770
{
Leigh Stoller's avatar
Leigh Stoller committed
771
    my ($self, $authority) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
772

Leigh Stoller's avatar
Leigh Stoller committed
773 774
    return 0
	if (! (ref($self) && ref($authority)));
Leigh Stoller's avatar
Leigh Stoller committed
775

Leigh Stoller's avatar
Leigh Stoller committed
776
    return 1
777
	if ($self->sa_uuid() == $authority->uuid());
Leigh Stoller's avatar
Leigh Stoller committed
778 779
    
    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
780 781
}

Leigh Stoller's avatar
Leigh Stoller committed
782
#
783 784
# Server side of binding users to slices; insert entries into the bindings
# table.
Leigh Stoller's avatar
Leigh Stoller committed
785 786 787 788 789 790 791 792
# 
sub BindUser($$)
{
    my ($self, $target_user) = @_;

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

793 794 795 796 797 798 799
    my $slice_uuid = $self->uuid();
    my $user_uuid  = $target_user->uuid();

    DBQueryWarn("replace into geni_bindings set ".
		" created=now(), slice_uuid='$slice_uuid', ".
		" user_uuid='$user_uuid'")
	or return -1;
Leigh Stoller's avatar
Leigh Stoller committed
800 801 802 803 804 805 806 807 808 809 810
    
    return 0;
}

sub UnBindUser($$)
{
    my ($self, $target_user) = @_;

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

811 812
    my $slice_uuid = $self->uuid();
    my $user_uuid  = $target_user->uuid();
Leigh Stoller's avatar
Leigh Stoller committed
813

814 815 816 817
    DBQueryWarn("delete from geni_bindings ".
		"where slice_uuid='$slice_uuid' and user_uuid='$user_uuid'")
	or return -1;
    
Leigh Stoller's avatar
Leigh Stoller committed
818 819 820
    return 0;
}

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
#
# Unbind all users.
#
sub UnBindUsers($)
{
    my ($self) = @_;

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

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

    DBQueryWarn("delete from geni_bindings ".
		"where slice_uuid='$slice_uuid'")
	or return -1;
    
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
840
#
841 842
# Return the user bindings for a slice, as a list of uuids. Do not look
# them up here since this routine is called from the CH.
Leigh Stoller's avatar
Leigh Stoller committed
843 844 845 846 847 848 849 850 851 852
#
sub UserBindings($$)
{
    my ($self, $pref) = @_;
    
    return -1
	if (! (ref($self) && ref($pref)));

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

853
    if (!defined($self->{'BINDINGS'})) {
Leigh Stoller's avatar
Leigh Stoller committed
854 855 856 857 858 859
	my $query_result =
	    DBQueryWarn("select user_uuid from geni_bindings ".
			"where slice_uuid='$uuid'");
	return -1
	    if (!$query_result);

860
	my @bindings = ();
Leigh Stoller's avatar
Leigh Stoller committed
861 862

	while (my ($user_uuid) = $query_result->fetchrow_array()) {
863
	    push(@bindings, $user_uuid);
Leigh Stoller's avatar
Leigh Stoller committed
864
	}
865
	$self->{'BINDINGS'} = \@bindings;
Leigh Stoller's avatar
Leigh Stoller committed
866
    }
867
    @$pref = @{ $self->{'BINDINGS'} };
Leigh Stoller's avatar
Leigh Stoller committed
868 869 870
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
#
# Is the user bound to a slice.
#
sub IsBound($$)
{
    my ($self, $user) = @_;
    
    return -1
	if (! (ref($self) && ref($user)));

    my $slice_uuid = $self->uuid();
    my $user_uuid  = $user->uuid();

    my $query_result =
	DBQueryWarn("select user_uuid from geni_bindings ".
		    "where slice_uuid='$slice_uuid' and ".
		    "      user_uuid='$user_uuid'");
    return 0
	if (!$query_result);
    return $query_result->numrows();
}

Leigh Stoller's avatar
Leigh Stoller committed
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
#
# Helper function for expiration.
#
sub AddToExpiration($$)
{
    my ($self, $increment) = @_;

    return undef
	if (!defined($self->expires()));
    
    my $new_expires = str2time($self->expires()) + $increment;

    return $self->SetExpiration($new_expires);
}

#
# Return expiration in GMT time format.
#
sub ExpirationGMT($)
{
    my ($self) = @_;

    return undef
	if (!defined($self->expires()));
    
    return POSIX::strftime("20%y-%m-%dT%H:%M:%S GMT",
			   gmtime(str2time($self->expires())));
}

Jonathon Duerig's avatar
Jonathon Duerig committed
922 923 924 925 926 927 928 929 930 931 932
sub ExpirationUTC($)
{
    my ($self) = @_;

    return undef
	if (!defined($self->expires()));
    
    return POSIX::strftime("20%y-%m-%dT%H:%M:%SZ",
			   gmtime(str2time($self->expires())));
}

Leigh Stoller's avatar
Leigh Stoller committed
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
#
# Set the expiration time for a slice. 
#
sub SetExpiration($$)
{
    my ($self, $expires) = @_;
    my $uuid = $self->uuid();

    if ($expires =~ /^\d+$/) {
	$expires = "FROM_UNIXTIME($expires)";
    }
    else {
	$expires = "'$expires'";
    }
    my $query_result =
	DBQueryWarn("update geni_slices set expires=$expires " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);
953 954 955 956 957 958 959 960

    # Has to be in the correct format.
    $query_result =
	DBQueryWarn("select expires from geni_slices where uuid='$uuid'");
    return -1
	if (!$query_result || !$query_result->numrows);
    ($expires) = $query_result->fetchrow_array();
    
961
    $self->{'SLICE'}->{'expires'} = $expires;
962 963 964
    return 0;
}

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
#
# Is slice expired?
#
sub IsExpired($)
{
    my ($self) = @_;

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

    my $slice_expires = $self->expires();
    return 0
	if (!defined($slice_expires));
    
    $slice_expires = str2time($slice_expires);

    return (time() >= $slice_expires);
}

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
#
# Set the speaksfor stuff.
#
sub SetSpeaksFor($$)
{
    my ($self, $speaksfor) = @_;
    my $uuid = $self->uuid();
    my $safe_speaksfor_uuid = DBQuoteSpecial($speaksfor->owner_uuid());
    my $safe_speaksfor_urn  = DBQuoteSpecial($speaksfor->owner_urn());

    print "GeniSlice->SetSpeaksFor($self, $speaksfor)\n";

    return -1
	if (!DBQueryWarn("update geni_slices set " .
			 "  speaksfor_uuid=$safe_speaksfor_uuid , ".
			 "  speaksfor_urn=$safe_speaksfor_urn ".
			 "where uuid='$uuid'"));

    $self->{'SLICE'}->{'speaksfor_urn'}  = $speaksfor->owner_urn();
    $self->{'SLICE'}->{'speaksfor_uuid'} = $speaksfor->owner_uuid();

    return 0;
}

1008 1009 1010 1011 1012 1013
sub SetDescription($$)
{
    my ($self, $description) = @_;
    my $uuid = $self->uuid();
    my $safe_description = DBQuoteSpecial($description);

1014
    return -1
1015 1016 1017 1018 1019 1020 1021 1022 1023
	if (!DBQueryWarn("update geni_slices set " .
			 "  description=$safe_description ".
			 "where uuid='$uuid'"));

    $self->{'SLICE'}->{'description'} = $description;

    return 0;
}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
sub SetLockdown($$)
{
    my ($self, $clear) = @_;
    my $uuid  = $self->uuid();
    my $value = ($clear ? 0 : 1);

    return -1
	if (!DBQueryWarn("update geni_slices set lockdown=$value " .
			 "where uuid='$uuid'"));

    $self->{'SLICE'}->{'lockdown'} = $value;

    return 0;
}

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 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 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
sub SetRenewLimit($$)
{
    my ($self, $limit) = @_;
    my $uuid = $self->uuid();

    if (!defined($limit)) {
	$limit = "null";
    }
    elsif ($limit =~ /^\d+$/) {
	$limit = "SEC_TO_TIME($limit)";
    }
    else {
	$limit = DBQuoteSpecial($limit);
    }
    return -1
	if (!DBQueryWarn("update geni_slices set renew_limit=$limit " .
			 "where uuid='$uuid'"));

    return 0;
}

sub SetExpirationMax($$)
{
    my ($self, $expires) = @_;
    my $uuid = $self->uuid();

    if (!defined($expires)) {
	$expires = "null";
    }
    elsif ($expires =~ /^\d+$/) {
	$expires = "FROM_UNIXTIME($expires)";
    }
    else {
	$expires = DBQuoteSpecial($expires);
    }
    return -1
	if (!DBQueryWarn("update geni_slices set expiration_max=$expires " .
			 "where uuid='$uuid'"));

    return 0;
}

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

    return undef
	if (!defined($self->expiration_max()));

    return str2time($self->expiration_max());
}
sub renew_limit_stamp($)
{
    my ($self) = @_;

    return undef
	if (!defined($self->renew_limit()));

    if ($self->renew_limit() =~ /^(\d*):(\d*):(\d*)$/) {
	return ($1 * 3600) + ($2 * 60) + $3;
    }
    return undef;
}

sub SetIdleIgnore($$)
{
    my ($self, $ignore) = @_;

    my $experiment = $self->GetExperiment();
    return -1
	if (!defined($experiment));

    if ($ignore) {
	return $experiment->SetIdleSwapFlags(0, 1);
    }
    else {
	return $experiment->SetIdleSwapFlags(1, 0);
    }
}

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
#
# Set the shutdown field.
#
sub SetShutdown($$)
{
    my ($self, $shutdown) = @_;
    my $uuid = $self->uuid();
    my $when;

    if ($shutdown) {
	$when = "now()";
    }
    else {
	$when = "NULL";
    }
1134 1135 1136
    #
    # Always clear isshutdown so that expire_daemon knows of change.
    #
1137
    my $query_result =
1138
	DBQueryWarn("update geni_slices set shutdown=$when, isshutdown=0 " .
1139 1140 1141 1142
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);
Leigh Stoller's avatar
Leigh Stoller committed
1143

1144
    # XXX Wrong format, but harmless.
1145 1146
    $self->{'SLICE'}->{'shutdown'}   = ($shutdown ? time() : undef);
    $self->{'SLICE'}->{'isshutdown'} = 0;
Leigh Stoller's avatar
Leigh Stoller committed
1147 1148 1149
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
#
# Set the experiment pointer from a slice to the emulab experiment.
#
sub SetExperiment($$)
{
    my ($self, $experiment) = @_;
    my $uuid  = $self->uuid();
    my $token = "NULL";

    if (defined($experiment)) {
	$token = "'" . $experiment->idx() . "'";
    }
    my $query_result =
	DBQueryWarn("update geni_slices set exptidx=$token " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'exptidx'} =
	(defined($experiment) ? $experiment->idx() : undef);
    return 0;
}

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
#
# Set the needsfirewall field.
#
sub SetFirewallFlag($$)
{
    my ($self, $needsfirewall) = @_;
    my $uuid = $self->uuid();

    $needsfirewall = ($needsfirewall ? 1 : 0);

    my $query_result =
	DBQueryWarn("update geni_slices set needsfirewall='$needsfirewall' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'needsfirewall'} = $needsfirewall;
    return 0;
}

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
#
# Set the name field.
#
sub SetName($$)
{
    my ($self, $name) = @_;
    my $uuid = $self->uuid();
    my $safe_name = DBQuoteSpecial($name);

    DBQueryWarn("update geni_slices set name=$safe_name " .
		"where uuid='$uuid'")
	or return -1;
    
    $self->{'SLICE'}->{'name'} = $name;
    return 0;
}

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
#
# Set the hosed field.
#
sub SetHosedFlag($$)
{
    my ($self, $hosed) = @_;
    my $uuid  = $self->uuid();

    $hosed = ($hosed ? 1 : 0);

    my $query_result =
	DBQueryWarn("update geni_slices set hosed='$hosed' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'hosed'} = $hosed;
    return 0;
}

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
#
# Set the registered field.
#
sub SetRegisteredFlag($$)
{
    my ($self, $registered) = @_;
    my $uuid  = $self->uuid();

    $registered = ($registered ? 1 : 0);

    my $query_result =
	DBQueryWarn("update geni_slices set registered='$registered' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'registered'} = $registered;
    return 0;
}

1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
#
# Set the isshutdown field.
#
sub SetShutdownFlag($$)
{
    my ($self, $isshutdown) = @_;
    my $uuid  = $self->uuid();

    $isshutdown = ($isshutdown ? 1 : 0);

    my $query_result =
	DBQueryWarn("update geni_slices set isshutdown='$isshutdown' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'isshutdown'} = $isshutdown;
    return 0;
}

1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
#
# Convert from placeholder to real slice. Caller will have it locked.
#
sub ConvertPlaceholder($$)
{
    my ($self, $user) = @_;
    my $uuid  = $self->uuid();

    my $safe_cuuid = DBQuoteSpecial($user->uuid());
    my $safe_curn  = DBQuoteSpecial($user->urn());

    my $query_result =
	DBQueryWarn("update geni_slices set isplaceholder=0, " .
		    "  creator_uuid=$safe_cuuid, creator_urn=$safe_curn ".
		    "where uuid='$uuid'");
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'isplaceholder'} = 0;
    $self->{'SLICE'}->{'creator_urn'}   = $user->urn();
    $self->{'SLICE'}->{'creator_uuid'}  = $user->uuid();
    return 0;
}

1299 1300 1301 1302 1303 1304
#
# Delete all slices for an authority.
#
sub DeleteAll($$)
{
    my ($class, $authority) = @_;
1305
    require GeniAggregate;
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348

    my $uuid = $authority->uuid();
    my $query_result =
	DBQueryWarn("select uuid from geni_slices ".
		    "where sa_uuid='$uuid'");

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

    while (my ($uuid) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($uuid);
	if (!defined($slice)) {
	    print STDERR "Could not lookup slice $uuid\n";
	    return -1;
	}
	#
	# Do not allow active slices to be deleted.
	#
	my $aggregate = GeniAggregate->SliceAggregate($slice);
	if (defined($aggregate)) {
	    print STDERR "Cannot delete active slice $slice:\n";
	    return -1;
	}
	my @slivers;
	if (GeniSliver->SliceSlivers($slice, \@slivers) != 0) {
	    print STDERR "Cannot lookup slivers for $slice:\n";
	    return -1;
	}
	if (@slivers) {
	    print STDERR "Cannot delete active slice $slice:\n";
	    return -1;
	}
	if ($slice->Delete() != 0) {
	    print STDERR "Could not delete $slice\n";
	    return -1;
	}
    }

    return 0;
}

1349 1350 1351
#
# List all slices, optionally for an authority.
#
1352
sub ListAll($$;$)
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
{
    my ($class, $pref, $authority) = @_;
    my @result = ();
    @$pref = ();

    my $query = "select uuid from geni_slices ";
    if (defined($authority)) {
	my $sa_uuid = $authority->uuid();
	$query .= "where sa_uuid='$sa_uuid'";
    }
    my $query_result = DBQueryWarn($query);

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

    while (my ($uuid) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($uuid);
	if (!defined($slice)) {
	    print STDERR "Could not lookup slice $uuid\n";
	    return -1;
	}
	push(@result, $slice);
    }
    @$pref = @result;
    return 0;
}

1382 1383 1384 1385 1386 1387 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
#
# Set/Clear the monitor pid.
#
sub SetMonitorPid($$)
{
    my ($self, $pid) = @_;
    my $uuid = $self->uuid();

    my $query_result =
	DBQueryWarn("update geni_slices set monitor_pid='$pid' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'monitor_pid'} = $pid;
    return 0;
}

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

    my $query_result =
	DBQueryWarn("update geni_slices set monitor_pid='0' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'monitor_pid'} = 0;
    return 0;
}

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
sub GetMonitorPid($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();

    my $query_result =
	DBQueryWarn("select monitor_pid from geni_slices " .
		    "where uuid='$uuid'");
    return -1
	if (!$query_result || !$query_result->numrows);
    my ($pid) = $query_result->fetchrow_array();

    $self->{'SLICE'}->{'monitor_pid'} = $pid;
    return $pid;
}

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
#
# Set the public ID.
#
sub SetPublicID($)
{
    my ($self) = @_;
    require libtestbed;

    my $uuid = $self->uuid();
    my $publicid = libtestbed::TBGenSecretKey();
    return -1
	if (!defined($publicid) || $publicid eq "");
    
    my $query_result =
	DBQueryWarn("update geni_slices set publicid='$publicid' " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);

    $self->{'SLICE'}->{'publicid'} = $publicid;
    return 0;
}

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
#
# Add a generic certificate/key for a slice.
#
sub AddGenericCert($$$)
{
    my ($self, $cert, $key) = @_;
    my $uuid  = $self->uuid();
    my $query = "insert into geni_slicecerts set uuid='$uuid' ";

    if (defined($cert)) {
	return -1
	    if (!TBcheck_dbslot($cert, "default", "fulltext",
				TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR));
	$query .= ",cert=" . DBQuoteSpecial($cert);
    }
    if (defined($key)) {
	return -1
	    if (!TBcheck_dbslot($key, "default", "fulltext",
				TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR));
	$query .= ",privkey=" . DBQuoteSpecial($key);
    }
    return DBQueryWarn($query);
}

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 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 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 1579 1580 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 1608 1609 1610 1611 1612 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 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 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 1681 1682 1683 1684 1685 1686 1687 1688
##########################################################################
#
package GeniSlice::ClientSliver;

use GeniDB;
use GeniSlice;
use GeniHRN;
use emutil qw(TBGetUniqueIndex);
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

#
# Lookup.
#
sub Lookup($$)
{
    my ($class, $token) = @_;
    my $query_result;
    my $idx;

    if( GeniHRN::IsValid( $token ) ) {
	$token = GeniHRN::Normalise( $token );

	my ($authority, $type, $id) = GeniHRN::Parse($token);
	return undef if $type ne "sliver";
	
	$query_result = 
	    DBQueryWarn("select idx from client_slivers ".
			"where urn='$token'");
	return undef
	    if (! $query_result || !$query_result->numrows);

	($idx) = $query_result->fetchrow_array();
    }
    elsif ($token =~ /^\d+$/) {
	$idx = $token;
    }
    else {
	return undef;
    }

    $query_result =
	DBQueryWarn("select * from client_slivers where idx='$idx'");
    return undef
	if (!$query_result || !$query_result->numrows);

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

    #
    # Grab the slice, since we will probably want it.
    #
    my $slice = GeniSlice->Lookup($self->slice_idx());
    if (!defined($slice)) {
	print STDERR "Could not find slice for slice $idx\n";
	return undef;
    }
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'SLIVER'}->{$_[1]}); }
sub idx($)		{ return field($_[0], "idx"); }
sub urn($)		{ return field($_[0], "urn"); }
sub manager_urn($)	{ return field($_[0], "manager_urn"); }
sub slice_idx($)	{ return field($_[0], "slice_idx"); }
sub creator_idx($)	{ return field($_[0], "creator_idx"); }
sub created($)		{ return field($_[0], "created"); }
sub expires($)		{ return field($_[0], "expires"); }
sub manifest($)		{ return field($_[0], "manifest"); }
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }

sub LookupByAuthority($$$)
{
    my ($class, $slice, $urn) = @_;
    my $slice_idx = $slice->idx();
    my $query_result;
    my $idx;

    if (GeniHRN::IsValid($urn)) {
	my $safe_urn = DBQuoteSpecial($urn);

	$query_result = 
	    DBQueryWarn("select idx from client_slivers ".
			"where manager_urn=$safe_urn and ".
			"slice_idx='$slice_idx'");
	return undef
	    if (! $query_result || !$query_result->numrows);

	($idx) = $query_result->fetchrow_array();
    }
    else {
	return undef;
    }
    return GeniSlice::ClientSliver->Lookup($idx);
}

# Returns an array of client slivers belonging which belong to a
# particular slice.
sub LookupBySlice($$)
{
    my ($class, $slice) = @_;
    my $slice_idx = $slice->idx();
    my $query_result;
    my @result = ();
    $query_result =
	DBQueryWarn("select idx from client_slivers ".
		    "where slice_idx='$slice_idx'");
    if ($query_result) {
	while (my ($idx) = $query_result->fetchrow_array()) {
	    my $sliver = GeniSlice::ClientSliver->Lookup($idx);
	    if (defined($sliver)) {
		push(@result, $sliver);
	    }
	}
    }
    return @result;
}

#
# Class function to create new Geni slice and return the object.
#
sub Create($$$$$)
{
    my ($class, $slice, $manager_urn, $user, $blob) = @_;
    my @insert_data = ();

    # Every one gets a new unique index.
    my $idx = TBGetUniqueIndex('next_clientsliver', 1);
    
    my $slice_idx      = $slice->idx();
    my $user_idx       = $user->idx();
    my $safe_urn       = DBQuoteSpecial($blob->{'urn'});
    my $safe_created   = DBQuoteSpecial($blob->{'created'});
    my $safe_expires   = DBQuoteSpecial($blob->{'expires'});
    my $safe_manager   = DBQuoteSpecial($manager_urn);

    push(@insert_data, "idx='$idx'");
    push(@insert_data, "slice_idx='$slice_idx'");
    push(@insert_data, "creator_idx='$user_idx'");
    push(@insert_data, "urn=$safe_urn");
    push(@insert_data, "manager_urn=$safe_manager");
    push(@insert_data, "created=$safe_created");
    push(@insert_data, "expires=$safe_expires");

    if (exists($blob->{'manifest'})) {
	my $safe_manifest  = DBQuoteSpecial($blob->{'manifest'});
	push(@insert_data, "manifest=$safe_manifest");
    }

    # Insert into DB.
    return undef
	if (! DBQueryWarn("insert into client_slivers set " .
			  join(",", @insert_data)));

    return GeniSlice::ClientSliver->Lookup($idx);
}

#
# Delete it.
#
sub Delete($)
{
    my ($self) = @_;

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

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

    DBQueryWarn("delete from client_slivers where idx='$idx'")
	or return -1;
    
    return 0;
}

#
# Delete all for a slice.
#
sub SliceDelete($$)
{
    my ($self, $slice) = @_;

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

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

    DBQueryWarn("delete from client_slivers where slice_idx='$slice_idx'")
	or return -1;
    
    return 0;
}

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

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

Leigh Stoller's avatar
Leigh Stoller committed
1689 1690
# _Always_ make sure that this 1 is at the end of the file...
1;