manage_images.in 22.6 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
# 
# {{{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 Date::Parse;
use JSON;

#
# Back-end script to manage APT profiles.
#
sub usage()
{
36 37 38 39
    print STDERR "Usage: manage_images [options] list ...\n";
    print STDERR "Usage: manage_images [options] delete <urn> ...\n";
    print STDERR "Usage: manage_images [options] getcredential <urn>\n";
    print STDERR "Usage: manage_images [options] relocate ...\n";
40 41 42 43 44 45 46 47 48 49 50 51 52 53
    exit(-1);
}
my $optlist     = "dt:";
my $debug       = 0;
my $webtask_id;
my $webtask;

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $OURDOMAIN     = "@OURDOMAIN@";
my $MYURN         = "urn:publicid:IDN+${OURDOMAIN}+authority+cm";
54
my $CMCERT	  = "$TB/etc/genicm.pem";
55
my $MANAGEPROFILE = "$TB/bin/manage_profile";
56
my $IMPORTER      = "$TB/sbin/image_import";
57 58 59 60
my $MAINSITE      = @TBMAINSITE@;

# For development.
my $usemydevtree = ($MAINSITE ? 0 : 0);
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

#
# 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 emdb;
use emutil;
use Project;
use User;
use WebTask;
use GeniResponse;
84 85 86
use GeniCertificate;
use GeniCredential;
use GeniImage;
87 88 89 90
use GeniXML;
use GeniUser;
use APT_Geni;
use APT_Profile;
91
use APT_Aggregate;
92 93 94

# Protos
sub fatal($);
Leigh Stoller's avatar
Leigh Stoller committed
95
sub UserError($);
96 97
sub DoListImages();
sub DoDeleteImage();
98 99
sub DoGetCredential();
sub DoRelocate();
100
sub ExitWithError($);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

#
# 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"};
    $webtask = WebTask->Lookup($webtask_id);
    if (!defined($webtask)) {
	fatal("Could not get webtask object");
    }
    $webtask->AutoStore(1);
}
if (@ARGV < 1) {
    usage();
}
my $action = shift(@ARGV);

# Need a real user.
my $this_user = User->ThisUser();
if (! defined($this_user)) {
    fatal("You ($UID) do not exist!");
}
my $geniuser = GeniUser->CreateFromLocal($this_user);

if ($action eq "list") {
    exit(DoListImages());
}
elsif ($action eq "delete") {
    exit(DoDeleteImage());
}
140 141 142 143 144 145
elsif ($action eq "getcredential") {
    exit(DoGetCredential());
}
elsif ($action eq "relocate") {
    exit(DoRelocate());
}
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
else {
    usage();
}
exit(1);

#
# List all images at the specified cluster,
#
sub DoListImages()
{
    my $usage = sub {
	print STDERR "Usage: manage_images list [-a am_urn]\n";
	exit(-1);
    };
    my $optlist = "a:p";
    my $aggregate_urn = $MYURN;
    my $withprofiles  = 0;
    my $errmsg;
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"a"})) {
	$aggregate_urn = $options{"a"};
    }
    if (defined($options{"p"})) {
	$withprofiles = 1;
    }
    my $context = APT_Geni::GeniContext();
    if (!defined($context)) {
	fatal("Could not create context to talk to CM.");
    }
    Genixmlrpc->SetContext($context);
    # Shorten default timeout.
180
    Genixmlrpc->SetTimeout(90);
181

