manage_dataset.in 35.4 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2019 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
# 
# {{{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/>.
# 
# }}}
#
use English;
use strict;
use Getopt::Std;
use Data::Dumper;
use POSIX ":sys_wait_h";
use POSIX qw(setsid close);
use Date::Parse;

#
# Back-end script to manage APT profiles.
#
sub usage()
{
    print STDERR "Usage: manage_dataset [options --] create ...\n";
    print STDERR "Usage: manage_dataset [options --] delete ...\n";
    print STDERR "Usage: manage_dataset [options --] refresh ...\n";
40 41
    print STDERR "Usage: manage_dataset [options --] modify ...\n";
    print STDERR "Usage: manage_dataset [options --] extend ...\n";
42
    print STDERR "Usage: manage_dataset [options --] approve ...\n";
43
    print STDERR "Usage: manage_dataset [options --] snapshot ...\n";
44
    print STDERR "Usage: manage_dataset [options --] getcredential ...\n";
45 46 47 48 49 50
    exit(-1);
}
my $optlist     = "dt:";
my $debug       = 0;
my $webtask_id;
my $webtask;
51 52
my $this_user;
my $geniuser;
53 54 55 56 57 58

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
59
my $SACERT      = "$TB/etc/genisa.pem";
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use libtestbed;
use EmulabConstants;
use emdb;
use emutil;
80
use libEmulab;
81 82 83
use User;
use Project;
use APT_Dataset;
84
use APT_Instance;
85
use APT_Geni;
86 87 88
use WebTask;
use Blockstore;
use GeniResponse;
89
use Genixmlrpc;
90
use GeniXML;
91
use GeniUser;
92 93 94 95
use GeniAuthority;
use GeniCertificate;
use GeniCredential;
use GeniImage;
96 97 98

# Protos
sub fatal($);
99
sub UserError($;$);
100 101 102
sub DoCreate();
sub DoDelete();
sub DoRefresh();
103
sub DoRefreshInternal($);
104
sub DoGetCredential();
105 106
sub DoModify();
sub DoExtend();
107
sub DoApprove();
108
sub DoSnapshot();
109
sub DoSnapShotInternal($$$$$);
110
sub PollDatasetStatus($$$);
111
sub DoImageTrackerStuff($$$$$);
112
sub ExitWithError($);
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (grep {$_ eq "--"} @ARGV &&
    ! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"t"})) {
    $webtask_id = $options{"t"};
128
    $webtask = WebTask->Lookup($webtask_id);
129
    if (!defined($webtask)) {
130
	fatal("Could not get webtask object");
131 132
    }
    $webtask->AutoStore(1);
133
}
134 135 136 137
# In general, these calls should not take a lot of time, so reduce the
# RPC timeout value. We will adjust them below if needed.
Genixmlrpc->SetTimeout(30);

138 139 140
if (@ARGV < 1) {
    usage();
}
141
my $action = shift(@ARGV);
142

143 144 145 146
if (getpwuid($UID) eq "nobody") {
    $this_user = User->ImpliedUser();
}
else  {
147 148
    $this_user = User->ThisUser();
}
149 150 151 152 153
# No guests allowed.
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
$geniuser = GeniUser->CreateFromLocal($this_user);
154 155 156 157 158 159 160 161 162 163

if ($action eq "create") {
    exit(DoCreate());
}
elsif ($action eq "delete") {
    exit(DoDelete());
}
elsif ($action eq "refresh") {
    exit(DoRefresh());
}
164 165 166 167 168 169
elsif ($action eq "modify") {
    exit(DoModify());
}
elsif ($action eq "extend") {
    exit(DoExtend());
}
170 171 172
elsif ($action eq "snapshot") {
    exit(DoSnapshot());
}
173 174 175
elsif ($action eq "getcredential") {
    exit(DoGetCredential());
}
176 177 178
elsif ($action eq "approve") {
    exit(DoApprove());
}
179 180 181 182 183 184 185 186 187 188 189 190
else {
    usage();
}
exit(1);

#
# 
#
sub DoCreate()
{
    my $usage = sub {
	print STDERR "Usage: manage_dataset create ".
191
	    "[-t type] [-f fstype] [-e expiration] ".
192
	    "[-R global|project] [-W creator|project] ".
193
	    "-a am_urn -s size pid/name\n";
194 195
	exit(-1);
    };
196
    my $aggregate_urn;
197 198 199
    my $errmsg;
    my $pid;
    my $expires;
200
    my $size = 0;
201 202
    my $type = "stdataset";
    my $fstype;
203 204
    my $read_access;
    my $write_access;
205
    # imdataset snapshot info.
206
    my ($instance,$aggregate,$nodeid,$bsname);
207
    
208
    my $optlist = "ds:t:e:f:w:p:R:W:I:i:a:";
209 210 211 212 213 214 215 216 217 218
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"d"})) {
	$debug = 1;
    }
    if (defined($options{"t"})) {
	$type = $options{"t"};
	&$usage()
219 220
	    if (! ($type eq "stdataset" || $type eq "ltdataset" ||
		   $type eq "imdataset"));
221
    }
222 223 224 225 226 227
    if (defined($options{"a"})) {
	$aggregate_urn = $options{"a"};
    }
    elsif ($type ne "imdataset") {
	&$usage();
    }
