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

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

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

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

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

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

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

90 91 92 93 94 95 96 97 98 99
    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.
100
	    my $safe_id = DBQuoteSpecial($id);
101 102
	    $query_result =
		DBQueryWarn("select idx from geni_slices ".
103
			    "where hrn='@PROTOGENI_DOMAIN@.$safe_id'");
104 105 106
	} else {
	    # Somebody else's slice.  We'll have to look up the slice
	    # by its certificate, which will work only for post-URN slices.
107
	    my $safe_token = DBQuoteSpecial($token);
108 109 110
	    $query_result = DBQueryWarn(
		"SELECT geni_slices.idx FROM geni_slices, geni_certificates " .
		"WHERE geni_slices.uuid = geni_certificates.uuid AND " .
111
		"geni_certificates.urn='$safe_token';" );
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	}

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

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

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

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

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

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

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

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

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

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    #
    # 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.
	#
268 269 270
	if ($isplaceholder) {
	    if (defined($creator)) {
		push(@insert_data, "idx='$curidx'");
271
	    
272 273 274 275 276 277 278
		if (! DBQueryWarn("replace into geni_slices set " .
				  "  isplaceholder=0, ".
				  join(",", @insert_data))) {
		    DBQueryWarn("unlock tables");
		    return undef;
		}
		$idx = $curidx;
279
	    }
280
	    goto lookup;
281
	}
282 283 284
	print STDERR "Slice already exists in database\n";
	DBQueryWarn("unlock tables");
	return undef;
285 286 287
    }
    # Do this after above code since we might need to overwrite entry.
    push(@insert_data, "idx='$idx'");
288

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

301
    $slice->{'LOCKED'} = $slice->{'STITCHLOCKED'} = $$
Leigh B Stoller's avatar
Leigh B Stoller committed
302 303
	if (defined($lock) && $lock);
    return $slice;
304 305 306 307 308 309
}
# 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"); }
310
sub publicid($)		{ return field($_[0], "publicid"); }
311 312
sub creator_uuid($)	{ return field($_[0], "creator_uuid"); }
sub creator_urn($)	{ return field($_[0], "creator_urn"); }
313
sub creator_urnOBJ($)	{ return field($_[0], "creator_urnOBJ"); }
314 315
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"); }
324
sub isplaceholder($)	{ return field($_[0], "isplaceholder"); }
325
sub monitor_pid($)	{ return field($_[0], "monitor_pid"); }
326
sub speaksfor_urn($)	{ return field($_[0], "speaksfor_urn"); }
327
sub speaksfor_urnOBJ($)	{ return field($_[0], "speaksfor_urnOBJ"); }
328
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 cert($)		{ return $_[0]->{'CERT'}->cert(); }
sub GetCertificate($)   { return $_[0]->{'CERT'}; }
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }
335
sub STITCHLOCKED($)     { return $_[0]->{'STITCHLOCKED'}; }
336

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

347
    return "[GeniSlice: $hrn, IDX: $idx]";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
348
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
349

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

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

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

363 364
    DBQueryWarn("delete from geni_slicecerts where uuid='$uuid'")
	or return -1;
365 366
    DBQueryWarn("delete from geni_bindings where slice_uuid='$uuid'")
	or return -1;
367 368 369 370
    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
371

372 373
    # Delete from cache. 
    delete($slices{$idx});
374 375 376
    delete($slices{$self->urn()});
    delete($slices{$self->uuid()});
    delete($slices{$self->hrn()});
377

378
    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
379 380
}

381 382 383 384 385
# The slicename is the last token in the hrn.
sub slicename($)
{
    my ($self) = @_;

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

    return $slicename;
}

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
404 405 406 407
    return $urn
	if (defined($urn) && $urn ne "");

    return $self->uuid();
408 409
}