182 183 184 185 186 187 188 189
    # Lets do a cluster check to make sure its reachable.
    my $aggregate = APT_Aggregate->Lookup($aggregate_urn);
    if (!defined($aggregate)) {
	fatal("No such aggregate");
    }
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
190 191
    my $authority = GeniAuthority->Lookup($aggregate_urn);
    if (!defined($authority)) {
192
	fatal("No authority for aggregate");
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    }
    my $cmurl = $authority->url();
    if ($usemydevtree) {
	$cmurl =~ s/protogeni/protogeni\/stoller/;
    }
    my ($credential, $speaksfor) = APT_Geni::GenUserCredential($geniuser);
    fatal("Could not generate credentials for user")
	if (!defined($credential));

    my $credentials = [$credential->asString()];
    if (defined($speaksfor)) {
	$credentials = [@$credentials, $speaksfor->asString()];
    }
    my $args = {
	"credentials" => $credentials,
    };
    my $response = Genixmlrpc::CallMethod($cmurl, undef, "ListImages", $args);

    if ($response->code() != GENIRESPONSE_SUCCESS) {
212 213
	print STDERR $response->error() . "\n";
	ExitWithError($response);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    }
    #
    # We get back a flat list, which can include mulitple versions of
    # each image. Lets reorganize into multilevel hash structure
    # before giving it back to the web interface, so the web interface
    # can just pass it off to the client browser. Also make sure
    # projects map to local projects, and put the local project into
    # the list if so.
    #
    my %ilist = ();

    #
    # First pass, bin them. The urn is without the versions, and then
    # there is a list of version urns.
    #
    foreach my $image (@{ $response->value() }) {
	my $urn     = $image->{"urn"};
	my $hrn     = GeniHRN->new($urn);
	next
	    if (!defined($hrn));
	my ($auth, $ospid, $os, $osvers) = $hrn->ParseImage();
	next
	    if (!defined($authority));
	# URN without the version.
	$urn = GeniHRN::GenerateImage($auth,$ospid,$os,undef);
Leigh Stoller's avatar
Leigh Stoller committed
239 240
	# Put it into the object so that PHP/JS code can find it easy.
	$image->{'imagename'} = $os;
241 242 243 244
	
	# Default to version zero, for old sites not reporting version.
	my $vers = (defined($osvers) ? $osvers : 0);
	# Put it into the object so that PHP/JS code can find it easy.
245
	$image->{'version'} = int($vers);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277

	# Try and set a local project, but use remote pid otherwise.
	$image->{'pid'} = $ospid;

	if (!exists($ilist{$urn})) {
	    $ilist{$urn} = [];
	}
	push(@{	$ilist{$urn} }, $image);
    }
    #
    # Convert to a lexically ordered list. 
    #
    my @ordered = ();
    foreach my $urn (sort keys(%ilist)) {
	push(@ordered, {"urn"      => $urn,
			"versions" => $ilist{$urn}});
    }
    
    #
    # Find profiles using both the naked image and the version
    # specific images. Also map the project urn to a local project.
    #
    foreach my $ref (@ordered) {
	my $urn = $ref->{'urn'};
	my @versions = @{$ref->{'versions'}};
	my $image0 = $versions[0];

	#
	# Use version zero of the image to map the local project. 
	#
	if (exists($image0->{'project_urn'})) {
	    my $projhrn = GeniHRN->new($image0->{'project_urn'});
Leigh Stoller's avatar
Leigh Stoller committed
278 279 280 281 282 283 284 285 286 287
	    if ($projhrn->domain() eq $OURDOMAIN) {
		my $project;
		
		if (defined($projhrn->project())) {
		    $project = Project->Lookup($projhrn->project());
		}
		else {
		    # Backwards compat; we did not always send project urns.
		    $project = Project->Lookup($image0->{'pid'});
		}
288 289 290 291 292 293 294 295 296 297
		if (defined($project)) {
		    $ref->{'pid'}     = $project->pid();
		    $ref->{'pid_idx'} = $project->pid_idx();
		}
	    }
	}
	else {
	    # Remote pid, set above
	    $ref->{'pid'} = $image0->{'pid'};
	}
Leigh Stoller's avatar
Leigh Stoller committed
298
	$ref->{'imagename'} = $image0->{'imagename'};
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	
	#
	# Find profiles using the named image
	#
	$ref->{'using'} = [];
	my @nakedusing  = ();
	next
	    if (APT_Profile::ImageInfo::FindProfilesUsing($urn, \@nakedusing));

	#
	# If no profiles using the naked image, mark it for delete, but
	# if any versions are in use below, we will flip it to no.
	#
	$ref->{'candelete'} = (@nakedusing ? 0 : 1);
	# How many of the children are inactive (can be deleted).
	$ref->{'inactive'}  = 0;
315 316
	# Marker.
	$ref->{'deleted'} = 0;
317 318 319 320 321 322 323

	#
	# List of profiles, with a list of versions of each.
	#
	my %tmp = ();
	foreach my $profile (@nakedusing) {
	    my $profile_uuid = $profile->profile_uuid();
324
	    my $headversion  = $profile->HeadVersionNumber();
325 326 327 328 329 330 331 332 333 334 335

	    if (!exists($tmp{$profile_uuid})) {
		$tmp{$profile_uuid} = {
		    "uuid"     => $profile_uuid,
		    "name"     => $profile->name(),
		    "creator"  => $profile->creator(),
		    "project"  => $profile->pid(),
		    "versions" => [],
		};
	    }
	    push(@{$tmp{$profile_uuid}->{'versions'}},
336
		 {"uuid"     => $profile->uuid(),
337
		  "version"  => int($profile->version()),
338 339
		  "created"  => $profile->created(),
		  "iscurrent"=> ($profile->version() == $headversion ? 1 : 0),
340 341 342 343 344 345 346
		 });
	}
	$ref->{'using'} = [ values(%tmp) ];

	#
	# And for each version of the image.
	#
347 348
	while (@versions) {
	    my $image = shift(@versions);
349
	    my $urn = $image->{'urn'};
Leigh Stoller's avatar
Leigh Stoller committed
350
	    my $hrn = GeniHRN->new($urn);
351 352 353
	    my @using = ();
	    $image->{'using'} = [];
	    $image->{'candelete'} = 0;
354
	    $image->{'deleted'} = 0;
355

Leigh Stoller's avatar
Leigh Stoller committed
356 357 358 359 360 361
	    my (undef, undef, undef, $osvers) = $hrn->ParseImage();
	    # Default to version zero, for old sites not reporting version.
	    my $vers = (defined($osvers) ? $osvers : 0);
	    # Put it into the object so that PHP/JS code can find it easy.
	    $image->{'version'} = int($vers);

362 363 364 365
	    next
		if (APT_Profile::ImageInfo::FindProfilesUsing($urn, \@using));

	    #
366
	    # No references *currently* means we can delete the image.
367 368
	    #
	    if (!@using) {
369 370 371 372 373 374 375 376 377 378 379 380
		#
		# Unless the naked image is being used, and this is the
		# highest numbered image.
		#
		if (@nakedusing && !@versions) {
		    $ref->{'candelete'} = 0;
		    $image->{'using'} = $ref->{'using'};
		}
		else {
		    $image->{'candelete'} = 1;
		    $ref->{'inactive'}++;
		}
381 382 383 384 385 386 387 388
		next;
	    }
	    # Reset candelete to no for entire image. See above.
	    $ref->{'candelete'} = 0;

	    %tmp = ();
	    foreach my $profile (@using) {
		my $profile_uuid = $profile->profile_uuid();
389
		my $headversion  = $profile->HeadVersionNumber();
390 391 392 393 394 395 396 397 398 399 400

		if (!exists($tmp{$profile_uuid})) {
		    $tmp{$profile_uuid} = {
			"uuid"     => $profile_uuid,
			"name"     => $profile->name(),
			"creator"  => $profile->creator(),
			"project"  => $profile->pid(),
			"versions" => [],
		    };
		}
		push(@{$tmp{$profile_uuid}->{'versions'}},
401
		     {"uuid"     => $profile->uuid(),
402
		      "version"  => int($profile->version()),
403 404 405
		      "created"  => $profile->created(),
		      "iscurrent"=> ($profile->version() ==
				     $headversion ? 1 :0),
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
		     });
	    }
	    $image->{'using'} = [ values(%tmp) ];
	}
    }
    if (defined($webtask)) {
	$webtask->value(\@ordered);
	$webtask->Exited(0);
    }
    else {
	print Dumper(\@ordered);
    }
    exit(0);
}