228
    if ($type eq "imdataset") {
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	if (!exists($options{"i"})) {
	    print STDERR "Must provide -i opton for imdatasets\n";
	    &$usage();
	}
	if (!exists($options{"I"})) {
	    print STDERR "Must provide -I opton for imdatasets\n";
	    &$usage();
	}
	$instance = APT_Instance->Lookup($options{"i"});
	if (!defined($instance)) {
	    fatal("Instance does not exist!");
	}
	($nodeid,$bsname) = split(",", $options{"I"});
	if (! (defined($nodeid) && defined($bsname))) {
	    print STDERR "Improper -I opton for imdatasets\n";
244 245
	    &$usage();
	}
246 247 248 249
	$aggregate = $instance->FindAggregateByNodeId($nodeid);
	if (!defined($aggregate)) {
	    fatal("Could not find aggregate for $nodeid");
	}
250
	$aggregate_urn = $aggregate->aggregate_urn();
251 252 253 254 255 256 257 258 259

	#
	# Not allowed to create a dataset on aggregates that are marked as
	# nolocalimages. Maybe add "relocation" later, but for now just
	# throw a user error.
	#
	if ($aggregate->nolocalimages()) {
	    UserError("Not allowed to create a new dataset on this cluster");
	}
260
    }
261
    else {
262
	if (!APT_Dataset::ValidBlockstoreBackend($aggregate_urn)) {	
263 264 265
	    fatal("Invalid cluster selection");
	}
    }
266 267 268 269 270 271 272 273 274 275 276 277
    if (defined($options{"f"})) {
	$fstype = $options{"f"};
	&$usage()
	    if ($fstype !~ /^(ext2|ext3|ext4|ufs|ufs2)$/);
    }
    if (defined($options{"R"})) {
	$read_access = $options{"R"};
	&$usage()
	    if ($read_access !~ /^(global|project)$/);
    }
    if (defined($options{"W"})) {
	$write_access = $options{"W"};
Leigh Stoller's avatar
Leigh Stoller committed
278
	&$usage()
279
	    if ($write_access !~ /^(creator|project)$/);
Leigh Stoller's avatar
Leigh Stoller committed
280
    }
281 282 283 284 285
    if (defined($options{"s"})) {
	if ($options{"s"} =~ /^(\d+)$/) {
	    $size = $1;
	}
	elsif ($options{"s"} =~ /^(\d+)(\w+)$/) {
Leigh Stoller's avatar
Leigh Stoller committed
286 287
	    # Converter wants upper case.
	    $size = Blockstore::ConvertToMebi(uc($options{"s"}));
288 289 290
	    if ($size < 0) {
		fatal("Could not parse size.");
	    }
291 292
	    if ($size <= 4.5) {
		UserError("Size too small; minimum is 5MB");
293
	    }
294 295 296 297 298 299 300 301 302 303 304 305
	}
	else {
	    &$usage();
	}
    }
    if (defined($options{"e"})) {
	$expires = str2time($options{"e"});
	if (!defined($expires)) {
	    fatal("Could not parse expiration date.");
	}
	$expires = $options{"e"};
    }
306
    
307
    &$usage()
308
	if (@ARGV != 1 || !defined($aggregate_urn) ||
309
	    ($type ne "imdataset" && !defined($size)) ||
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
	    ($type eq "stdataset" && !defined($expires)));
    my $name = shift(@ARGV);

    if ($name =~ /^([-\w]+)\/([-\w]+)$/) {
	$pid  = $1;
	$name = $2;
    }
    else {
	fatal("Dataset name $name not in the form <pid>/<name>.");
    }
    my $project = Project->Lookup($pid);
    if (!defined($project)) {
	fatal("No such project");
    }
    if (!$project->AccessCheck($this_user, TB_PROJECT_CREATELEASE())) {
325
	UserError("Not enough permission to create datasets in project $pid");
326 327 328 329 330
    }
    &$usage()
	if ($type eq "stdataset" && !defined($expires));

    if (APT_Dataset->Lookup("$pid/$name")) {
Leigh Stoller's avatar
Leigh Stoller committed
331
	UserError("Dataset already exists!");
332 333
    }

334 335 336
    # Check for expired certs and speaksfor.
    if (my $retval = APT_Geni::VerifyCredentials($geniuser, \$errmsg)) {
	if ($retval) {
337
	    ($retval < 0 ? fatal($errmsg) : UserError($errmsg));
338 339 340
	}
    }

341 342 343 344
    my $blob = {
	"dataset_id"     => $name,
	"pid"            => $project->pid(),
	"pid_idx"        => $project->pid_idx,
345 346
	"gid"            => $project->pid(),
	"gid_idx"        => $project->pid_idx,
347 348 349 350 351 352 353 354
	"creator_uid"    => $this_user->uid(),
	"creator_idx"    => $this_user->uid_idx(),
	"aggregate_urn"  => $aggregate_urn,
	"type"           => $type,
	"size"           => $size,
    };
    $blob->{"fstype"} = $fstype
	if (defined($fstype));
Leigh Stoller's avatar
Leigh Stoller committed
355
    $blob->{"expires"} = TBDateStringLocal($expires)
356
	if (defined($expires));
357 358 359 360
    $blob->{"read_access"} = $read_access
	if (defined($read_access));
    $blob->{"write_access"} = $write_access
	if (defined($write_access));
361

362 363 364 365 366 367 368 369 370 371 372 373
    #
    # Always create a webtask for tracking image or allocation status.
    # This is an internal webtask, not the one used on the command line.
    #
    my $dwebtask = WebTask->Create();
    if (!defined($dwebtask)) {
	$errmsg = "Could not create webtask object";
	goto failed;
    }
    $dwebtask->AutoStore(1);
    $blob->{"webtask_id"} = $dwebtask->task_id();

