GeniSlice.pm.in 26.2 KB
Newer Older
Leigh B. Stoller's avatar
Leigh B. Stoller committed
1 2
#!/usr/bin/perl -wT
#
3
# GENIPUBLIC-COPYRIGHT
4
# Copyright (c) 2008-2011 University of Utah and the Flux Group.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
5 6 7 8 9 10
# All rights reserved.
#
package GeniSlice;

use strict;
use Exporter;
11
use vars qw(@ISA);
12
@ISA = "Exporter";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
13 14 15

# Must come after package declaration!
use GeniDB;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
16
use GeniRegistry;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
17 18
use GeniAuthority;
use GeniCredential;
19
use GeniCertificate;
20
use GeniUser;
21
use GeniHRN;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
22
use English;
23
use emutil qw(TBGetUniqueIndex);
24
use Date::Parse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
25
use Data::Dumper;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
26
use vars qw();
27
use overload ('""' => 'Stringify');
Leigh B. Stoller's avatar
Leigh B. Stoller committed
28 29 30 31 32 33 34 35 36

# Configure variables
my $TB		   = "@prefix@";
my $TBOPS          = "@TBOPSEMAIL@";
my $TBAPPROVAL     = "@TBAPPROVALEMAIL@";
my $TBAUDIT   	   = "@TBAUDITEMAIL@";
my $BOSSNODE       = "@BOSSNODE@";
my $CONTROL	   = "@USERNODE@";
my $OURDOMAIN      = "@OURDOMAIN@";
37
my $PGENIDOMAIN    = "@PROTOGENI_DOMAIN@";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
38 39 40

# Cache of instances to avoid regenerating them.
my %slices     = ();
41
BEGIN { use GeniUtil; GeniUtil::AddCache(\%slices); }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
42 43 44 45 46 47 48 49 50 51 52 53 54
my $debug      = 0;

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

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