#
# Delete image at the specified cluster,
#
sub DoDeleteImage()
{
    my $usage = sub {
	print STDERR "Usage: manage_images delete [-a am_urn] <image_urn>\n";
	exit(-1);
    };
Leigh Stoller's avatar
Leigh Stoller committed
430
    my $optlist = "a:d:v:n";
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    my $aggregate_urn = $MYURN;
    my $impotent      = 0;
    my $profile;
    my $errmsg;
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"a"})) {
	$aggregate_urn = $options{"a"};
    }
    if (defined($options{"n"})) {
	$impotent = 1;
    }
    &$usage()
	if (!@ARGV);
    my $image_urn = shift(@ARGV);
    
    if (defined($options{"d"})) {
	$profile = APT_Profile->Lookup($options{"d"});
	if (!defined($profile)) {
	    fatal("Profile does not exist");
	}
	if ($profile->isLocked()) {
	    fatal("Profile is locked down, cannot be deleted");
	}
Leigh Stoller's avatar
Leigh Stoller committed
457

458
	#
Leigh Stoller's avatar
Leigh Stoller committed
459
	# The caller tells us what versions of the image to delete,
460
	#
Leigh Stoller's avatar
Leigh Stoller committed
461 462 463 464 465 466
	if (!exists($options{"v"})) {
	    fatal("Missing version number list");
	}
	if ($options{"v"} !~ /^[\d,]+$/) {
	    fatal("Version number list should be comma separated integers");
	}
467 468
	my @todelete = ();
	
Leigh Stoller's avatar
Leigh Stoller committed
469 470 471 472
	foreach my $versnum (split(",", $options{"v"})) {
	    my $version = APT_Profile->Lookup($profile->profileid(), $versnum);
	    next
		if (!defined($version));
Leigh Stoller's avatar
Leigh Stoller committed
473

Leigh Stoller's avatar
Leigh Stoller committed
474
	    if ($version->isLocked()) {
Leigh Stoller's avatar
Leigh Stoller committed
475 476 477 478 479 480 481 482 483 484
		my $mesg =
		    "Version " . $version->version() . " of the " .
		    $version->name() . " profile is locked down, ".
		    "cannot delete it.";
		
		if ($webtask) {
		    $webtask->reason("locked");
		    $webtask->profile($version->uuid());
		}
		UserError($mesg);
485
	    }
Leigh Stoller's avatar
Leigh Stoller committed
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

	    #
	    # Check image references for this version. We want to
	    # know if there are any other images associated with this
	    # version beside the one we are trying to delete. If so,
	    # we cannot delete the profile version since that will
	    # result in another image getting deleted.
	    #
	    my %irefs = %{ $version->images() };

	    if (keys(%irefs) > 1) {
		foreach my $client_id (keys(%irefs)) {
		    my $imageinfo = $irefs{$client_id};
		    
		    # We do not ever care about system images.
		    next
			if ($imageinfo->ospid() eq "emulab-ops");

		    my $mesg =
			"Version " . $version->version() . " of the " .
			$version->name() . " profile is using multiple ".
			"images. As a safety measure, we require that you ".
			"delete or edit that profile before you can delete ".
			"this image.";

		    if ($webtask) {
			$webtask->reason("conflict");
			$webtask->profile($version->uuid());
			$webtask->image($imageinfo->image());
		    }
		    UserError($mesg);
		}
518
	    }
Leigh Stoller's avatar
Leigh Stoller committed
519 520 521
	    print "Would delete version " . $version->version() .
		" of profile " . $profile->name() . "\n";
	    push(@todelete, $version);
522 523 524 525 526
	}
	foreach my $version (@todelete) {
	    my $vers = $version->version();
	    my $uuid = $version->uuid();
	    
527
	    print "Deleting version $uuid:$vers\n";
528 529 530
	    my $opt = ($impotent ? "-n" : "");

	    my $output =
531
		emutil::ExecQuiet("$MANAGEPROFILE delete -k $opt $uuid");
532 533
	    print $output;
	    if ($?) {
534
		fatal("Could not delete version $uuid:$vers");
535 536 537 538 539 540 541 542 543 544
	    }
	}
    }
    
    my $context = APT_Geni::GeniContext();
    if (!defined($context)) {
	fatal("Could not create context to talk to CM.");
    }
    Genixmlrpc->SetContext($context);
    # Shorten default timeout.
