APT_Dataset.pm.in 14 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2007-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 29 30 31 32 33 34 35 36 37 38 39 40 41
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
package APT_Dataset;

use strict;
use English;
use Data::Dumper;
use Carp;
use Exporter;
use vars qw(@ISA @EXPORT $AUTOLOAD);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use EmulabConstants;
use emdb;
use emutil;
use libtestbed;
use APT_Geni;
Leigh B Stoller's avatar
Leigh B Stoller committed
42
use GeniHRN;
43 44 45
use Genixmlrpc;
use GeniResponse;
use GeniCertificate;
Leigh B Stoller's avatar
Leigh B Stoller committed
46 47
use GeniAuthority;
use GeniCredential;
48 49 50 51 52
use overload ('""' => 'Stringify');

# Configure variables
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
Leigh B Stoller's avatar
Leigh B Stoller committed
53
my $OURDOMAIN     = "@OURDOMAIN@";
54

55
# Debugging
56
my $usemydevtree  = 0;
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
#
# Lookup by uuid.
#
sub Lookup($$;$)
{
    my ($class, $token) = @_;
    my $query_result;

    if ($token =~ /^\w+\-\w+\-\w+\-\w+\-\w+$/) {
	$query_result =
	    DBQueryWarn("select * from apt_datasets where uuid='$token'");
    }
    elsif ($token =~ /^([-\w]+)\/([-\w]+)$/) {
	$query_result =
	    DBQueryWarn("select * from apt_datasets ".
			"where pid='$1' and dataset_id='$2'");
    }
    else {
	return undef;
    }
    return undef
	if (!$query_result || !$query_result->numrows);

    my $self            = {};
    $self->{'DATASET'}  = $query_result->fetchrow_hashref();

    bless($self, $class);
    
    return $self;
}

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
#
# Lookup by remote URN.
#
sub LookupByRemoteURN($$)
{
    my ($class, $urn) = @_;

    return undef
	if (!GeniHRN::IsValid($urn));

    my $safe_urn = DBQuoteSpecial($urn);
    my $query_result =
	DBQueryWarn("select uuid from apt_datasets ".
		    "where remote_urn=$safe_urn");
    return undef
	if (!$query_result || !$query_result->numrows);

    my ($uuid) = $query_result->fetchrow_array();
    return Lookup($class, $uuid);
}

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
AUTOLOAD {
    my $self  = $_[0];
    my $type  = ref($self) or croak "$self is not an object";
    my $name  = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    # A DB row proxy method call.
    if (exists($self->{'DATASET'}->{$name})) {
	return $self->{'DATASET'}->{$name};
    }
    carp("No such slot '$name' field in class $type");
    return undef;
}

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{'DATASET'} = undef;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
131 132 133 134
# Valid Blockstore backend.
sub ValidBlockstoreBackend($)
{
    my ($authority) = @_;
135
    my ($domain,$subauth) = split(":", $authority);
Leigh B Stoller's avatar
Leigh B Stoller committed
136 137
    
    return 1
138
	if ($domain eq "emulab.net" || $domain eq "apt.emulab.net");
Leigh B Stoller's avatar
Leigh B Stoller committed
139 140 141 142

    return 0;
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

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

    my $uuid = $self->uuid();
    
    my $query_result =
	DBQueryWarn("select * from apt_datasets where uuid='$uuid'");

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

    $self->{'DATASET'} = $query_result->fetchrow_hashref();

    return 0;
}