#
55
# Lookup by idx, URN or uuid.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
56 57 58 59
#
sub Lookup($$)
{
    my ($class, $token) = @_;
60 61
    my $query_result;
    my $idx;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
62

63 64
    return $slices{"$token"}
        if (exists($slices{"$token"}));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    if( GeniHRN::IsValid( $token ) ) {
	my ($authority, $type, $id) = GeniHRN::Parse( $token );

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

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

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

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

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

    $query_result =
	DBQueryWarn("select * from geni_slices where idx='$idx'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
119
    return undef
120
	if (!$query_result || !$query_result->numrows);
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    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;
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
139
    # Add to cache. 
140 141 142 143
    $slices{$self->idx()}  = $self;
    $slices{$self->urn()}  = $self;
    $slices{$self->uuid()} = $self;
    $slices{$self->hrn()}  = $self;
144
    
145
    return $self;
146 147 148 149 150
}

#
# Class function to create new Geni slice and return the object.
#
151
sub Create($$$$;$$)
152
{
153
    my ($class, $certificate, $creator, $authority, $exptidx, $lock) = @_;
154
    my @insert_data = ();
155

156 157
    # Every slice gets a new unique index.
    my $idx = TBGetUniqueIndex('next_exptidx', 1);
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172
    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()");
    push(@insert_data, "expires=DATE_ADD(now(), INTERVAL 6 HOUR)");
    push(@insert_data, "sa_uuid='$sa_uuid'");
    push(@insert_data, "exptidx=$exptidx")
	if (defined($exptidx));
    push(@insert_data, "locked=now()")
	if (defined($lock) && $lock);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
173
    
174 175 176 177
    my $safe_hrn   = DBQuoteSpecial($certificate->hrn());
    my $safe_uuid  = DBQuoteSpecial($certificate->uuid());
    push(@insert_data, "hrn=$safe_hrn");
    push(@insert_data, "uuid=$safe_uuid");
178 179 180 181 182 183 184 185 186 187 188 189

    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'");
    }
190 191 192 193 194 195

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

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    #
    # Lock the table and look for an existing entry. If there is one,
    # and it is the placeholder entry, overwrite it.
    #
    DBQueryWarn("lock tables geni_slices write")
	or return undef;
    my $query_result =
	DBQueryWarn("select idx,isplaceholder from geni_slices " .
		    "where uuid=$safe_uuid or hrn=$safe_hrn");
    if (!$query_result) {
	DBQueryWarn("unlock tables");
	return undef;
    }
    if ($query_result->numrows) {
	if ($query_result->numrows != 1) {
	    my $urn  = $certificate->urn();
	    my $uuid = $certificate->uuid();
	    my $hrn  = $certificate->hrn();
	    print STDERR "Too many rows for $uuid/$hrn/$urn\n";
	    DBQueryWarn("unlock tables");
	    return undef;
	}
	my ($curidx,$isplaceholder) = $query_result->fetchrow_array();
	#
	# If the existing entry is a placeholder, and we got the creator,
	# then replace the existing entry to make it a non-placeholder.
	#
	if ($isplaceholder && defined($creator)) {
	    push(@insert_data, "idx='$curidx'");
	    
	    if (! DBQueryWarn("replace into geni_slices set " .
			      "  isplaceholder=0, ".
			      join(",", @insert_data))) {
		DBQueryWarn("unlock tables");
		return undef;
	    }
	    $idx = $curidx;
	    goto didit;
	}
    }
    # Do this after above code since we might need to overwrite entry.
    push(@insert_data, "idx='$idx'");
238

239 240 241 242 243 244 245 246
    # Insert into DB.
    if (! DBQueryWarn("insert into geni_slices set " .
		      join(",", @insert_data))) {
        DBQueryWarn("unlock tables");
	return undef;
    }
  didit:
    DBQueryWarn("unlock tables");
Leigh B Stoller's avatar
Leigh B Stoller committed
247 248 249 250 251 252 253
    my $slice = GeniSlice->Lookup($idx);
    return undef
	if (!defined($slice));

    $slice->{'LOCKED'} = $$
	if (defined($lock) && $lock);
    return $slice;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
}
# 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"); }
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"); }
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"); }
sub registered($)	{ return field($_[0], "registered"); }
269
sub isplaceholder($)	{ return field($_[0], "isplaceholder"); }
270 271 272
sub cert($)		{ return $_[0]->{'CERT'}->cert(); }
sub GetCertificate($)   { return $_[0]->{'CERT'}; }
sub LOCKED($)           { return $_[0]->{'LOCKED'}; }
273

274 275 276 277 278 279 280 281 282
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $hrn = $self->hrn();
    my $idx = $self->idx();
283

284
    return "[GeniSlice: $hrn, IDX: $idx]";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
285
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
286

Leigh B. Stoller's avatar
Leigh B. Stoller committed
287
#
288
# Delete the slice, as for registration errors.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
289
#
290
sub Delete($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
291 292
{
    my ($self) = @_;
293 294 295 296 297 298 299 300 301

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

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

    DBQueryWarn("delete from geni_bindings where slice_uuid='$uuid'")
	or return -1;
302 303 304 305
    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
306

307 308
    # Delete from cache. 
    delete($slices{$idx});
309 310 311
    delete($slices{$self->urn()});
    delete($slices{$self->uuid()});
    delete($slices{$self->hrn()});
312

313
    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
314 315
}

316 317 318 319 320 321 322 323 324 325 326 327
# The slicename is the last token in the hrn.
sub slicename($)
{
    my ($self) = @_;

    my ($slicename) = ($self->hrn() =~ /^.*\.(\w*)$/);
    $slicename = $self->hrn()
	if (!defined($slicename));

    return $slicename;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
328 329 330 331 332 333
#
# 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.
#
334 335 336
sub urn($)
{
    my ($self) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
337
    my $urn = $self->GetCertificate()->urn();
338

Leigh B. Stoller's avatar
Leigh B. Stoller committed
339 340 341 342
    return $urn
	if (defined($urn) && $urn ne "");

    return $self->uuid();
343 344
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
#
# 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);
}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
#
# Lookup all slice(s) of a specified creator.
#
sub LookupByCreator($$)
{
    my ($class, $creator) = @_;

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

    return map( GeniSlice->Lookup( $_ ), $query_result->fetchcol( 0 ) );
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
#
# 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;

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

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

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

    DBQueryWarn("update geni_slices set locked=NULL where idx='$idx'")
	or return -1;
    
    $self->{'LOCKED'} = 0;
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
426 427
#
# Class function to create new Geni slice from a local experiment.
428
# We want to create the key pair so that we can sign credentials.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
429
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
430
sub CreateFromLocal($$$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
431
{
432
    my ($class, $experiment, $geniuser) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
433

434 435 436 437 438 439
    #
    # 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)) {
440
	print STDERR "Could not load certificate from $EMULAB_PEMFILE\n";
441 442
	return undef;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
443

444
    #
445
    # Need our own slice authority record.
446
    #
447
    my $authority = GeniAuthority->Lookup($certificate->uuid());
448 449 450 451
    if (!defined($authority)) {
	print STDERR "Could not find the local authority record\n";
	return undef;
    }
452 453

    #
454
    # This mirrors the code in GeniSA.pm
455
    #
456 457 458
    my $hrn = "CE" . $experiment->idx();
    my $urn = GeniHRN::Generate("@OURDOMAIN@", "slice", $hrn);
    $hrn = "${PGENIDOMAIN}.${hrn}";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
459 460

    #
461
    # Generate a certificate.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
462
    #
463 464 465
    $certificate = GeniCertificate->Create({'urn'  => $urn,
					    'hrn'  => $hrn,
					    'email'=> $geniuser->email()});
466
    if (!defined($certificate)) {
467
	print STDERR "GeniSlice::CreateFromLocal: ".
468
	    "Could not generate new certificate $experiment\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
469 470
	return undef;
    }
471
    # Create the slice as locked.
472
    my $slice = GeniSlice->Create($certificate, $geniuser,
473
				  $authority, $experiment->idx(), 1);
474 475 476 477
    $certificate->Delete()
	if (!defined($slice));

    return $slice;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
478 479 480 481 482 483 484 485
}

#
# Register a local slice at the clearinghouse;
#
sub Register($)
{
    my ($self) = @_;
486
    my $idx    = $self->idx();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
487 488 489 490

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
491 492 493
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
494

495 496 497 498 499
    my $creator = GeniUser->Lookup($self->creator_uuid(), 1);
    if (!defined($creator)) {
	print STDERR "Could not find creator for $self\n";
	return -1;
    }
500 501 502 503 504 505 506 507
    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
508 509
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
510
#
511
# Remove a local slice at the clearinghouse;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
512
#
513
sub UnRegister($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
514 515 516 517
{
    my ($self) = @_;

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
520 521 522
    my $clearinghouse = GeniRegistry::ClearingHouse->Create();
    return -1
	if (!defined($clearinghouse));
523

524 525 526 527 528
    return -1
	if ($clearinghouse->RemoveSlice($self->urn()));
    $self->SetRegisteredFlag(0);

    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
529 530
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
531 532 533 534 535 536 537 538 539 540
#
# 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
541
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
542
# Return the emulab experiment for this slice.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
543
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
544
sub GetExperiment($)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
545
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
546
    my ($self) = @_;
547
    require Experiment;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
548

Leigh B. Stoller's avatar
Leigh B. Stoller committed
549 550
    return undef
	if (!ref($self));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
551

Leigh B. Stoller's avatar
Leigh B. Stoller committed
552
    return Experiment->Lookup($self->uuid());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
553 554
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
555 556 557 558 559 560 561 562 563 564 565 566 567
#
# 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
568
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
569
# Check if the given SA is the actual SA for the slice.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
570
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
571
sub IsSliceAuthority($$)
Leigh B. Stoller's avatar
Leigh B. Stoller committed
572
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
573
    my ($self, $authority) = @_;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
574

Leigh B. Stoller's avatar
Leigh B. Stoller committed
575 576
    return 0
	if (! (ref($self) && ref($authority)));
Leigh B. Stoller's avatar
Leigh B. Stoller committed
577

Leigh B. Stoller's avatar
Leigh B. Stoller committed
578
    return 1
579
	if ($self->sa_uuid() == $authority->uuid());
Leigh B. Stoller's avatar
Leigh B. Stoller committed
580 581
    
    return 0;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
582 583
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
584
#
585 586
# Server side of binding users to slices; insert entries into the bindings
# table.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
587 588 589 590 591 592 593 594
# 
sub BindUser($$)
{
    my ($self, $target_user) = @_;

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

595 596 597 598 599 600 601
    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
602 603 604 605 606 607 608 609 610 611 612
    
    return 0;
}

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

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

613 614
    my $slice_uuid = $self->uuid();
    my $user_uuid  = $target_user->uuid();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
615

616 617 618 619
    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
620 621 622
    return 0;
}

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
#
# 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
642
#
643 644
# 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
645 646 647 648 649 650 651 652 653 654
#
sub UserBindings($$)
{
    my ($self, $pref) = @_;
    
    return -1
	if (! (ref($self) && ref($pref)));

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

655
    if (!defined($self->{'BINDINGS'})) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
656 657 658 659 660 661
	my $query_result =
	    DBQueryWarn("select user_uuid from geni_bindings ".
			"where slice_uuid='$uuid'");
	return -1
	    if (!$query_result);

662
	my @bindings = ();
Leigh B. Stoller's avatar
Leigh B. Stoller committed
663 664

	while (my ($user_uuid) = $query_result->fetchrow_array()) {
665
	    push(@bindings, $user_uuid);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
666
	}
667
	$self->{'BINDINGS'} = \@bindings;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
668
    }
669
    @$pref = @{ $self->{'BINDINGS'} };
Leigh B. Stoller's avatar
Leigh B. Stoller committed
670 671 672
    return 0;
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
#
# 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();
}

#
# 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);
715 716 717 718 719 720 721 722

    # 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();
    
723
    $self->{'SLICE'}->{'expires'} = $expires;
724 725 726
    return 0;
}

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
#
# 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);
}

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
#
# Set the shutdown field.
#
sub SetShutdown($$)
{
    my ($self, $shutdown) = @_;
    my $uuid = $self->uuid();
    my $when;

    if ($shutdown) {
	$when = "now()";
    }
    else {
	$when = "NULL";
    }
    my $query_result =
	DBQueryWarn("update geni_slices set shutdown=$when " .
		    "where uuid='$uuid'");
    
    return -1
	if (!$query_result);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
767

768 769
    # XXX Wrong format, but harmless.
    $self->{'SLICE'}->{'shutdown'} = ($shutdown ? time() : undef);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
770 771 772
    return 0;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
#
# 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;
}

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

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
#
# 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;
}

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
#
# 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;
}

863 864 865 866 867 868
#
# Delete all slices for an authority.
#
sub DeleteAll($$)
{
    my ($class, $authority) = @_;
869
    require GeniAggregate;
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

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

913 914 915
#
# List all slices, optionally for an authority.
#
916
sub ListAll($$;$)
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
{
    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;
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 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
##########################################################################
#
package GeniSlice::ClientSliver;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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