545
    Genixmlrpc->SetTimeout(90);
546

547 548 549 550 551 552 553 554
    # Lets do a cluster check to make sure its reachable.
    my $aggregate = APT_Aggregate->Lookup($aggregate_urn);
    if (!defined($aggregate)) {
	fatal("No such aggregate");
    }
    if ($aggregate->CheckStatus(\$errmsg)) {
	UserError($errmsg);
    }
555 556
    my $authority = GeniAuthority->Lookup($aggregate_urn);
    if (!defined($authority)) {
557
	fatal("No authority for aggregate");
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    }
    my $cmurl = $authority->url();
    if ($usemydevtree) {
	$cmurl =~ s/protogeni/protogeni\/stoller/;
    }
    my ($credential, $speaksfor) = APT_Geni::GenUserCredential($geniuser);
    fatal("Could not generate credentials for user")
	if (!defined($credential));

    my $credentials = [$credential->asString()];
    if (defined($speaksfor)) {
	$credentials = [@$credentials, $speaksfor->asString()];
    }
    my $args = {
	"image_urn"   => $image_urn,
	"credentials" => $credentials,
    };
    if ($impotent) {
	$args->{"impotent"} = 1;
    }
    my $response = Genixmlrpc::CallMethod($cmurl, undef, "DeleteImage", $args);

    if ($response->code() != GENIRESPONSE_SUCCESS &&
	$response->code() != GENIRESPONSE_SEARCHFAILED) {
	if ($response->output()) {
	    print STDERR $response->output() . "\n";
	    if (defined($webtask)) {
		$webtask->output($response->output());
	    }
	}
	else {
	    print STDERR "Operation failed, returned " .
		$response->code() . "\n";
	    if (defined($webtask)) {
		$webtask->output("Operation failed");
	    }
	}
	if (defined($webtask)) {
	    $webtask->Exited($response->code());
	}
	exit($response->code());
    }
    if (defined($webtask)) {
	$webtask->Exited(0);
    }
    exit(0);
}

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 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 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
sub GetCredentialInternal($$$)
{
    my ($image_urn, $context, $perror) = @_;

    # Convert the image urn into the authority URN.
    my $hrn      = GeniHRN->new($image_urn);
    my $authurn  = GeniHRN::Generate($hrn->domain(), "authority", "cm");
    my $manager  = APT_Geni::GetAuthority($authurn);
    if (!defined($manager)) {
	$$perror = "Could not lookup authority $authurn";
	return undef;
    }
    my $args = {"image_urn" => $image_urn};
    my $response = APT_Geni::PortalRPC($manager, $context,
				       "GetImageCredential", $args);
    if (GeniResponse::IsError($response)) {
	return $response;
    }
    my $credential = GeniCredential->CreateFromSigned($response->value());
    if (!defined($credential)) {
	$$perror = "Could not parse new credential";
	return undef;
    }
    return $credential;
}

