GeniSlice.pm.in 40.8 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
29 30 31 32 33
#
package GeniSlice;

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

# Must come after package declaration!
use GeniDB;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
39
use GeniRegistry;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
40 41
use GeniAuthority;
use GeniCredential;
42
use GeniCertificate;
43
use GeniUser;
44
use GeniHRN;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
45
use English;
46
use libEmulab;
47
use emutil;
48
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
49
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
50
use vars qw();
51
use overload ('""' => 'Stringify');
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
59 60 61
my $BOSSNODE       = "@BOSSNODE@";
my $CONTROL	   = "@USERNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
62
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
63 64 65

# Cache of instances to avoid regenerating them.
my %slices     = ();
66
BEGIN { use GeniUtil; GeniUtil::AddCache(\%slices); }
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. Stoller committed
81 82 83 84
#
sub Lookup($$)
{
    my ($class, $token) = @_;
85 86
    my $query_result;
    my $idx;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
87

88 89
    return $slices{"$token"}
        if (exists($slices{"$token"}));
Leigh B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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 B. Stoller's avatar
Leigh B. 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");
Leigh B Stoller's avatar
Leigh B Stoller committed
298 299 300 301
    my $slice = GeniSlice->Lookup($idx);
    return undef
	if (!defined($slice));

302
    $slice->{'LOCKED'} = $slice->{'STITCHLOCKED'} = $$
Leigh B Stoller's avatar
Leigh B Stoller committed
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 B Stoller's avatar
Leigh B 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 337
sub cert($)		{ return $_[0]->{'CERT'}->cert(); }
sub GetCertificate($)   { return $_[0]->{'CERT'}; }
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }
338
sub STITCHLOCKED($)     { return $_[0]->{'STITCHLOCKED'}; }
339

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

350
    return "[GeniSlice: $hrn, IDX: $idx]";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
351
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
352

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

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

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

366 367
    DBQueryWarn("delete from geni_slicecerts where uuid='$uuid'")
	or return -1;
368 369
    DBQueryWarn("delete from geni_bindings where slice_uuid='$uuid'")
	or return -1;
370 371 372 373
    DBQueryWarn("delete from geni_certificates where uuid='$uuid'")
	or return -1;
    DBQueryWarn("delete from geni_slices where idx='$idx'")
	or return -1;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
374

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

381
    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
382 383
}

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

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

    return $slicename;
}

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
407 408 409 410
    return $urn
	if (defined($urn) && $urn ne "");

    return $self->uuid();
411 412
}

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

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

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

444 445 446
    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+%'");
447
    return () unless defined($query_result);
448 449 450 451 452 453 454 455 456 457

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

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

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

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

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 B. Stoller's avatar
Leigh B. Stoller committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
#
# 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;

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

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

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

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

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

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

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
#
# 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 B. Stoller's avatar
Leigh B. Stoller committed
652 653
#
# Class function to create new Geni slice from a local experiment.
654
# We want to create the key pair so that we can sign credentials.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
655
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
656
sub CreateFromLocal($$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
657
{
658
    my ($class, $experiment, $geniuser) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
659

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

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

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

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

    return $slice;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
705 706 707 708 709 710 711 712
}

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

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

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

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

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

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

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

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

    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
756 757
}

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

765
    $self->GetCertificate()->Flush();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
766 767 768
    delete($slices{$self->idx()});
}

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
777 778
    return undef
	if (!ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
779

Leigh B. Stoller's avatar
Leigh B. Stoller committed
780
    return Experiment->Lookup($self->uuid());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
781 782
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
783 784 785 786 787 788 789 790 791 792 793 794 795
#
# Return the slice authority for this slice.
#
sub SliceAuthority($)
{
    my ($self) = @_;

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

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
796
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
797
# Check if the given SA is the actual SA for the slice.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
798
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
799
sub IsSliceAuthority($$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
800
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
801
    my ($self, $authority) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
802

Leigh B. Stoller's avatar
Leigh B. Stoller committed
803 804
    return 0
	if (! (ref($self) && ref($authority)));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
805

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

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

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

823 824 825 826 827 828 829
    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 B. Stoller's avatar
Leigh B. Stoller committed
830 831 832 833 834 835 836 837 838 839 840
    
    return 0;
}

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

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

841 842
    my $slice_uuid = $self->uuid();
    my $user_uuid  = $target_user->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
843

844 845 846 847
    DBQueryWarn("delete from geni_bindings ".
		"where slice_uuid='$slice_uuid' and user_uuid='$user_uuid'")
	or return -1;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
848 849 850
    return 0;
}

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

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

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

890
	my @bindings = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
891 892

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

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

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

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

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
#
# 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();
1035
    # Not a blessed reference.
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    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;
}

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

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

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

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

    return 0;
}

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

1108 1109 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
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);
    }
}

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

    if ($shutdown) {
	$when = "now()";
    }
    else {
	$when = "NULL";
    }
1203