410 411 412 413 414 415 416
sub urnOBJ($)
{
    my ($self) = @_;

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

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

435 436 437 438 439 440
#
# Lookup all slice(s) of a specified creator.
#
sub LookupByCreator($$)
{
    my ($class, $creator) = @_;
441
    
442 443 444 445 446 447
    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);

448 449 450 451 452 453 454
    my @result = ();
    while (my ($idx) = $query_result->fetchrow_array()) {
	my $slice = GeniSlice->Lookup($idx);
	push(@result, $slice)
	    if (defined($slice));
    }
    return @result;
455 456
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

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
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
#
# 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;

493
    # Slice lock always takes both locks. Holder can drop the stitch lock.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
494
    my $query_result =
495 496 497
	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
498 499 500 501 502
    if (!$query_result || !$query_result->numrows) {
	DBQueryWarn("unlock tables");
	return 1;
    }
    $query_result =
503 504
	DBQueryWarn("update geni_slices set ".
		    "locked=now(),stitch_locked=now() where idx='$idx'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
505 506 507 508 509
    DBQueryWarn("unlock tables");

    return 1
	if (!$query_result);
    $self->{'LOCKED'} = $$;
510
    $self->{'STITCHLOCKED'} = $$;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
511 512 513 514 515 516 517 518 519 520
    return 0;
}
sub UnLock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

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

521 522
    DBQueryWarn("update geni_slices set ".
		"locked=NULL,stitch_locked=NULL where idx='$idx'")
Leigh B. Stoller's avatar
Leigh B. Stoller committed
523 524 525
	or return -1;
    
    $self->{'LOCKED'} = 0;
526 527 528 529
    $self->{'STITCHLOCKED'} = 0;
    return 0;
}

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
#
# 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;
}