374 375
    my $dataset = APT_Dataset->Create($blob);
    if (!defined($dataset)) {
376
	$dwebtask->Delete();
377
	fatal("Error creating dataset object");
378
    }
379
    
380 381 382 383 384 385 386 387
    # new dataset is returned locked. If we have instance, try to lock
    # that now, else its a failure.
    if ($type eq "imdataset" && defined($instance)) {
	if ($instance->Lock()) {
	    $errmsg = "Instance is busy, cannot snapshot data";
	    goto failed;
	}
    }
388 389 390 391 392 393
    #
    # Ask the aggregate to create the dataset. 
    #
    my $response = $dataset->CreateDataset();
    if ($response->code() != GENIRESPONSE_SUCCESS) {
	$errmsg = "CreateDataset failed: ". $response->output() . "\n";
394 395
	$instance->Unlock()
	    if (defined($instance));
396 397 398
	goto failed;
    }
    $blob = $response->value();
399 400
    $dataset->Update({"remote_uuid" => $blob->{"uuid"},
		      "remote_urn"  => $blob->{"urn"}});
401 402 403
    if (exists($blob->{'url'}) && $blob->{'url'} ne "") {
	$dataset->Update({"remote_url" => $blob->{"url"}});
    }
404

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    if ($type ne "imdataset") {
	#
	# Okay, this is silly; there is no distinct state for resource
	# allocation. The other side now tells us expicitly that the
	# dataset (lease) was approved or not. If not approved there is
	# no reason to continue, we just want to tell the user in the
	# web UI an send email to local tbops.
	#
	# If approved, then it is probably busy and we need to wait for
	# it to finish.
	#
	if (! $blob->{'approved'}) {
	    $dataset->Update({"state" => "unapproved"});
	    if (defined($webtask)) {
		$webtask->needapproval(1);
		$webtask->unapproved_reason($blob->{'unapproved_reason'})
		    if (exists($blob->{'unapproved_reason'}));
	    }
	    $dataset->Unlock();
	    return 0;
	}
	if ($blob->{"busy"}) {
	    # Will poll for completion below.
	    $dataset->Update({"state" => "busy"});
	}
	else {
	    # This should no longer happen.
	    $dataset->Update({"state" => $blob->{"state"}});
	    $dataset->Unlock();
	    return 0;
	}
436 437 438
    }
    else {
	$dataset->Update({"state" => $blob->{"state"}});
439 440
	# Not doing a snapshot so just exit. Not sure this actually happens.
	if (!defined($instance)) {
441 442 443
	    $dataset->Unlock();
	    return 0;
	}
444
    }
445

446 447 448
    #
    # Handoff to snapshot if an imdataset.
    #
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    if ($type eq "imdataset") {
	my $errcode = DoSnapShotInternal($dataset, $aggregate,
					 $bsname, $nodeid, \$errmsg);
	if ($errcode) {
	    $response = $dataset->DeleteDataset();
	    if ($response->code() == GENIRESPONSE_SUCCESS ||
		$response->code() == GENIRESPONSE_SEARCHFAILED) {
		$instance->Unlock();
		$dataset->Delete();
	    }
	    else {
		# We want to keep the local dataset record around
		# since we could not delete it remotely.
		$instance->Unlock();
	    }
	    if ($errcode < 0) {
		# This will set the webtask, see below.
		fatal($errmsg);
	    }
	    else {
		UserError($errmsg);
	    }
471
	}
472
    }
473
    if (PollDatasetStatus($dataset, $aggregate, \$errmsg)) {
474 475
	# Exit and let child poll
	exit(0);
476 477
    }
    $dataset->Unlock();
478
    $instance->Unlock() if (defined($instance));
479 480 481
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
482 483 484 485 486 487 488 489 490 491 492 493 494 495
    return 0;

  failed:
    $dataset->Delete()
	if (defined($dataset));
    # This will set the webtask, see below.
    fatal($errmsg);
}

#
# Delete
#
sub DoDelete()
{
496
    my $errmsg  = "Could not delete dataset";
497 498 499 500 501 502 503 504 505 506
    
    if (@ARGV != 1) {
	fatal("usage: $0 delete pid/name");
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    if ($dataset->Lock()) {
507
	UserError("dataset is busy, cannot lock it");
508
    }
509 510 511 512 513
    # Check if the aggregate is online and reachable. 
    my $aggregate = $dataset->GetAggregate();
    if ($aggregate->CheckStatus(\$errmsg)) {
	$dataset->Unlock();
	UserError($errmsg);
514
    }
515 516 517
    my $response = $dataset->DeleteDataset();
    if (GeniResponse::IsError($response) &&
	$response->code() != GENIRESPONSE_SEARCHFAILED()) {
518
	$dataset->Unlock();
519
	ExitWithError($response);
520
    }
521
    $dataset->Delete();
522 523 524
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
525 526 527 528 529 530 531 532 533
    return 0;
}

#
# Refresh
#
sub DoRefresh()
{
    my $errmsg;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    my $errcode;

    my $usage = sub {
	print STDERR "Usage: manage_dataset refresh [-p] uuid\n";
	exit(-1);
    };
    my $optlist = "p";
    my $poll    = 0;
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"p"})) {
	$poll = 1;
    }
