GeniSlice.pm.in 42.3 KB
Newer Older
Leigh Stoller's avatar
Leigh Stoller committed
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2008-2018 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

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

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

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

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

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

88 89
    return $slices{"$token"}
        if (exists($slices{"$token"}));
Leigh Stoller's avatar
Leigh Stoller committed
90

91 92 93 94 95 96 97 98 99 100
    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.
101
	    my $safe_id = DBQuoteSpecial("@PROTOGENI_DOMAIN@.$id");
102 103
	    $query_result =
		DBQueryWarn("select idx from geni_slices ".
104
			    "where hrn=$safe_id");
105 106 107
	} else {
	    # Somebody else's slice.  We'll have to look up the slice
	    # by its certificate, which will work only for post-URN slices.
108
	    my $safe_token = DBQuoteSpecial($token);
109 110 111
	    $query_result = DBQueryWarn(
		"SELECT geni_slices.idx FROM geni_slices, geni_certificates " .
		"WHERE geni_slices.uuid = geni_certificates.uuid AND " .
112
		"geni_certificates.urn=$safe_token;" );
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 143 144 145
	}

	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
146
    return undef
147
	if (!$query_result || !$query_result->numrows);
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    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;
165
    $self->{'STITCHLOCKED'} = 0;
166
    
Leigh Stoller's avatar
Leigh Stoller committed
167
    # Add to cache. 
168 169 170 171
    $slices{$self->idx()}  = $self;
    $slices{$self->urn()}  = $self;
    $slices{$self->uuid()} = $self;
    $slices{$self->hrn()}  = $self;
172 173

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

#
# Class function to create new Geni slice and return the object.
#
184
sub Create($$$$;$$)
185
{
186
    my ($class, $certificate, $creator, $authority, $exptidx, $lock) = @_;
187
    my @insert_data = ();
188 189 190 191 192 193 194
    # 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;
    }
195

196 197
    # Every slice gets a new unique index.
    my $idx = TBGetUniqueIndex('next_exptidx', 1);
198

199 200 201 202 203 204 205 206
    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()");
207 208
    push(@insert_data, "expires=DATE_ADD(now(), ".
	                       "INTERVAL $default_slice_lifetime HOUR)");
209 210 211
    push(@insert_data, "sa_uuid='$sa_uuid'");
    push(@insert_data, "exptidx=$exptidx")
	if (defined($exptidx));
212 213 214 215 216 217 218

    # 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
219
    
220 221 222 223
    my $safe_hrn   = DBQuoteSpecial($certificate->hrn());
    my $safe_uuid  = DBQuoteSpecial($certificate->uuid());
    push(@insert_data, "hrn=$safe_hrn");
    push(@insert_data, "uuid=$safe_uuid");
224 225 226 227 228 229 230 231 232 233 234 235

    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'");
    }
236 237 238 239 240 241

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

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
    #
    # 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.
	#
269 270 271
	if ($isplaceholder) {
	    if (defined($creator)) {
		push(@insert_data, "idx='$curidx'");
272
	    
273 274 275 276 277 278 279
		if (! DBQueryWarn("replace into geni_slices set " .
				  "  isplaceholder=0, ".
				  join(",", @insert_data))) {
		    DBQueryWarn("unlock tables");
		    return undef;
		}
		$idx = $curidx;
280
	    }
281
	    goto lookup;
282
	}
283 284 285
	print STDERR "Slice already exists in database\n";
	DBQueryWarn("unlock tables");
	return undef;
286 287 288
    }
    # Do this after above code since we might need to overwrite entry.
    push(@insert_data, "idx='$idx'");
289

290 291 292 293 294 295
    # Insert into DB.
    if (! DBQueryWarn("insert into geni_slices set " .
		      join(",", @insert_data))) {
        DBQueryWarn("unlock tables");
	return undef;
    }
296
  lookup:
297
    DBQueryWarn("unlock tables");
298 299 300 301
    my $slice = GeniSlice->Lookup($idx);
    return undef
	if (!defined($slice));

302
    $slice->{'LOCKED'} = $slice->{'STITCHLOCKED'} = $$
