manage_images.in 14.4 KB
Newer Older
1 2 3 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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 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 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 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 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 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 265 266 267 268 269 270 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 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 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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
#!/usr/bin/perl -w
#
# Copyright (c) 2000-2017 University of Utah and the Flux Group.
# 
# {{{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()
{
    print STDERR "Usage: manage_images [options --] list ...\n";
    print STDERR "Usage: manage_images [options --] delete <urn> ...\n";
    exit(-1);
}
my $optlist     = "dt:";
my $debug       = 0;
my $webtask_id;
my $webtask;

# For development.
my $usemydevtree = 0;

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $OURDOMAIN     = "@OURDOMAIN@";
my $MYURN         = "urn:publicid:IDN+${OURDOMAIN}+authority+cm";
my $MANAGEPROFILE = "$TB/bin/manage_profile";

#
# 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;
use GeniXML;
use GeniUser;
use APT_Geni;
use APT_Profile;

# Protos
sub fatal($);
sub DoListImages();
sub DoDeleteImage();

#
# 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());
}
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.
    Genixmlrpc->SetTimeout(60);

    my $authority = GeniAuthority->Lookup($aggregate_urn);
    if (!defined($authority)) {
	fatal("No such aggregate");
    }
    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) {
	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());
    }
    #
    # 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);
	
	# 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'} = $vers;

	# 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'});
	    if ($projhrn->domain() eq $OURDOMAIN &&
		defined($projhrn->project())) {
		my $project = Project->Lookup($projhrn->project());
		if (defined($project)) {
		    $ref->{'pid'}     = $project->pid();
		    $ref->{'pid_idx'} = $project->pid_idx();
		}
	    }
	}
	else {
	    # Remote pid, set above
	    $ref->{'pid'} = $image0->{'pid'};
	}
	
	#
	# 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;

	#
	# List of profiles, with a list of versions of each.
	#
	my %tmp = ();
	foreach my $profile (@nakedusing) {
	    my $profile_uuid = $profile->profile_uuid();

	    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'}},
		 {"uuid"    => $profile->uuid(),
		  "version" => $profile->version(),
		  "created" => $profile->created(),
		 });
	}
	$ref->{'using'} = [ values(%tmp) ];

	#
	# And for each version of the image.
	#
	# The last version of the image is special; it gets any profile
	# references for the naked image, since that is what a naked image
	# means; use the most recent image. So if we have naked references,
	# mark the last image for the loop below so we can extend the list
	#
	if (@nakedusing) {
	    $versions[scalar(@versions) - 1]->{'islast'} = 1;
	}
	foreach my $image (@versions) {
	    my $urn = $image->{'urn'};
	    my @using = ();
	    $image->{'using'} = [];
	    $image->{'candelete'} = 0;

	    next
		if (APT_Profile::ImageInfo::FindProfilesUsing($urn, \@using));

	    # Combine the lists.
	    if ($image->{'islast'}) {
		foreach my $p (@nakedusing) {
		    push(@using, $p)
			if (!grep {$_->profileid() == $p->profileid()} @using);
		}
	    }

	    #
	    # No references *currently* means we can delete the image. 
	    #
	    if (!@using) {
		$image->{'candelete'} = 1;
		$ref->{'inactive'}++;
		next;
	    }
	    # Reset candelete to no for entire image. See above.
	    $ref->{'candelete'} = 0;

	    %tmp = ();
	    foreach my $profile (@using) {
		my $profile_uuid = $profile->profile_uuid();

		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'}},
		     {"uuid"    => $profile->uuid(),
		      "version" => $profile->version(),
		      "created" => $profile->created(),
		     });
	    }
	    $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);
    };
    my $optlist = "a:d:n";
    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");
	}
	#
	# This argument says; delete any version of the specified
	# profile, that reference the image being deleted. So we
	# have to go through every version of the profile and check
	# to see if its using this image. For any of those versions,
	# we try to delete it.
	#
	my @todelete = ();
	
	foreach my $version ($profile->AllVersions()) {
	    my $usingimage = 0;
	    my $conflict;

	    #
	    # 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() };
	    
	    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 $snapname = $profile->name() . "." . $client_id;

		next
		    if (! ($imageinfo->os() eq $profile->name() ||
			   $imageinfo->os() eq $snapname));

		if ($imageinfo->image() eq $image_urn) {
		    $usingimage = 1;
		}
		else {
		    $conflict = $imageinfo->image();
		}
	    }
	    if ($usingimage && $conflict) {
		fatal("Version " . $version->version() . " of the " .
		      $version->name() . " profile has another ".
		      "image that would be deleted as well: $conflict. ".
		      "You will need to go to the profile page and delete ".
		      "that profile version before you can delete this image.");
	    }
	    if ($usingimage && $version->isLocked()) {
		fatal("Version " . $version->version() . " is locked ".
		      "down, cannot delete it.");
	    }
	    if ($usingimage) {
		push(@todelete, $version);
		print "Would delete profile version " .
		    $version->version() . "\n";
	    }
	}
	foreach my $version (@todelete) {
	    my $vers = $version->version();
	    my $uuid = $version->uuid();
	    
	    print "Deleting version $vers\n";
	    my $opt = ($impotent ? "-n" : "");

	    my $output =
		emutil::ExecQuiet("$MANAGEPROFILE delete -- -k $opt $uuid");
	    print $output;
	    if ($?) {
		fatal("Could not delete version $vers");
	    }
	}
    }
    
    my $context = APT_Geni::GeniContext();
    if (!defined($context)) {
	fatal("Could not create context to talk to CM.");
    }
    Genixmlrpc->SetContext($context);
    # Shorten default timeout.
507
    Genixmlrpc->SetTimeout(90);
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

    my $authority = GeniAuthority->Lookup($aggregate_urn);
    if (!defined($authority)) {
	fatal("No such aggregate");
    }
    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);
}

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

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

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