549
    if (@ARGV != 1) {
550
	&$usage();
551 552 553 554 555 556
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
557 558 559 560 561
    # Check if the aggregate is online and reachable. 
    my $aggregate = $dataset->GetAggregate();
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
562
    if ($dataset->Lock()) {
563
	UserError("dataset is busy, cannot lock it");
564
    }
565 566 567 568 569 570 571
    if ($poll) {
	if (PollDatasetStatus($dataset, $dataset->GetAggregate(), \$errmsg)) {
	    # Parent exits;
	    return 0;
	}
    }
    else {
572 573 574 575 576
	my $response = DoRefreshInternal($dataset);
	if (GeniResponse::IsError($response)) {
	    $dataset->Unlock();
	    ExitWithError($response);
	}
577
    }
578
    $dataset->Unlock();
579 580 581
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
582 583 584
    return 0;
}

585
sub DoRefreshInternal($)
586
{
587
    my ($dataset) = @_;
588 589
    
    my $response = $dataset->DescribeDataset();
590 591
    if (GeniResponse::IsError($response)) {
	return $response;
592 593
    }
    my $blob = $response->value();
594
    print Dumper($blob);
595
    
Leigh Stoller's avatar
Leigh Stoller committed
596 597
    $dataset->Update({"expires"   => TBDateStringLocal($blob->{"expires"})})
	if ($blob->{"expires"} && $blob->{"expires"} ne "");
598
    $dataset->Update({"updated"  => TBDateStringLocal($blob->{"updated"})})
599
	if ($blob->{"updated"});
600 601
    $dataset->Update({"last_used" => TBDateStringLocal($blob->{"lastused"})})
	if ($blob->{"lastused"} && $blob->{"lastused"} ne "");
602 603 604

    if ($blob->{"busy"}) {
	$dataset->Update({"state" => "busy"});
605
	if ($dataset->type() eq "imdataset") {
606 607 608 609 610
	    $dataset->webtask()->image_size($blob->{'image_size'}) 	
		if (exists($blob->{'image_size'}));
	    $dataset->webtask()->image_status($blob->{'image_status'})
		if (exists($blob->{'image_status'}));
	    $dataset->webtask()->Store();
611
	}
612 613 614
    }
    else {
	$dataset->Update({"state" => $blob->{"state"}});
615 616
	if ($dataset->type() eq "imdataset") {
	    $dataset->Update({"size" => $blob->{"size"}});
617 618 619 620 621
	    $dataset->webtask()->image_size($blob->{'image_size'}) 	
		if (exists($blob->{'image_size'}));
	    $dataset->webtask()->image_status($blob->{'image_status'})
		if (exists($blob->{'image_status'}));
	    $dataset->webtask()->Store();
622
	}
623
    }
624 625 626
    return 0;
}

627 628 629 630 631 632 633 634 635
#
# Modify
#
sub DoModify()
{
    my $errmsg;
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset modify ".
636
	    "[-R global|project] [-W creator|project] pid/name\n";
637 638
	exit(-1);
    };
639
    my $optlist = "R:W:";
640 641 642 643 644 645 646 647 648 649 650 651
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (@ARGV != 1) {
	&$usage();
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
652 653 654
    my $blob = {};
    if (defined($options{"R"})) {
	my $read_access = $options{"R"};
655
	&$usage()
656 657
	    if ($read_access !~ /^(global|project)$/);
	$blob->{'read_access'} = $read_access;
658
    }
659 660 661 662 663
    if (defined($options{"W"})) {
	my $write_access = $options{"W"};
	&$usage()
	    if ($write_access !~ /^(creator|project)$/);
	$blob->{'write_access'} = $write_access;
664
    }
665 666 667 668 669 670
    # Check if the aggregate is online and reachable. 
    my $aggregate = $dataset->GetAggregate();
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
    
671
    if ($dataset->Lock()) {
672
	UserError("dataset is busy, cannot lock it");
673
    }
674 675
    if (keys(%$blob)) {
	if ($dataset->Update($blob)) {
676
	    $errmsg = "Could not update privacy settings!";
677 678 679
	    $dataset->Unlock();
	    # This will set the webtask, see below.
	    fatal($errmsg);
680 681 682
	}
    }
    my $response = $dataset->ModifyDataset();
683 684 685
    if (GeniResponse::IsError($response)) {
	$dataset->Unlock();
	ExitWithError($response);
686
    }
687
    $blob = $response->value();
688 689 690
    if ($dataset->type() ne "imdataset") {
	$dataset->Update({"expires" => TBDateStringLocal($blob->{"expires"})});
    }
691
    $dataset->Unlock();
692 693 694
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    return 0;
}

#
# Extend
#
sub DoExtend()
{
    my $errmsg;
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset extend pid/name\n";
	exit(-1);
    };
    if (@ARGV != 1) {
	&$usage();
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
717 718 719 720 721
    # Check if the aggregate is online and reachable. 
    my $aggregate = $dataset->GetAggregate();
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
722
    if ($dataset->Lock()) {
723
	UserError("dataset is busy, cannot lock it");
724 725
    }
    my $response = $dataset->ExtendDataset();
726 727 728
    if (GeniResponse::IsError($response)) {
	$dataset->Unlock();
	ExitWithError($response);
729 730 731
    }
    my $blob = $response->value();
    $dataset->Update({"expires" => TBDateStringLocal($blob->{"expires"})});
732 733 734
    if (exists($blob->{'state'})) {
	$dataset->Update({"state" => $blob->{'state'}});
    }
735
    $dataset->Unlock();
736 737 738
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
739 740 741
    return 0;
}