303 304
	if (defined($lock) && $lock);
    return $slice;
305 306 307 308 309 310
}
# 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"); }
311
sub publicid($)		{ return field($_[0], "publicid"); }
312 313 314 315
sub creator_uuid($)	{ return field($_[0], "creator_uuid"); }
sub creator_urn($)	{ return field($_[0], "creator_urn"); }
sub created($)		{ return field($_[0], "created"); }
sub shutdown($)		{ return field($_[0], "shutdown"); }
316
sub isshutdown($)	{ return field($_[0], "isshutdown"); }
317 318 319 320
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"); }
321
sub name($)		{ return field($_[0], "name"); }
322
sub registered($)	{ return field($_[0], "registered"); }
323
sub lockdown($)		{ return field($_[0], "lockdown"); }
Leigh Stoller's avatar
Leigh Stoller committed
324
sub locked($)		{ return field($_[0], "locked"); }
325
sub isplaceholder($)	{ return field($_[0], "isplaceholder"); }
326
sub monitor_pid($)	{ return field($_[0], "monitor_pid"); }
327 328
sub speaksfor_urn($)	{ return field($_[0], "speaksfor_urn"); }
sub speaksfor_uuid($)	{ return field($_[0], "speaksfor_uuid"); }
329 330
sub expiration_max($)	{ return field($_[0], "expiration_max"); }
sub renew_limit($)	{ return field($_[0], "renew_limit"); }
331
sub description($)      { return field($_[0], "description"); }
332 333 334
sub async_mode($)       { return field($_[0], "async_mode"); }
sub async_code($)       { return field($_[0], "async_code"); }
sub async_output($)     { return field($_[0], "async_output"); }
335 336
sub portal_tag($)       { return field($_[0], "portal_tag"); }
sub portal_url($)       { return field($_[0], "portal_url"); }
337 338 339
sub cert($)		{ return $_[0]->{'CERT'}->cert(); }
sub GetCertificate($)   { return $_[0]->{'CERT'}; }
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }
340
sub STITCHLOCKED($)     { return $_[0]->{'STITCHLOCKED'}; }
341

342 343 344 345 346 347 348 349 350
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $hrn = $self->hrn();
    my $idx = $self->idx();
351

352
    return "[GeniSlice: $hrn, IDX: $idx]";
Leigh Stoller's avatar
Leigh Stoller committed
353
}
Leigh Stoller's avatar
Leigh Stoller committed
354

Leigh Stoller's avatar
Leigh Stoller committed
355
#
356
# Delete the slice, as for registration errors.
Leigh Stoller's avatar
Leigh Stoller committed
357
#
358
sub Delete($)
Leigh Stoller's avatar
Leigh Stoller committed
359 360
{
    my ($self) = @_;
361 362 363 364 365 366 367

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

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

368 369
    DBQueryWarn("delete from geni_slicecerts where uuid='$uuid'")
	or return -1;
370 371
    DBQueryWarn("delete from geni_bindings where slice_uuid='$uuid'")
	or return -1;
372 373 374 375
    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
376

377 378
    # Delete from cache. 
    delete($slices{$idx});
379 380 381
    delete($slices{$self->urn()});
    delete($slices{$self->uuid()});
    delete($slices{$self->hrn()});
382

383
    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
384 385
}

386 387 388 389 390
# The slicename is the last token in the hrn.
sub slicename($)
{
    my ($self) = @_;

Leigh Stoller's avatar
Leigh Stoller committed
391
    my ($slicename) = ($self->hrn() =~ /^.*\.([-\w]*)$/);
392 393 394 395 396 397
    $slicename = $self->hrn()
	if (!defined($slicename));

    return $slicename;
}

Leigh Stoller's avatar
Leigh Stoller committed
398 399 400 401 402 403
#
# 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.
#
404 405 406
sub urn($)
{
    my ($self) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
407
    my $urn = $self->GetCertificate()->urn();
408

Leigh Stoller's avatar
Leigh Stoller committed
409 410 411 412
    return $urn
	if (defined($urn) && $urn ne "");

    return $self->uuid();
413 414
}