#
# Request an image credential via the Portal fast path.
#
sub DoGetCredential()
{
    my $usage = sub {
	print STDERR "Usage: manage_images getcredential [-a urn] ".
	    "<image_urn>\n";
	print STDERR "Options:\n";
	print STDERR "  -a urn    - URN of the remote cluster (cm)\n";
	print STDERR " image_urn  - URN of the image at the remote cluster\n";
	exit(-1);
    };
    my $optlist = "a:";
    my $authority;
    my $errmsg;
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"a"})) {
	my $urn = $options{"a"};
	$authority = APT_Geni::GetAuthority($urn);
	if (!defined($authority)) {
	    fatal("Could not lookup authority $urn");
	}
    }
    &$usage()
	if (!@ARGV);
    my $image_urn = shift(@ARGV);
    if (!GeniHRN::IsValid($image_urn)) {
	fatal("Not a valid urn");
    }
    # Convert the image urn into the authority URN.
    my $hrn = GeniHRN->new($image_urn);
    if (!$hrn->IsImage()) {
	fatal("Not an image urn");
    }
    my $context  = APT_Geni::GeniContext();
    my $credential = GetCredentialInternal($image_urn, $context, \$errmsg);
    if (!defined($credential)) {
	fatal($errmsg);
    }
    if (GeniResponse::IsError($credential)) {
	ExitWithError($credential);
    }
    if (defined($authority)) {
	my $delegated = $credential->Delegate($authority);
	$delegated->Sign($context);
	$credential = $delegated;
    }
    print $credential->asString();
    exit(0);
}