742 743 744 745 746 747
#
# Snapshot an image backed dataset
#
sub DoSnapshot()
{
    my $errmsg;
748
    my $errcode = -1;
749
    my ($copyback_uuid, $sha1hash);
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset snapshot ".
	    "-i instance -b bsname pid/name nodeid\n";
	exit(-1);
    };
    my $optlist = "b:i:";
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    &$usage()
	if (! (@ARGV == 2 && exists($options{"b"}) && exists($options{"i"})));
    
    my $bsname  = $options{"b"};
    my $token   = shift(@ARGV);
    my $nodeid  = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    if ($dataset->type() ne "imdataset") {
772
	fatal("Only image backed datasets supported");
773 774 775
    }
    my $instance = APT_Instance->Lookup($options{"i"});
    if (!defined($instance)) {
776 777
	fatal("No such instance");
    }
778 779 780 781
    my $aggregate = $instance->FindAggregateByNodeId($nodeid);
    if (!defined($aggregate)) {
	fatal("Could not find aggregate for $nodeid");
    }
782 783 784 785
    # Check if the aggregate is online and reachable. 
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
786
    if (GetSiteVar("protogeni/use_imagetracker")) {
787 788
	if (DoImageTrackerStuff($dataset, $aggregate,
				\$copyback_uuid,\$sha1hash,\$errmsg)) {
789 790 791
	    fatal("Could not get info from image tracker");
	}
    }
792
    if ($dataset->Lock()) {
793
	UserError("dataset is busy, cannot lock it");
794 795
    }
    if ($instance->Lock()) {
796
	$dataset->Unlock();
797
	UserError("instance is busy, cannot lock it");
798
    }
799 800 801 802 803 804 805
    # Clear the webtask, starting a new snapshot.
    $dataset->webtask()->Reset();
    # These three are convenience for the web server to give feedback.
    $dataset->webtask()->aggregate_urn($aggregate->aggregate_urn());
    $dataset->webtask()->client_id($nodeid);
    $dataset->webtask()->instance($instance->uuid());
    
806 807
    if (defined($copyback_uuid)) {
	# Tell the imaging modal.
808
	$dataset->webtask()->copyback_uuid($copyback_uuid);
809 810 811 812 813
	# For polling below.
	$dataset->_copyback_uuid($copyback_uuid);
	$dataset->_sha1hash("$sha1hash");
	$dataset->_copying(0);
    }
814 815
    $dataset->webtask()->Store();
    $dataset->webtask()->AutoStore(1);
816 817 818 819 820 821

    $errcode = DoSnapShotInternal($dataset, $aggregate,
				  $bsname, $nodeid, \$errmsg);
    goto failed
	if ($errcode);

822
    if (PollDatasetStatus($dataset, $aggregate, \$errmsg)) {
823 824 825
	# Exit and let child poll
	exit(0);
    }
826 827 828 829 830
    $instance->Unlock();
    $dataset->Unlock();
    return 0;
    
  failed:
831
    $instance->Unlock();
832
    $dataset->Unlock();
833 834 835 836 837 838 839
    if ($errcode < 0) {
	# This will set the webtask, see below.
	fatal($errmsg);
    }
    else {
	UserError($errmsg);
    }
840 841 842 843
}

sub DoSnapShotInternal($$$$$)
{
844
    my ($dataset, $aggregate, $bsname, $nodeid, $perrmsg) = @_;
845 846
    my $errmsg;
    
847
    my $manifest = GeniXML::Parse($aggregate->manifest());
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    if (! defined($manifest)) {
	$errmsg = "Could not parse manifest";
	goto failed;
    }
    my $sliver_urn;
    my @nodes = GeniXML::FindNodes("n:node", $manifest)->get_nodelist();
    foreach my $node (@nodes) {
	my $client_id = GeniXML::GetVirtualId($node);
	if ($nodeid eq $client_id) {
	    $sliver_urn = GeniXML::GetSliverId($node);
	    #
	    # But check that the bsname is on this node.
	    #
	    my $found = 0;
	    foreach my $blockref
		(GeniXML::FindNodesNS("n:blockstore", $node,
				      $GeniXML::EMULAB_NS)->get_nodelist()) {
		    my $name = GeniXML::GetText("name", $blockref);
		    if ($name eq $bsname) {
			$found = 1;
			last;
		    }
	    }
	    if (!$found) {
		$errmsg = "No such blockstore $bsname on node $nodeid";
		goto failed;
	    }
	    last;
	}
    }
    if (!defined($sliver_urn)) {
	$errmsg = "Could not find node '$nodeid' in manifest";
	goto failed;
    }
882
    my $response = $aggregate->CreateImage($sliver_urn,
883
					   $dataset->dataset_id(), 0,
884
					   $dataset->_copyback_uuid(),
885
					   $bsname, 0, 0, 0);
886
    if ($response->code() != GENIRESPONSE_SUCCESS) {
887 888 889 890 891 892 893 894 895
	$$perrmsg = $response->output();
	if ($response->code() == GENIRESPONSE_REFUSED ||
	    $response->code() == GENIRESPONSE_SEARCHFAILED ||
	    $response->code() == GENIRESPONSE_SERVER_UNAVAILABLE ||
	    $response->code() == GENIRESPONSE_NETWORK_ERROR ||
	    $response->code() == GENIRESPONSE_BUSY) {
	    return 1;
	}
	return -1;
896 897
    }
    $dataset->Update({"state" => "busy"});
898 899 900 901 902 903 904 905 906
    #
    # If we are taking the snapshot at a different cluster, we have
    # to poll that cluster via ImageInfo() instead of DescribeDataset().
    # We need the image urn to do that in the polling loop.
    #
    if ($aggregate->aggregate_urn() ne $dataset->aggregate_urn()) {
	my ($image_urn) = @{ $response->value() };	
	$dataset->_image_urn($image_urn);
    }
907
    return 0;
908

909
  failed:
910 911
    $$perrmsg = $errmsg;
    return -1;
912
}
913 914 915 916