Leigh Stoller's avatar
Leigh Stoller committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
#
# 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);
}

433 434 435 436 437 438 439
#
# Lookup all slice(s) in a specified project (name, not urn).
#
sub LookupByProject($$)
{
    my ($class, $project_name) = @_;

440 441 442 443 444 445
    if (! TBcheck_dbslot($project_name, "projects", "pid",
            TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)){
        print STDERR "project has an invalid name: \"$project_name\"";
        return ();
    }

446 447 448
    my $query_result =
        DBQueryWarn("select s.idx from geni_slices s JOIN geni_certificates c ON s.uuid=c.uuid ".
                    "where c.urn LIKE '%:$project_name+slice+%'");
449
    return () unless defined($query_result);
450 451 452 453 454 455 456 457 458 459

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

460 461 462 463 464 465
#
# Lookup all slice(s) of a specified creator.
#
sub LookupByCreator($$)
{
    my ($class, $creator) = @_;
466
    
467 468 469 470 471 472
    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);

473 474 475 476 477 478 479
    my @result = ();
    while (my ($idx) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($idx);
	push(@result, $slice)
	    if (defined($slice));
    }
    return @result;
480 481
}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

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
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
#
# 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;

518
    # Slice lock always takes both locks. Holder can drop the stitch lock.
Leigh Stoller's avatar
Leigh Stoller committed
519
    my $query_result =
520 521 522
	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
523 524 525 526 527
    if (!$query_result || !$query_result->numrows) {
	DBQueryWarn("unlock tables");
	return 1;
    }
    $query_result =
528 529
	DBQueryWarn("update geni_slices set ".
		    "locked=now(),stitch_locked=now() where idx='$idx'");
Leigh Stoller's avatar
Leigh Stoller committed
530 531 532 533 534
    DBQueryWarn("unlock tables");

    return 1
	if (!$query_result);
    $self->{'LOCKED'} = $$;
535
    $self->{'STITCHLOCKED'} = $$;
Leigh Stoller's avatar
Leigh Stoller committed
536 537 538 539 540 541 542 543 544 545
    return 0;
}
sub UnLock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

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

546 547
    DBQueryWarn("update geni_slices set ".
		"locked=NULL,stitch_locked=NULL where idx='$idx'")
Leigh Stoller's avatar
Leigh Stoller committed
548 549 550
	or return -1;
    
    $self->{'LOCKED'} = 0;
551 552 553 554
    $self->{'STITCHLOCKED'} = 0;
    return 0;
}

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
#
# 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;
}

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
#
# 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
622 623 624
    return 0;
}

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
#
# 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
654 655
#
# Class function to create new Geni slice from a local experiment.
656
# We want to create the key pair so that we can sign credentials.
Leigh Stoller's avatar
Leigh Stoller committed
657
#
Leigh Stoller's avatar
Leigh Stoller committed
658
sub CreateFromLocal($$$)
Leigh Stoller's avatar
Leigh Stoller committed
659
{
660
    my ($class, $experiment, $geniuser) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
661

662 663 664 665 666 667
    #
    # 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)) {
668
	print STDERR "Could not load certificate from $EMULAB_PEMFILE\n";
669 670
	return undef;
    }
Leigh Stoller's avatar
Leigh Stoller committed
671

672
    #
673
    # Need our own slice authority record.
674
    #
675
    my $authority = GeniAuthority->Lookup($certificate->uuid());
676 677 678 679
    if (!defined($authority)) {
	print STDERR "Could not find the local authority record\n";
	return undef;
    }
680 681

    #
682
    # This mirrors the code in GeniSA.pm
683
    #
684 685 686
    my $hrn = "CE" . $experiment->idx();
    my $urn = GeniHRN::Generate("@OURDOMAIN@", "slice", $hrn);
    $hrn = "${PGENIDOMAIN}.${hrn}";
Leigh Stoller's avatar
Leigh Stoller committed
687 688

    #
689
    # Generate a certificate.
Leigh Stoller's avatar
Leigh Stoller committed
690
    #