550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
#
# 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
597 598 599
    return 0;
}

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
#
# 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
629 630
#
# Class function to create new Geni slice from a local experiment.
631
# We want to create the key pair so that we can sign credentials.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
632
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
633
sub CreateFromLocal($$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
634
{
635
    my ($class, $experiment, $geniuser) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
636

637 638 639 640 641 642
    #
    # 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)) {
643
	print STDERR "Could not load certificate from $EMULAB_PEMFILE\n";
644 645
	return undef;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
646

647
    #
648
    # Need our own slice authority record.
649
    #
650
    my $authority = GeniAuthority->Lookup($certificate->uuid());
651 652 653 654
    if (!defined($authority)) {
	print STDERR "Could not find the local authority record\n";
	return undef;
    }
655 656

    #
657
    # This mirrors the code in GeniSA.pm
658
    #
659 660 661
    my $hrn = "CE" . $experiment->idx();
    my $urn = GeniHRN::Generate("@OURDOMAIN@", "slice", $hrn);
    $hrn = "${PGENIDOMAIN}.${hrn}";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
662 663

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

    return $slice;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
682 683 684 685 686 687 688 689
}

#
# Register a local slice at the clearinghouse;
#
sub Register($)
{
    my ($self) = @_;
690
    my $idx    = $self->idx();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
691 692 693 694

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
695 696 697
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
698

699 700 701 702 703
    my $creator = GeniUser->Lookup($self->creator_uuid(), 1);
    if (!defined($creator)) {
	print STDERR "Could not find creator for $self\n";
	return -1;
    }
704 705 706 707 708 709 710 711
    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
712 713
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
714
#
715
# Remove a local slice at the clearinghouse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
716
#
717
sub UnRegister($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
718 719 720 721
{
    my ($self) = @_;

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
724 725 726
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
727

728 729 730 731 732
    return -1
	if ($clearinghouse->RemoveSlice($self->urn()));
    $self->SetRegisteredFlag(0);

    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
733 734
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
735 736 737 738 739 740 741 742 743 744
#
# Flush from our little cache, as for the expire daemon.
#
sub Flush($)
{
    my ($self) = @_;

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
745
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
746
# Return the emulab experiment for this slice.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
747
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
748
sub GetExperiment($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
749
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
750
    my ($self) = @_;
751
    require Experiment;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
752

Leigh B. Stoller's avatar
Leigh B. Stoller committed
753 754
    return undef
	if (!ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
755

Leigh B. Stoller's avatar
Leigh B. Stoller committed
756
    return Experiment->Lookup($self->uuid());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
757 758
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
759 760 761 762 763 764 765 766 767 768 769 770 771
#
# 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
772
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
773
# Check if the given SA is the actual SA for the slice.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
774
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
775
sub IsSliceAuthority($$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
776
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
777
    my ($self, $authority) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
778

Leigh B. Stoller's avatar
Leigh B. Stoller committed
779 780
    return 0
	if (! (ref($self) && ref($authority)));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
781

Leigh B. Stoller's avatar
Leigh B. Stoller committed
782
    return 1
783
	if ($self->sa_uuid() == $authority->uuid());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
784 785
    
    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
786 787
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
788
#
789 790
# Server side of binding users to slices; insert entries into the bindings
# table.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
791 792 793 794 795 796 797 798
# 
sub BindUser($$)
{
    my ($self, $target_user) = @_;

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

799 800 801 802 803 804 805
    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
806 807 808 809 810 811 812 813 814 815 816
    
    return 0;
}

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

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

817 818
    my $slice_uuid = $self->uuid();
    my $user_uuid  = $target_user->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
819

820 821 822 823
    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
824 825 826
    return 0;
}

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
#
# 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
846
#
847 848
# 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
849 850 851 852 853 854 855 856 857 858
#
sub UserBindings($$)
{
    my ($self, $pref) = @_;
    
    return -1
	if (! (ref($self) && ref($pref)));

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

859
    if (!defined($self->{'BINDINGS'})) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
860 861 862 863 864 865
	my $query_result =
	    DBQueryWarn("select user_uuid from geni_bindings ".
			"where slice_uuid='$uuid'");
	return -1
	    if (!$query_result);

866
	my @bindings = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
867 868

	while (my ($user_uuid) = $query_result->fetchrow_array()) {
869
	    push(@bindings, $user_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
870
	}
871
	$self->{'BINDINGS'} = \@bindings;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
872
    }
873
    @$pref = @{ $self->{'BINDINGS'} };
Leigh B. Stoller's avatar
Leigh B. Stoller committed
874 875 876
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
#
# 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
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
#
# 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
928 929 930 931 932 933 934 935 936 937 938
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
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
#
# 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);
959 960 961 962 963 964 965 966

    # 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();
    
967
    $self->{'SLICE'}->{'expires'} = $expires;
968 969 970
    return 0;
}

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
#
# 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);
}

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

1014 1015 1016 1017 1018 1019
sub SetDescription($$)
{
    my ($self, $description) = @_;
    my $uuid = $self->uuid();
    my $safe_description = DBQuoteSpecial($description);

1020
    return -1
1021 1022 1023 1024 1025 1026 1027 1028 1029
	if (!DBQueryWarn("update geni_slices set " .
			 "  description=$safe_description ".
			 "where uuid='$uuid'"));

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

    return 0;
}

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
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;
}

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
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);
    }
}

1125 1126 1127
#
# Set the shutdown field.
#
1128
sub SetShutdown($$;$)
1129
{
1130
    my ($self, $shutdown, $isshutdown) = @_;
1131 1132 1133 1134 1135 1136 1137 1138 1139
    my $uuid = $self->uuid();
    my $when;

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

1142 1143 1144
    #
    # Always clear isshutdown so that expire_daemon knows of change.
    #
1145
    my $query_result =
1146 1147
	DBQueryWarn("update geni_slices set ".
		    "  shutdown=$when, isshutdown=$isshutdown " .
1148 1149 1150 1151
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1152

1153
    # XXX Wrong format, but harmless.
1154
    $self->{'SLICE'}->{'shutdown'}   = ($shutdown ? time() : undef);
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    $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;
1173
    $self->{'SLICE'}->{'isshutdown'} = 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1174 1175 1176
    return 0;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
#
# 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;
}