#
# Create an Dataset
#
sub Create($$)
{
    my ($class, $argref) = @_;
    my $uuid;

    if (exists($argref->{'uuid'})) {
	$uuid = $argref->{'uuid'};
	delete($argref->{'uuid'});
    }
    else {
	$uuid = NewUUID();
    }
    my $idx = TBGetUniqueIndex('next_leaseidx');

    #
    # The uuid has to be unique, so lock the table for the check/insert.
    #
    DBQueryWarn("lock tables apt_datasets write")
	or return undef;

    my $query_result =
	DBQueryWarn("select uuid from apt_datasets where uuid='$uuid'");

    if ($query_result->numrows) {
	DBQueryWarn("unlock tables");
	tberror("Dataset uuid $uuid already exists!");
	return undef;
    }

    my $query = "insert into apt_datasets set ".
	" locked=now(),locker_pid='$PID', ".
	" idx='$idx',created=now(),uuid='$uuid', ".
	join(",", map("$_=" .
		      DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

    if (! DBQueryWarn($query)) {
	DBQueryWarn("unlock tables");
	tberror("Error inserting new apt_datasets record for $uuid!");
	return undef;
    }
    DBQueryWarn("unlock tables");
Leigh B Stoller's avatar
Leigh B Stoller committed
210 211 212 213 214 215 216

    my $dataset = Lookup($class, $uuid);
    return undef
	if (!defined($dataset));
    return undef
	if ($dataset->CreateCertificate());
    return $dataset;
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
}

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

    return "[APT_Dataset: $uuid]";
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

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

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

    my $query = "update apt_datasets set ".
	join(",", map("$_=" . DBQuoteSpecial($argref->{$_}), keys(%{$argref})));

    $query .= " where uuid='$uuid'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

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

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

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

Leigh B Stoller's avatar
Leigh B Stoller committed
265 266 267 268
    my $certificate = $self->GetCertificate();
    $certificate->Delete()
	if (defined($certificate));

Leigh B Stoller's avatar
Leigh B Stoller committed
269
    DBQueryWarn("delete from web_tasks where object_uuid='$uuid'") or
270
	return -1;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    DBQueryWarn("delete from apt_datasets where uuid='$uuid'") or
	return -1;

    return 0;
}

sub SetStatus($$)
{
    my ($self,$status) = @_;

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

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

    DBQueryWarn("update apt_datasets set status='$status' ".
		"where uuid='$uuid'") or
	return -1;

    $self->{'DATASET'}->{'status'} = $status;
    return 0;
    
}

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
#
# Load the project object for an experiment.
#
sub GetProject($)
{
    my ($self) = @_;
    require Project;

    my $project = Project->Lookup($self->pid_idx());
    
    if (! defined($project)) {
	print("*** WARNING: Could not lookup project object for $self!\n");
	return undef;
    }
    return $project;
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 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
#
# Lock and Unlock
#
sub Lock($;$)
{
    my ($self, $steal) = @_;

    # Already locked?
    if ($self->GotLock()) {
	return 0;
    }
    return -1
	if (!DBQueryWarn("lock tables apt_datasets write"));

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

    my $query_result =
	DBQueryWarn("update apt_datasets set locked=now(),locker_pid=$PID " .
		    "where idx=$idx ".
		    (!defined($steal) ? "and locked is null" : ""));

    if (! $query_result ||
	$query_result->numrows == 0) {
	DBQueryWarn("unlock tables");
	return -1
    }
    DBQueryWarn("unlock tables");
    $self->{'LOCKED'} = time();
    $self->{'LOCKER_PID'} = $PID;
    return 0;
}

sub Unlock($)
{
    my ($self) = @_;
    my $idx    = $self->idx();

    return -1
	if (! DBQueryWarn("update apt_datasets set locked=null,locker_pid=0 " .
			  "where idx=$idx"));
    
    $self->{'LOCKED'} = 0;
    $self->{'LOCKER_PID'} = 0;
    return 0;
}

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

    return 1
	if ($self->{'LOCKED'} &&
	    $self->{'LOCKER_PID'} == $PID);
    
    return 0;
}

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

    return $self->Lock(1);
}

#
# Locate Geni objects
#
sub GetGeniUser($)
{
    my ($self) = @_;
    require GeniUser;
    require User;

    #
    # Only local users can do this, so do a direct local lookup.
    #
    my $user = User->Lookup($self->creator_idx());
    return undef
	if (!defined($user));
    
    return GeniUser->CreateFromLocal($user);
}

sub GetGeniAuthority($)
{
    my ($self) = @_;
    require GeniAuthority;

    return APT_Geni::GetAuthority($self->aggregate_urn());
}