691 692
    $certificate = GeniCertificate->Create({'urn'  => $urn,
					    'hrn'  => $hrn,
693
					    'showuuid' => 1,
694
					    'email'=> $geniuser->email()});
695
    if (!defined($certificate)) {
696
	print STDERR "GeniSlice::CreateFromLocal: ".
697
	    "Could not generate new certificate $experiment\n";
Leigh Stoller's avatar
Leigh Stoller committed
698 699
	return undef;
    }
700
    # Create the slice as locked.
701
    my $slice = GeniSlice->Create($certificate, $geniuser,
702
				  $authority, $experiment->idx(), 1);
703 704 705 706
    $certificate->Delete()
	if (!defined($slice));

    return $slice;
Leigh Stoller's avatar
Leigh Stoller committed
707 708 709 710 711 712 713 714
}

#
# Register a local slice at the clearinghouse;
#
sub Register($)
{
    my ($self) = @_;
715
    my $idx    = $self->idx();
Leigh Stoller's avatar
Leigh Stoller committed
716 717 718 719

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

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

724 725 726 727 728
    my $creator = GeniUser->Lookup($self->creator_uuid(), 1);
    if (!defined($creator)) {
	print STDERR "Could not find creator for $self\n";
	return -1;
    }
729 730 731 732 733 734 735 736
    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
737 738
}

Leigh Stoller's avatar
Leigh Stoller committed
739
#
740
# Remove a local slice at the clearinghouse;
Leigh Stoller's avatar
Leigh Stoller committed
741
#
742
sub UnRegister($)
Leigh Stoller's avatar
Leigh Stoller committed
743 744 745 746
{
    my ($self) = @_;

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

Leigh Stoller's avatar
Leigh Stoller committed
749 750 751
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
752

753 754 755 756 757
    return -1
	if ($clearinghouse->RemoveSlice($self->urn()));
    $self->SetRegisteredFlag(0);

    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
758 759
}

Leigh Stoller's avatar
Leigh Stoller committed
760 761 762 763 764 765 766
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

767
    $self->GetCertificate()->Flush();
Leigh Stoller's avatar
Leigh Stoller committed
768 769 770
    delete($slices{$self->idx()});
}

Leigh Stoller's avatar
Leigh Stoller committed
771
#
Leigh Stoller's avatar
Leigh Stoller committed
772
# Return the emulab experiment for this slice.
Leigh Stoller's avatar
Leigh Stoller committed
773
#
Leigh Stoller's avatar
Leigh Stoller committed
774
sub GetExperiment($)
Leigh Stoller's avatar
Leigh Stoller committed
775
{
Leigh Stoller's avatar
Leigh Stoller committed
776
    my ($self) = @_;
777
    require Experiment;
Leigh Stoller's avatar
Leigh Stoller committed
778

Leigh Stoller's avatar
Leigh Stoller committed
779 780
    return undef
	if (!ref($self));
Leigh Stoller's avatar
Leigh Stoller committed
781

Leigh Stoller's avatar
Leigh Stoller committed
782
    return Experiment->Lookup($self->uuid());
Leigh Stoller's avatar
Leigh Stoller committed
783 784
}

Leigh Stoller's avatar
Leigh Stoller committed
785 786 787 788 789 790 791 792 793 794 795 796 797
#
# 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
798
#
Leigh Stoller's avatar
Leigh Stoller committed
799
# Check if the given SA is the actual SA for the slice.
Leigh Stoller's avatar
Leigh Stoller committed
800
#
Leigh Stoller's avatar
Leigh Stoller committed
801
sub IsSliceAuthority($$)
Leigh Stoller's avatar
Leigh Stoller committed
802
{
Leigh Stoller's avatar
Leigh Stoller committed
803
    my ($self, $authority) = @_;
Leigh Stoller's avatar
Leigh Stoller committed
804

Leigh Stoller's avatar
Leigh Stoller committed
805 806
    return 0
	if (! (ref($self) && ref($authority)));
Leigh Stoller's avatar
Leigh Stoller committed
807

Leigh Stoller's avatar
Leigh Stoller committed
808
    return 1
809
	if ($self->sa_uuid() == $authority->uuid());
Leigh Stoller's avatar
Leigh Stoller committed
810 811
    
    return 0;
Leigh Stoller's avatar
Leigh Stoller committed
812 813
}