#
# Relocate an image back to this cluster. 
#
sub DoRelocate()
{
    $debug = 1;
    
    my $usage = sub {
	print STDERR "Usage: manage_images relocate [-s] [-u user] -p pid ".
	    "-i imagename <image_urn> <url>\n";
	print STDERR "       manage_images relocate -p pid -i imagename\n";
	print STDERR "Use the -s option to *also* schedule.\n";
	print STDERR "Use the -S option to *only* schedule.\n";
	print STDERR "Use the second form to start a scheduled relocation\n";
	exit(-1);
    };
    my $optlist  = "p:i:u:sS";
    my $schedule = 0;
    my $project;
    my $group;
    my $pid;
    my $user;
    my $image_urn;
    my $image_url;
    my $imagename;
    my $errmsg;
    my %options = ();
    if (! getopts($optlist, \%options)) {
	&$usage();
    }
    if (defined($options{"s"}) || defined($options{"S"})) {
	$schedule = 1;
    }
    if (defined($options{"p"})) {
	$pid = $options{"p"};
	$project = Project->Lookup($pid);
	if (!defined($project)) {
	    fatal("No such project");
	}
	$group = $project->GetProjectGroup();
    }
    if (defined($options{"u"})) {
	$user = User->Lookup($options{"u"});
	if (!defined($user)) {
	    fatal("No such user");
	}
    }
    else {
	$user = $this_user;
    }
    if (defined($options{"i"})) {
	$imagename = $options{"i"};
	if (!TBcheck_dbslot($imagename, "images", "imagename",
			    TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)){
	    fatal("Not a valid imagename");
	}
    }
    &$usage()
	if (!(defined($pid) && defined($imagename)));

    if (@ARGV == 2) {
	$image_urn = shift(@ARGV);
	if (!GeniHRN::IsValid($image_urn)) {
	    fatal("Not a valid urn");
	}
        $image_url = shift(@ARGV);
    }
    else {
	my $blob;
	my $val = GeniImage::ImageRelocationPending($imagename, $group, \$blob);
	if (!$val || !defined($blob)) {
	    fatal("Could not lookup scheduled relocation");
	}
	print Dumper($blob);
	$image_urn = $blob->{'remote_urn'};
	$image_url = $blob->{'metadata_url'};
	$user = User->Lookup($blob->{'uid_idx'});
	if (!defined($user)) {
	    fatal("Not a valid user: " . $blob->{'uid'});
	}
    }
    # Convert the image urn into the authority URN.
    my $hrn = GeniHRN->new($image_urn);
    if (!$hrn->IsImage()) {
	fatal("Not an image urn");
    }

    if ($schedule) {
	if (GeniImage::ImageRelocationSchedule($imagename, $user, $group,
					       $image_urn, $image_url)) {
	    fatal("Could not schedule incoming relocation for $image_urn");
	}
	if (exists($options{"S"})) {
	    exit(0);
	}
    }
    #
    # The context for image import is the CM.
    #
    my $cmcert = GeniCertificate->LoadFromFile($CMCERT);
    if (!defined($cmcert)) {
	fatal("Could not load certificate from $CMCERT\n");
    }
    my $context = Genixmlrpc->Context($cmcert);
    if (!defined($context)) {
	fatal("Could not create RPC context");
    }
    my $credential = GetCredentialInternal($image_urn, $context, \$errmsg);
    if (!defined($credential)) {
	fatal("Could not generate credential: $errmsg");
    }
    if (GeniResponse::IsError($credential)) {
	ExitWithError($credential);
    }
    # This will autodelete
    my $credfile = $credential->WriteToFile();
    if (!defined($credfile)) {
	fatal("Could not write credential to file");
    }
    if (GeniImage::ImageRelocationLock($imagename, $group)) {
	print STDERR "Could not lock image relocation record\n";
	exit(1);
    }
    my $cmd = "$IMPORTER ";
    $cmd .= "-d " if ($debug);
    $cmd .= "-R -C $credfile -p $pid -u " . $user->uid() . " " ;
    $cmd .= "-i '$imagename' '$image_url'";
    if ($debug) {
	print "Running '$cmd'\n";
    }
    system($cmd);
    if ($?) {
	GeniImage::ImageRelocationUnlock($imagename, $group);
	fatal("Could not relocate image");
    }
    GeniImage::ImageRelocationFinished($imagename, $group);
    exit(0);
}

826 827 828 829 830 831 832 833 834 835 836 837
sub fatal($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(-1);
    }
    print STDERR "$mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}
Leigh Stoller's avatar
Leigh Stoller committed
838 839 840 841 842 843 844 845 846 847 848 849
sub UserError($)
{
    my ($mesg) = @_;

    if (defined($webtask)) {
	$webtask->output($mesg);
	$webtask->Exited(1);
    }
    print STDERR "$mesg\n";
    # Exit with positive status so web interface treats it as user error
    exit(1);
}
850 851 852 853 854 855 856 857 858

sub escapeshellarg($)
{
    my ($str) = @_;

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

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
#
# 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".
	             "    $mesg\n";
	exit(1);
    }
    fatal($mesg);
}