#
# Warn creator that the experiment is going to expire. This is hooked
# in from the sa_daemon, so we can send a message that is less geni like
# and more APT/Cloud.
#
sub WarnExpiring($$)
{
    my ($self, $when) = @_;
    return 0;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
#
# Create a certificate we can use for the credential. We want this
# certificate to be a subauthority certificate so that the backend puts
# the dataset in an SA subgroup.
#
sub CreateCertificate($)
{
    my ($self) = @_;
    my $pid  = $self->pid();
    my $id   = $self->dataset_id();
    my $urn  = GeniHRN::Generate("$OURDOMAIN:$pid", "dataset", $id);

    # Kill stale certificate.
    my $certificate = GeniCertificate->Lookup($urn);
    $certificate->Delete()
	if (defined($certificate));
    
    $certificate = GeniCertificate->Create({"urn"   => $urn,
					    "email" => "$TBOPS",
					    "hrn"   => "$OURDOMAIN.$pid.$id"});
    return -1
	if (!defined($certificate));

    # We want to save until we delete the dataset.
    $certificate->Store() == 0
	or return -1;

    return 0;
}
sub GetCertificate($)
{
    my ($self) = @_;
    my $pid  = $self->pid();
    my $id   = $self->dataset_id();
    my $urn  = GeniHRN::Generate("$OURDOMAIN:$pid", "dataset", $id);

    return GeniCertificate->Lookup($urn);
}

454 455 456 457 458 459 460 461 462
#
# Create a dataset on the remote aggregate.
#
sub CreateDataset($)
{
    my ($self) = @_;
    my $authority = $self->GetGeniAuthority();
    my $geniuser  = $self->GetGeniUser();
    my $context   = APT_Geni::GeniContext();
Leigh B Stoller's avatar
Leigh B Stoller committed
463
    my $cert      = $self->GetCertificate();
464
    return undef
Leigh B Stoller's avatar
Leigh B Stoller committed
465 466 467 468 469
	if (! (defined($geniuser) && defined($authority) &&
	       defined($context) && defined($cert)));
    
    my ($credential, $speaksfor_credential) =
	APT_Geni::GenCredentials($cert, $geniuser, ["blockstores"]);
470 471
    return undef
	if (! (defined($speaksfor_credential) &&
Leigh B Stoller's avatar
Leigh B Stoller committed
472
	       defined($credential)));
473 474 475 476 477

    my $args = {
	"size"        => $self->size(),
	"name"        => $self->dataset_id(),
	"type"        => $self->type(),
478 479
	"read_access" => $self->read_access(),
	"write_access"=> $self->write_access(),
Leigh B Stoller's avatar
Leigh B Stoller committed
480
	"credentials" => [$credential->asString(),
481 482 483 484
			  $speaksfor_credential->asString()],
    };
    $args->{"fstype"} = $self->fstype()
	if ($self->fstype() ne "none");
Leigh B Stoller's avatar
Leigh B Stoller committed
485
    $args->{"expires"} = emutil::TBDateStringGMT($self->expires())
486 487 488
	if (defined($self->expires()));

    my $cmurl = $authority->url();
489
    $cmurl =~ s/protogeni/protogeni\/stoller/ if ($usemydevtree);
490 491 492 493 494 495 496 497 498 499 500 501 502

    return Genixmlrpc::CallMethod($cmurl, $context, "CreateDataset", $args);
}

#
# Delete a dataset on the remote aggregate.
#
sub DeleteDataset($)
{
    my ($self) = @_;
    my $authority = $self->GetGeniAuthority();
    my $geniuser  = $self->GetGeniUser();
    my $context   = APT_Geni::GeniContext();
Leigh B Stoller's avatar
Leigh B Stoller committed
503
    my $cert      = $self->GetCertificate();
504
    return undef
Leigh B Stoller's avatar
Leigh B Stoller committed
505 506 507 508 509
	if (! (defined($geniuser) && defined($authority) &&
	       defined($context) && defined($cert)));
    
    my ($credential, $speaksfor_credential) =
	APT_Geni::GenCredentials($cert, $geniuser, ["blockstores"]);
510 511
    return undef
	if (! (defined($speaksfor_credential) &&
Leigh B Stoller's avatar
Leigh B Stoller committed
512
	       defined($credential)));
513 514 515

    my $args = {
	"name"        => $self->dataset_id(),
Leigh B Stoller's avatar
Leigh B Stoller committed
516
	"credentials" => [$credential->asString(),
517 518 519
			  $speaksfor_credential->asString()],
    };
    my $cmurl = $authority->url();
520
    $cmurl =~ s/protogeni/protogeni\/stoller/ if ($usemydevtree);
521 522 523 524

    return Genixmlrpc::CallMethod($cmurl, $context, "DeleteDataset", $args);
}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
#
# Apply some updates to the dataset on server.
#
sub ModifyDataset($)
{
    my ($self) = @_;
    my $authority = $self->GetGeniAuthority();
    my $geniuser  = $self->GetGeniUser();
    my $context   = APT_Geni::GeniContext();
    my $cert      = $self->GetCertificate();
    return undef
	if (! (defined($geniuser) && defined($authority) &&
	       defined($context) && defined($cert)));
    
    my ($credential, $speaksfor_credential) =
	APT_Geni::GenCredentials($cert, $geniuser, ["blockstores"]);
    return undef
	if (! (defined($speaksfor_credential) &&
	       defined($credential)));

    my $args = {
	"name"        => $self->dataset_id(),
547 548
	"read_access" => $self->read_access(),
	"write_access"=> $self->write_access(),
549 550 551 552
	"credentials" => [$credential->asString(),
			  $speaksfor_credential->asString()],
    };
    my $cmurl = $authority->url();
553
    $cmurl =~ s/protogeni/protogeni\/stoller/ if ($usemydevtree);
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

    return Genixmlrpc::CallMethod($cmurl, $context, "ModifyDataset", $args);
}

#
# Request single extension.
#
sub ExtendDataset($)
{
    my ($self) = @_;
    my $authority = $self->GetGeniAuthority();
    my $geniuser  = $self->GetGeniUser();
    my $context   = APT_Geni::GeniContext();
    my $cert      = $self->GetCertificate();
    return undef
	if (! (defined($geniuser) && defined($authority) &&
	       defined($context) && defined($cert)));
    
    my ($credential, $speaksfor_credential) =
	APT_Geni::GenCredentials($cert, $geniuser, ["blockstores"]);
    return undef
	if (! (defined($speaksfor_credential) &&
	       defined($credential)));

    my $args = {
	"name"        => $self->dataset_id(),
	"credentials" => [$credential->asString(),
			  $speaksfor_credential->asString()],
	"extend"      => 1,
    };
    my $cmurl = $authority->url();
585
    $cmurl =~ s/protogeni/protogeni\/stoller/ if ($usemydevtree);
586 587 588 589

    return Genixmlrpc::CallMethod($cmurl, $context, "ModifyDataset", $args);
}

590 591 592 593 594 595 596 597 598
#
# Refresh our metadata.
#
sub DescribeDataset($)
{
    my ($self) = @_;
    my $authority = $self->GetGeniAuthority();
    my $geniuser  = $self->GetGeniUser();
    my $context   = APT_Geni::GeniContext();
Leigh B Stoller's avatar
Leigh B Stoller committed
599
    my $cert      = $self->GetCertificate();
600
    return undef
Leigh B Stoller's avatar
Leigh B Stoller committed
601 602 603 604 605
	if (! (defined($geniuser) && defined($authority) &&
	       defined($context) && defined($cert)));
    
    my ($credential, $speaksfor_credential) =
	APT_Geni::GenCredentials($cert, $geniuser, ["blockstores"]);
606 607
    return undef
	if (! (defined($speaksfor_credential) &&
Leigh B Stoller's avatar
Leigh B Stoller committed
608
	       defined($credential)));
609 610 611

    my $args = {
	"name"        => $self->dataset_id(),
Leigh B Stoller's avatar
Leigh B Stoller committed
612
	"credentials" => [$credential->asString(),
613 614 615
			  $speaksfor_credential->asString()],
    };
    my $cmurl = $authority->url();
616
    $cmurl =~ s/protogeni/protogeni\/stoller/ if ($usemydevtree);
617 618 619 620 621 622

    return Genixmlrpc::CallMethod($cmurl, $context, "DescribeDataset", $args);
}

# _Always_ make sure that this 1 is at the end of the file...
1;