Leigh Stoller's avatar
Leigh Stoller committed
814
#
815 816
# Server side of binding users to slices; insert entries into the bindings
# table.
Leigh Stoller's avatar
Leigh Stoller committed
817 818 819 820 821 822 823 824
# 
sub BindUser($$)
{
    my ($self, $target_user) = @_;

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

825 826 827 828 829 830 831
    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
832 833 834 835 836 837 838 839 840 841 842
    
    return 0;
}

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

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

843 844
    my $slice_uuid = $self->uuid();
    my $user_uuid  = $target_user->uuid();
Leigh Stoller's avatar
Leigh Stoller committed
845

846 847 848 849
    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
850 851 852
    return 0;
}

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
#
# 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
872
#
873 874
# 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
875 876 877 878 879 880 881 882 883 884
#
sub UserBindings($$)
{
    my ($self, $pref) = @_;
    
    return -1
	if (! (ref($self) && ref($pref)));

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

885
    if (!defined($self->{'BINDINGS'})) {
Leigh Stoller's avatar
Leigh Stoller committed
886 887 888 889 890 891
	my $query_result =
	    DBQueryWarn("select user_uuid from geni_bindings ".
			"where slice_uuid='$uuid'");
	return -1
	    if (!$query_result);

892
	my @bindings = ();
Leigh Stoller's avatar
Leigh Stoller committed
893 894

	while (my ($user_uuid) = $query_result->fetchrow_array()) {
895
	    push(@bindings, $user_uuid);
Leigh Stoller's avatar
Leigh Stoller committed
896
	}
897
	$self->{'BINDINGS'} = \@bindings;
Leigh Stoller's avatar
Leigh Stoller committed
898
    }
899
    @$pref = @{ $self->{'BINDINGS'} };
Leigh Stoller's avatar
Leigh Stoller committed
900 901 902
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
#
# 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
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
#
# 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
954 955 956 957 958 959 960 961 962 963 964
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
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
#
# 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);
985 986 987 988 989 990 991 992

    # 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();
    
993
    $self->{'SLICE'}->{'expires'} = $expires;
994 995 996
    return 0;
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
#
# 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);
}

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
#
# Set async mode
#
sub SetAsyncMode($$)
{
    my ($self, $onoff) = @_;
    my $uuid = $self->uuid();
    $onoff = ($onoff ? 1 : 0);

    DBQueryWarn("update geni_slices set async_mode='$onoff' " .
		"where uuid='$uuid'")
	or return -1;

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

sub SetAsyncError($$)
{
    my ($self, $response) = @_;
    my $uuid   = $self->uuid();
1037
    # Not a blessed reference.
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    my $code   = $response->{'code'};
    my $output = $response->{'output'};
    if (defined($output) && $output ne "") {
	$output = DBQuoteSpecial($output);
    }
    else {
	$output = "''";
    }
    DBQueryWarn("update geni_slices set async_code='$code', ".
		"  async_output=$output ".
		"where uuid='$uuid'")
	or return -1;

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

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
#
# 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;
}

1079 1080 1081 1082 1083 1084
sub SetDescription($$)
{
    my ($self, $description) = @_;
    my $uuid = $self->uuid();
    my $safe_description = DBQuoteSpecial($description);

1085
    return -1
1086 1087 1088 1089 1090 1091 1092 1093 1094
	if (!DBQueryWarn("update geni_slices set " .
			 "  description=$safe_description ".
			 "where uuid='$uuid'"));

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

    return 0;
}

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
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;
}

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
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);
    }
}