#
# Poll for snapshot status.
#
917
sub PollDatasetStatus($$$)
918
{
919
    my ($dataset, $aggregate, $perrmsg) = @_;
920 921 922 923 924 925 926 927 928 929 930
    my $project = $dataset->GetProject();
    my $dname   = $dataset->dataset_id();
    my $logfile;

    #
    # If busy, then allocation is in progress. We leave it locked and
    # poll in the background for a while, hoping for it to eventually
    # stop being busy. Eventually might have to replace this, since
    # polling got any non-small length of time will lead to trouble.
    #
    if (! $debug) {
931
        $logfile = TBMakeLogname("polldataset");
932 933 934 935 936 937 938

	if (my $childpid = TBBackGround($logfile)) {
	    return $childpid;
	}
	# Let parent exit;
	sleep(2);
    }
939
    $dataset->webtask()->SetProcessID($PID);
940

941 942 943 944 945 946
    print "State: " . $dataset->state() . "\n";
    if (defined($dataset->_copyback_uuid())) {
	my $copyback_uuid = $dataset->_copyback_uuid();
	my $sha1hash = $dataset->_sha1hash();
	print "hash: $sha1hash, copyback_uuid: $copyback_uuid\n";
    }
947
    my $seconds  = 1200;
948
    my $interval = 10;
949 950 951
    
    while ($seconds > 0) {
	$seconds -= $interval;
952 953 954 955 956 957 958 959 960 961
	#
	# The second part of the test is to distingush between an
	# imdataset snapshot at its home aggregate, and an imdataset
	# taking place at another cluster and thus needing a copy
	# back. We use a different polling function for the later,
	# since there is no dataset to ask about, just an image that
	# is doing a snapshot. This needs more thought, its not a
	# great way to do this.
	#
	if ($dataset->type() =~ /^(lt|st)dataset$/ ||
962
	    $aggregate->aggregate_urn() eq $dataset->aggregate_urn()) {
963 964 965 966
	    my $response = DoRefreshInternal($dataset);
	    if (GeniResponse::IsError($response)) {
		my $errcode = $response->code();
		print STDERR $response->error() . "\n";
967 968 969 970 971 972 973 974 975 976 977 978
		if ($errcode == GENIRESPONSE_SEARCHFAILED) {
		    #
		    # The dataset is gone, so it failed allocation.
		    # This should not happen for an imdataset of course.
		    # Mark the dataset as failed, we do not know why
		    # though, the allocation is asynchronous, and the error
		    # went out in email. But we can tell the user in the
		    # web UI.
		    #
		    $dataset->Update({"state" => "failed"});
		    $dataset->webtask()->output("allocation failure");
		    $dataset->webtask()->Exited(GENIRESPONSE_SEARCHFAILED);
979
		    $perrmsg = $response->error();
980 981 982
		    last;
		}
		# Otherwise we keep trying. 
983 984 985 986 987 988 989 990 991 992
		sleep($interval);
		next;
	    }
	}
	else {
	    if (PollImageStatus($dataset, $aggregate, $perrmsg)) {
		print STDERR $$perrmsg;
		sleep($interval);
		next;
	    }
993 994
	}
	if ($dataset->state() eq "valid") {
995
	    print "Dataset is now valid\n";
996 997
	    $project->SendEmail($this_user->email(),
			"Your dataset is now ready to use",
998
			"Dataset '$dname' is now ready to use.\n",
999
				$project->LogsEmailAddress(), undef, $logfile);
1000
	    $dataset->webtask()->Exited(0);
1001 1002 1003 1004
	    last;
	}
	sleep($interval);
    }
1005
    unlink($logfile) if (defined($logfile));
1006 1007
    $dataset->webtask()->Exited(-1)
	if ($seconds <= 0);
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
    return 0;
}