1190 1191 1192
#
# Set the shutdown field.
#
1193
sub SetShutdown($$;$)
1194
{
1195
    my ($self, $shutdown, $isshutdown) = @_;
1196 1197 1198 1199 1200 1201 1202 1203 1204
    my $uuid = $self->uuid();
    my $when;

    if ($shutdown) {
	$when = "now()";
    }
    else {
	$when = "NULL";
    }
1205 1206
    $isshutdown = (defined($isshutdown) ? ($isshutdown ? 1 : 0) : 0);

1207 1208 1209
    #
    # Always clear isshutdown so that expire_daemon knows of change.
    #
1210
    my $query_result =
1211 1212
	DBQueryWarn("update geni_slices set ".
		    "  shutdown=$when, isshutdown=$isshutdown " .
1213 1214 1215 1216
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);
Leigh Stoller's avatar
Leigh Stoller committed
1217

1218
    # XXX Wrong format, but harmless.
1219
    $self->{'SLICE'}->{'shutdown'}   = ($shutdown ? time() : undef);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    $self->{'SLICE'}->{'isshutdown'} = $isshutdown;
    return 0;
}
sub ClearShutdown($)
{
    my ($self) = @_;
    my $uuid = $self->uuid();

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

    # XXX Wrong format, but harmless.
    $self->{'SLICE'}->{'shutdown'}   = undef;
1238
    $self->{'SLICE'}->{'isshutdown'} = 0;
Leigh Stoller's avatar
Leigh Stoller committed
1239 1240 1241
    return 0;
}

Leigh Stoller's avatar
Leigh Stoller committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
#
# 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;
}

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
#
# 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;
}

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
#
# 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;
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
#
# 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;
}

1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
#
# 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;
}

1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
#
# 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;
}

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
#
# 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;
}

1391 1392 1393 1394 1395 1396
#
# Delete all slices for an authority.
#
sub DeleteAll($$)
{
    my ($class, $authority) = @_;
1397
    require GeniAggregate;
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440

    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;
}

1441 1442 1443
#
# List all slices, optionally for an authority.
#
1444
sub ListAll($$;$)
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
{
    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;
}

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

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
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;
}

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
#
# 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;
}

1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
#
# 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);
}

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
sub SetPortalTag($$)
{
    my ($self, $tag) = @_;
    my $uuid = $self->uuid();
    my $safe_tag = DBQuoteSpecial($tag);

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

    $self->{'SLICE'}->{'portal_tag'} = $tag;
    return 0;
}
sub SetPortalURL($$)
{
    my ($self, $url) = @_;
    my $uuid = $self->uuid();
    my $safe_url = DBQuoteSpecial($url);

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

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

# Turn the URN into an experiment ID at the Portal.
sub portal_eid($)
{
    my ($self) = @_;
    my $urn = $self->urn();

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

    my $eid = $urn->id();
    $eid = $urn->project() . "/" . $eid if (defined($urn->project()));

    return $eid;
}

#
# Generate a Portal URL.
#
sub GetPortalURL($)
{
    my ($self) = @_;
    my $portal_url;

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

    my $speaker = $self->speaksfor_urn();
    return undef
	if (!defined($speaker));

    return undef
	if (! ($speaker->domain() eq $OURDOMAIN ||
	       $speaker->domain() eq "emulab.net"));
    
    if ($speaker->domain() eq $OURDOMAIN) {
        $portal_url = "$TBBASE/portal/";
    }
    else {
        $portal_url = "https://www.emulab.net/portal/";
    }
Leigh Stoller's avatar
Leigh Stoller committed
1640
    $portal_url .= "status.php?slice_uuid=" . $self->uuid();
1641 1642 1643
    return $portal_url;
}

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 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
##########################################################################
#
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);
}

1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
sub UpdateExpire($$)
{
    my ($self, $new_expires) = @_;

    if (! ref($self)) {
        print STDERR "UpdateExpire error: self ref error\n";
        return -1;
    }

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

    my $safe_expires = DBQuoteSpecial($new_expires);

    my $query_res = DBQueryWarn("update client_slivers set expires=$safe_expires where idx='$idx'");
	if (!$query_res) {
        print STDERR "UpdateExpire error: DB error\n";
        return -1;
    }
    
    return 0;
}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
#
# 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
1874 1875
# _Always_ make sure that this 1 is at the end of the file...
1;