#
# GetCredential
#
sub DoGetCredential()
{
    my $errmsg  = "Could not get credential for dataset";
    my ($authority, $certificate, $credential);
    
    my $optlist = "a:f";
    my %options = ();
    if (! getopts($optlist, \%options)) {
	usage();
    }
    if (defined($options{"a"})) {
	my $urn = GeniHRN->new($options{"a"});
	fatal("Not a valid authority URN")
	    if (!defined($urn));

	#
	# Load the cert to act as caller context in case we need to go
	# to the clearinghouse.
	#
	$certificate = GeniCertificate->LoadFromFile($SACERT);
	if (!defined($certificate)) {
	    fatal("Could not load certificate from $SACERT\n");
	}
	Genixmlrpc->SetContext(Genixmlrpc->Context($certificate));
	
	$authority = GeniAuthority->CreateFromRegistry($urn->id(), $urn);
	fatal("No such authority")
	    if (!defined($authority));
    }
    if (@ARGV != 1) {
	fatal("usage: $0 getcredential [-a authority] pid/name");
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
1051 1052 1053 1054 1055
    # Check if the aggregate is online and reachable. 
    my $aggregate = $dataset->GetAggregate();
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
1056
    if ($dataset->Lock()) {
1057
	UserError("dataset is busy, cannot lock it");
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    }
    #
    # If we have a stored unexpired credential, we can just use that.
    #
    if (!defined($options{"f"}) &&
	$dataset->credential_string() && $dataset->credential_string() ne "") {
	$credential =
	    GeniCredential->CreateFromSigned($dataset->credential_string());
	goto haveit
	    if (defined($credential) && !$credential->IsExpired());
    }
    my $response = $dataset->GetCredential();
1070
    if (GeniResponse::IsError($response)) {
1071
	$dataset->Unlock();
1072
	ExitWithError($response);
1073
    }
1074
    $credential = GeniCredential->CreateFromSigned($response->value());
1075 1076 1077 1078
    if (!defined($credential)) {
	$dataset->Unlock();
	fatal("Could not parse new credential")
    }
1079 1080 1081 1082 1083 1084 1085 1086 1087
    $dataset->Update({"credential_string" => $response->value()});
  haveit:
    if (defined($authority)) {
	my $delegated = $credential->Delegate($authority);
	$delegated->Sign($certificate);
	$credential = $delegated;
    }
    print $credential->asString();
    $dataset->Unlock();
1088 1089 1090
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
1091 1092 1093
    return 0;
}

1094
sub DoImageTrackerStuff($$$$$)
1095
{
1096 1097 1098
    my ($dataset, $aggregate, $puuid, $phash, $perrmsg) = @_;
    my $remote_urn = GeniHRN->new($dataset->remote_urn());
    my $aggregate_urn = GeniHRN->new($aggregate->aggregate_urn());
1099 1100
    my $errmsg;

1101 1102 1103 1104 1105 1106 1107
    #
    # If the dataset is being used on the cluster where it lives, then
    # there is no need for any of this.
    #
    return 0
	if (lc($remote_urn->domain()) eq lc($aggregate_urn->domain()));
    
1108 1109 1110 1111 1112 1113 1114 1115 1116
    Genixmlrpc->SetContext(APT_Geni::GeniContext());
    my $blob = GeniImage::GetImageData($remote_urn, \$errmsg);
    Genixmlrpc->SetContext(undef);
    
    if (!defined($blob)) {
	$$perrmsg = "Could not get info from the image server for ".
	    "$remote_urn:\n" . $errmsg;
	    return 1;
    }
1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    $$puuid = $blob->{'version_uuid'} if (defined($puuid));
    $$phash = $blob->{'sha1hash'} if (defined($phash));
    return 0;
}

sub PollImageStatus($$$)
{
    my ($dataset, $aggregate, $perrmsg) = @_;
    my $image_urn = $dataset->_image_urn();
    my $copyback_uuid = $dataset->_copyback_uuid();

    #
    # Once we hit the copyback phase, we have to ask the image tracker
    # for info to figure out when the copyback is done.
    #
    if ($dataset->_copying()) {
	my $sha1hash;
	
1136 1137
	if (DoImageTrackerStuff($dataset, $aggregate,
				undef, \$sha1hash, $perrmsg)) {
1138 1139 1140
	    print STDERR $perrmsg . "\n";
	    # Give up.
	    $dataset->Update({"state" => "valid"});
1141
	    $dataset->webtask()->image_status("ready");
1142 1143 1144 1145
	}
	if ("$sha1hash" eq $dataset->_sha1hash()) {
	    # Done!
	    $dataset->Update({"state" => "valid"});
1146
	    $dataset->webtask()->image_status("ready");
1147 1148 1149 1150
	}
	return 0;
    }
    else {
1151 1152
	print "Getting Image Info\n";
	
1153 1154
	my $response = $aggregate->ImageInfo($image_urn);
	if ($response->code() != GENIRESPONSE_SUCCESS &&
1155
	    $response->code() != GENIRESPONSE_NETWORK_ERROR &&
1156 1157 1158 1159 1160 1161 1162 1163
	    $response->code() != GENIRESPONSE_SERVER_UNAVAILABLE &&
	    $response->code() != GENIRESPONSE_BUSY) {
	    $$perrmsg = "Imageinfo failed: ". $response->output() . "\n";
	    return -1;
	}
	return 0
	    if ($response->code() == GENIRESPONSE_BUSY ||
		$response->code() == GENIRESPONSE_SERVER_UNAVAILABLE ||
1164
		$response->code() == GENIRESPONSE_NETWORK_ERROR);
1165 1166

	my $blob = $response->value();
1167
	print Dumper($response->value());
1168
    
1169
	$dataset->webtask()->image_size($blob->{'size'})
1170
	    if (exists($blob->{'size'}));
1171
	$dataset->webtask()->image_status($blob->{'status'})
1172 1173 1174
	    if (exists($blob->{'status'}));
	if ($blob->{'status'} eq "ready") {
	    if ($copyback_uuid) {
1175
		$dataset->webtask()->image_status("copying");
1176 1177 1178 1179 1180 1181 1182
		$dataset->_copying(1);
	    }
	    else {
		$dataset->Update({"state" => "valid"});
	    }
	}
    }
1183 1184 1185
    return 0;
}

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
#
# Approve
#
sub DoApprove()
{
    my $errmsg;
    my $logname;
    
    my $usage = sub {
	print STDERR "Usage: manage_dataset approve pid/name\n";
	exit(-1);
    };
    if (@ARGV != 1) {
	&$usage();
    }
    my $token   = shift(@ARGV);
    my $dataset = APT_Dataset->Lookup($token);
    if (!defined($dataset)) {
	fatal("No such dataset");
    }
    my $dname   = $dataset->dataset_id();

    if (!$this_user->IsAdmin()) {
	fatal("No permission to schedule reservation cancellation")
    }    
1211 1212 1213 1214 1215
    # Check if the aggregate is online and reachable. 
    my $aggregate = $dataset->GetAggregate();
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
1216
    if ($dataset->Lock()) {
1217
	UserError("dataset is busy, cannot lock it");
1218 1219 1220 1221 1222
    }
    my $project = $dataset->GetProject();
    my $creator = $dataset->GetCreator();
    
    my $response = $dataset->ApproveDataset();
Leigh Stoller's avatar
Leigh Stoller committed
1223
    if (GeniResponse::IsError($response)) {
1224 1225
	$dataset->Unlock();
	ExitWithError($response);
1226 1227 1228 1229
    }
    # No failure, change the state now so the web interface sees a change.
    $dataset->Update({"state" => "busy"});
    
1230 1231 1232
    # Clear the webtask, starting approval.
    $dataset->webtask()->Reset();
    
1233 1234 1235 1236 1237 1238 1239 1240 1241
    #
    # Now we want to poll for allocation completion so we can tell the
    # web interface when it is done (or failed). We know this when the
    # state changes to valid or failed.
    #
    if (! $debug) {
        $logname = TBMakeLogname("approvedataset");

	if (my $childpid = TBBackGround($logname)) {
1242 1243 1244
	    if (defined($webtask)) {
		$webtask->Exited(0);
	    }
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
	    exit(0);
	}
	# Let parent exit;
	sleep(2);
    }
    $dataset->webtask()->SetProcessID($PID);

    # Arbitrary max wait.
    my $seconds  = 1200;
    my $interval = 15;
    
    while ($seconds > 0) {
1257 1258 1259 1260
	my $response = DoRefreshInternal($dataset);
	if (GeniResponse::IsError($response)) {
	    my $errcode = $response->code();
	    print STDERR $response->error() . "\n";
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
	    if ($errcode == GENIRESPONSE_SEARCHFAILED) {
		#
		# The dataset is gone, so it failed allocation.
		# This should not happen for an imdataset of course.
		# Mark the dataset as failed, we do not know why
		# though, the allocation is asynchronous, and the error
		# went out in email. But we can tell the user in the
		# web UI.
		#
		$dataset->Update({"state" => "failed"});
		$dataset->webtask()->output("allocation failure");
		$dataset->webtask()->Exited(GENIRESPONSE_SEARCHFAILED);
		last;
	    }
	    # Otherwise we keep trying. 
	    goto again;
	}
	if ($dataset->state() eq "valid") {
	    $creator->SendEmail("Your dataset is now ready to use",
				"Dataset '$dname' is now ready to use.\n",
				$project->LogsEmailAddress(), $TBOPS);
	    $dataset->webtask()->Exited(0);
	    last;
	}
	if ($dataset->state() eq "failed") {
	    $creator->SendEmail("Your dataset failed to allocate!",
				"Dataset '$dname' could not be allocated!\n",
				$project->LogsEmailAddress(), $TBOPS);
	    $dataset->webtask()->Exited(0);
	}
      again:
	$seconds -= $interval;
	sleep($interval);
    }
    if ($seconds <= 0) {
	$creator->SendEmail("Your dataset timed out while allocating!",
			    "Dataset '$dname' timed out while allocating!\n",
			    $project->LogsEmailAddress(), $TBOPS);
	$dataset->Update({"state" => "failed"});
	$dataset->webtask()->Exited(-1);
    }
    unlink($logname) if (defined($logname));
    $dataset->Unlock();
    return 0;
}

1307 1308 1309 1310 1311 1312 1313 1314
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(-1);
    }
1315
    print STDERR "$mesg\n";
1316 1317 1318 1319
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

1320
sub UserError($;$)
1321
{
1322 1323
    my ($mesg, $code) = @_;
    $code = 1 if (!defined($code));
1324 1325 1326

    if (defined($webtask)) {
	$webtask->output($mesg);
1327
	$webtask->Exited($code);
1328 1329
    }
    print STDERR "$mesg\n";
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    exit(1);
}

#
# These are errors which the user might need to see. Some errors are
# exceptions though, and those we want to treat as internal errors.
#
sub ExitWithError($)
{
    my ($response) = @_;
    my $mesg = $response->error();
    my $code = $response->code();

    #
    # In general, these errors are to be expected by the caller.
    #
    if ($code == GENIRESPONSE_REFUSED ||
	$code == GENIRESPONSE_SEARCHFAILED ||
	$code == GENIRESPONSE_SERVER_UNAVAILABLE ||
	$code == GENIRESPONSE_NETWORK_ERROR ||
	$code == GENIRESPONSE_BUSY) {

	if (defined($webtask)) {
	    $webtask->output($mesg);
	    $webtask->Exited($code);
	}
	print STDERR "*** $0:\n".
1357 1358 1359 1360 1361 1362 1363 1364
	    "    $mesg\n";
	
	# Hmm, the apt_daemon cares about the response code, which is
	# fine except that some response codes are too big. Damn.
	if ($code > 255) {
	    $code = 1;
	}
	exit($code);
1365 1366
    }
    fatal($mesg);
1367 1368
}

1369 1370 1371 1372 1373 1374 1375 1376
sub escapeshellarg($)
{
    my ($str) = @_;

    $str =~ s/[^[:alnum:]]/\\$&/g;
    return $str;
}