image_import-new.in 37.7 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2010-2017 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 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
# 
# {{{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 XML::Simple;
use Data::Dumper;
use URI::Escape;

#
# Import an image from an external source. 
#
sub usage()
{
    print("Usage: image_import [-d] [-v] [-u <user>] [-g] [-p pid] ".
	  "[-i name] <url>\n");
    print("       image_import [-d] [-u <user>] [-c] [-g] <imageid> [url]\n");
    print("Options:\n");
    print(" -d      - Turn on debugging\n");
    print(" -v      - Verify XML description only\n");
    print(" -g      - Download image after creating/updating descriptor\n");
    print(" -G      - Download ALL images instead.\n");
    print(" -u uid  - Create image as user instead of caller\n");
    print(" -p pid  - Create image in the specified project.\n".
	  "           Defaults to emulab-ops.\n");
    print(" -i name - Use name for imagename.\n".
	  "           Defaults to name in the desciptor\n");
    print(" -s      - With -r just update the sig file\n");
    print(" -c      - With -r update ndz file using the updates table\n");
    exit(-1);
}
my $optlist = "dvu:p:gGi:Iscr";
my $debug   = 0;
my $verify  = 0;
my $getimage= 0;
my $update  = 0;
my $dosig   = 0;
my $force   = 0;
my $copyback= 0;
my $getallimages=0;
my $user;
my $group;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBLOGS      = "@TBLOGSEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
my $TBGROUP_DIR	= "@GROUPSROOT_DIR@";
my $TBPROJ_DIR	= "@PROJROOT_DIR@";
my $TBBASE	= "@TBBASE@";
my $CONTROL     = "@USERNODE@";
my $WGET	= "/usr/local/bin/wget";
my $NEWIMAGE_EZ = "$TB/bin/newimageid_ez";
my $IMAGEDUMP   = "$TB/bin/imagedump";
my $SHA1	= "/sbin/sha1";
my $SAVEUID	= $UID;
my $IMAGEVALIDATE = "$TB/sbin/imagevalidate";
my $DELETEIMAGE   = "$TB/sbin/delete_image";
my $POSTIMAGEINFO = "$TB/sbin/protogeni/postimagedata";
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
my $WITHDELTAS    = @IMAGEDELTAS@;
my $DOIMAGEDIRS   = @IMAGEDIRECTORIES@;
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
my $doprovenance  = $WITHPROVENANCE;
89
my $dodeltas      = $WITHDELTAS;
90 91 92 93 94 95

#
# When fetching the metadata, we now tell the server what client
# version of the software we are so it gives something we can handle.
# Be sure to update this if you change the version in dumpdescriptor.
#
96
my $METADATA_CLIENTVERSION = 5;
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

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

#
# We don't want to run this script unless its the real version.
#
if ($EUID != 0) {
    die("*** $0:\n".
	"    Must be setuid! Maybe its a development version?\n");
}

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use libdb;
use emutil;
use EmulabConstants;
use EmulabFeatures;
use libtestbed;
use User;
use Project;
use Group;
129
use OSImage;
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

# Locals;
my $url;
my $image;
my $imagename;
my $updater_urn;

# Protos
sub fatal($);
sub FetchMetadata($);
sub CreateImage($$$$$);
sub DownLoadImage($$$$);
sub FetchImageFile($$);
sub FetchSigFile($$);
sub CloneFromMetadata($$$);
sub UpdateImageFromMetadata($$);
sub maybeGetImage($$);

#
# There is no reason to run as root unless we need to ssh over
# to ops to fetch the URL.
#
$EUID = $UID;

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verify = 1;
}
if (defined($options{"g"})) {
    $getimage = 1;
}
if (defined($options{"G"})) {
    $getimage = 1;
    $getallimages = 1;
}
if (defined($options{"s"})) {
    $dosig = 1;
}
if (defined($options{"i"})) {
    $imagename = $options{i};
}
if (defined($options{"r"})) {
    $update   = 1;
    if (defined($options{"c"})) {
	$copyback = 1;
    }
}
if (defined($options{"R"})) {
    $update = 1;
    $force  = 1;
}
if (defined($options{"u"})) {
    $user = User->Lookup($options{"u"});
    fatal("User does not exist")
	if (!defined($user));
}
if (defined($options{"p"})) {
    $group = Group->Lookup($options{"p"});
    if (!defined($group)) {
	my $project = Project->Lookup($options{"p"});
	fatal("Project/Group does not exist")
	    if (!defined($project));
	$group = $project->GetProjectGroup();
	fatal("Error getting project group for $project")
	    if (!defined($group));
    }
}
else {
    $group = Group->Lookup(TBOPSPID(), TBOPSPID());
    fatal("Error getting project group for " . TBOPSPID())
	if (!defined($group));
}

if (!defined($user)) {
    $user = User->ThisUser();
    if (! defined($user)) {
	fatal("You ($UID) do not exist!");
    }
}

usage()
    if (!@ARGV);

#
# If arg is a URL, then image must not exist.
#
if ($ARGV[0] =~ /^http/) {
    $url = $ARGV[0];
228
    if (OSImage->LookupByURL($url)) {
229 230 231 232 233 234 235 236 237 238 239 240 241 242
	fatal("Image already exists for URL, please use the id to update");
    }
    # We know this is valid, but must taint check anyway for shell command.
    if ($url =~/^(.*)$/) {
	$url = $1;
    }
    # If the user is not an admin, must be a member or have perm in
    # the group.
    if (!$user->IsAdmin() &&
	!$group->AccessCheck($user, TB_PROJECT_MAKEIMAGEID())) {
	fatal("$user does not have permission to create images in $group");
    }
}
else {
243
    $image = OSImage->Lookup(shift(@ARGV));
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
    if (!defined($image)) {
	fatal("Image does not exist, maybe you need to import by url first");
    }
    if ($copyback) {
	my ($updater_uid,$updater_idx);
	
	#
	# We have to look in the updates table, but we want to do this
	# locked so that no one else can mess with it. So lock up here,
	# and skip locking below. See fatal(), we will unlock there if
	# things go bad.
	#
	if ($image->Lock()) {
	    print "$image is currently locked. Please try again later\n";
	    exit(0);
	}
	my $imageid = $image->imageid();
	my $query_result =
	    DBQueryWarn("select * from image_updates ".
			"where imageid='$imageid'");
	if (!$query_result) {
	    $image->Unlock();
	    exit(-1);
	}
	if (!$query_result->numrows) {
	    print "No update in table. Nothing to do.\n";
	    $image->Unlock();
	    exit(0);
	}
	my $row = $query_result->fetchrow_hashref();
	$url          = $row->{'url'};
	$updater_uid  = $row->{'updater'};
	$updater_idx  = $row->{'updater_idx'};
	$updater_urn  = $row->{'updater_urn'};

	#
	# Also want the user doing the import to be the user who actually
	# did the update on the remote cluster, if we happen to have that
	# record. If not, we have to do it as the creator (someone in the
	# project the image belongs to). 
	#
	$user = undef;
	if (defined($updater_uid)) {
	    $user = User->Lookup($updater_idx);
	    # Ick, setgroups skips nonlocal users, so user does not have
	    # permission to do this on ops. Needs thought.
	    if ($user->IsNonLocal()) {
		$user = undef;
	    }
	}
	if (!defined($user)) {
	    $user = User->Lookup($image->creator_idx());
	}
	if (!defined($user)) {
	    print STDERR "No current user to import image as.\n";
	    $image->Unlock();
	    exit(-1);
	}
	$EUID = 0;
	$UID  = $SAVEUID = $user->unix_uid();
	$EUID = $UID;
    }
    else {
	#
	# Allow importing new version of an existing image by a url. This
	# allows adding new versions of the image at the origin cluster, to
	# an existing image here. Previously, we would have created a brand
	# new image name.  Of course, we have to compare the origin image
	# uuids to confirm they are really from the same image.
	#
	if (@ARGV) {
	    $url = $ARGV[0];
	    
	    # We know this is valid, but must taint check anyway for shell
	    # command.
	    if ($url =~/^(.*)$/) {
		$url = $1;
	    }
	}
	else {	    
	    if (!defined($image->metadata_url())) {
		fatal("Not an imported image");
	    }
	    $url = $image->metadata_url();
	}
    }
    # If the user is not an admin, must have perm on the image.
    if (!$user->IsAdmin() &&
	!$image->AccessCheck($user, TB_IMAGEID_CREATE())) {
	fatal("$user does not have permission to modify $image");
    }
    # Implied.
    $update = 1;
}
my $xmlparse = FetchMetadata($url);
fatal("Could not get metadata!")
    if (!defined($xmlparse));

if ($WITHPROVENANCE) {
    # But allow feature override.
    if (EmulabFeatures->Lookup("ImageProvenance")) {
	$doprovenance =
346
	    EmulabFeatures->FeatureEnabled("ImageProvenance", undef, $group);
347
    }
348 349 350 351
}
if (!$doprovenance && $getallimages) {
    fatal("-G option requires IMAGE_PROVENANCE to be enabled");
}
352 353 354 355 356 357 358 359 360 361 362 363 364

#
# Need to watch for two experiments causing this image to
# get created at the same time. It would be pretty silly,
# but it can happen.
#
if (!$update) {
    my $safe_url = DBQuoteSpecial($url);
    my $query_result = DBQueryWarn("select GET_LOCK($safe_url, 120)");
    if (!$query_result ||
	!$query_result->numrows) {
	fatal("Could not get the SQL lock for a long time!");
    }
365 366 367 368 369 370 371 372
    $image = OSImage->LookupByURL($url);
    #
    # Look inside the metadata. If we get a non-version specific URL,
    # we can use that to look at our images to see if we already have
    # a different version of the image. If we do, we can shift to
    # update mode and add the later versions to our image history,
    # thus bringing them into sync.
    #
373
    if (!defined($image)) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	if ($doprovenance &&
	    exists($xmlparse->{'attribute'}->{"image_metadata_url"})) {
	    my $image_url =
		$xmlparse->{'attribute'}->{"image_metadata_url"}->{'value'};
	
	    $image = OSImage->LookupByURL($image_url);
	    if (defined($image)) {
		print "Another version of this image is already imported.\n";
		print "Shifting to update mode\n";
		$update = 1;
	    }
	}
	if (!defined($image)) {
	    $image = CreateImage($url, $xmlparse, $user, $group, $imagename);
	}
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
    }
    DBQueryWarn("select RELEASE_LOCK($safe_url)");
}
exit(0)
    if ($verify);

#
# We need to get the lock since someone else could already
# be downloading it. Even worse, someone might be taking a local
# snapshot, although at the moment we do not support that.
# If doing a copyback, we already have the lock.
#
if (($update || $getimage) && !$copyback) {
    if ($image->Lock()) {
	print "$image is currently locked. Waiting ...\n";

	my $maxwait = 600;
	while ($maxwait > 0 && $image->WaitLock(60)) {
	    print "$image is currently locked. Waiting ...\n";
	    $maxwait -= 60;
	}
	if (!$image->GotLock()) {
	    fatal("Could not get the image lock after a long time");
	}
    }
}

#
# If we are doing image versioning and the origin cluster is doing
# versioning, we can import the entire descriptor list. We will not
# import the image files unless we need them, and really, this is
# only useful when the origin is doing deltas where we need all the
# intermediate versions to lay down the correct image.
#
# If we are not doing image versioning, then all we can do is
# import the new image file and overwrite what we have locally. 
#
# Origin not doing history, we are NOT doing history:
#   Update local descriptor, download new image to overwrite local.
#   Must be the full image file, we cannot do deltas.
# Origin not doing history, we ARE doing history:
#   Create new local version, download new image file.
#   Must be the full image file.
# Origin doing history, we are NOT doing history:
#   Update local descriptor, download new image to overwrite local.
#   Must be the full image file, we cannot do deltas without history.
# Origin doing history, we ARE doing history:
#   In all cases, we want to create local image descriptors for
#   the entire history, duplicating the history at the origin cluster,
#   so that local users can use earlier versions of the image. But then
#   things changed based on deltas:
# 
#   We are NOT doing deltas:
#     Origin IS doing deltas:
#     Origin is NOT doing deltas:
#       Must download only a full image for the specific image being used.
#   We ARE doing deltas:
#     Origin IS doing deltas:
#       Download the delta files for the current version and all versions
#       back to the first version (which is a full image of course). 
#     Origin is NOT doing deltas:
#       Must download only a full image for the specific image being used.
#

#
# First off, if this is an update we want to fetch any prior versions
# of the metadata back to the most recent version we have, so that we
# can build local descriptor versions for everything up to the image
# we actually want to use. Mostly this matters for deltas, but we do it
# anyway in case we ever want to convert from full images into deltas.
#
if ($update) {
    if ($doprovenance) {
	if (exists($xmlparse->{"version_history"})) {
	    my @versions = ();
    
	    foreach my $vers (keys(%{ $xmlparse->{"version_history"} })) {
		my $val = $xmlparse->{"version_history"}->{$vers};
		my $parse = FetchMetadata($val);
		fatal("Could not fetch metadata for version $vers")
		    if (!defined($parse));
		$versions[$vers] = $parse;
	    }
	    #
	    # Sanity check that there are no gaps.
	    #
	    if (scalar(@versions) !=
		scalar(keys(%{$xmlparse->{"version_history"}}))){
		fatal("Inconsistent number of version history records");
	    }

	    #
481 482
	    # Go through the version list and make sure we have a
	    # local version created.
483
	    #
484 485
	    for (my $i = 1; $i <= scalar(@versions); $i++) {
		my $clone = OSImage->Lookup($image->imageid(), $i);
486 487 488 489 490 491 492

		if (!defined($clone)) {
		    $clone = CloneFromMetadata($image, $versions[$i], $user);
		    if (!defined($clone)) {
			$image->Unlock();
			fatal("Could not clone image descriptor $image");
		    }
493 494 495 496
		}
		else {
		    my $attributes = $versions[$i]->{'attribute'};
		    
497
		    #
498
		    # If the image has diverged locally we are screwed.
499
		    #
500 501 502 503 504
		    if ($clone->metadata_url() ne
			$attributes->{"metadata_url"}->{'value'}) {
			$image->Unlock();
			fatal("Image out of sync wrt url at version $i");
		    }
505 506 507 508 509
		    foreach my $attribute ("hash", "deltahash",
					   "size", "deltasize") {
			my $xmlval = $attributes->{$attribute}->{'value'}
		            if (exists($attributes->{$attribute}));
			my $curval = $image->field($attribute);
510

511 512 513 514 515 516 517
			if (defined($curval) &&
			    !(defined($xmlval) || "$xmlval" ne "$curval")) {
			    
			    $image->Unlock();
			    fatal("Image out of sync wrt $attribute at ".
				  "version $i: $xmlval != $curval");
			}
518
		    }
519 520 521 522
		}
		$image = $clone;
	    }
	    #
523 524 525
	    # Image now points to the clone for the highest numbered
	    # version, which might have been the image we started
	    # with.
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 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 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
	    #
	}
	#
	# We are doing provenance (obviously), but the other side might
	# not.  It is actually hard to know since it might be the only
	# version of the image (thus no version history in the metadata) or
	# it might just be version zero from a cluster that does versioning
	# (again, no version history). In fact, the other side might have
	# started out not doing provenance, and then decided to start doing
	# it. This last case I need to come back and revisit. But anyway,
	# if we are doing provenance and the origin side gives a new hash
	# value for the same version of the image, we can assume the other
	# side is not doing image versioning. 
	#
	if (defined($image->hash()) &&
	    $image->hash() ne $xmlparse->{'attribute'}->{"hash"}->{'value'}) {
	    #
	    # The other side changed the hash for an image, so it is not
	    # doing versioning, so the best we can do is clone what we
	    # have to make a new local version.
	    #
	    # This will include unreleased images (in image_versions, but
	    # not the one pointed to by the images table). 
	    #
	    $image = $image->LookupMostRecent();
	    if (!defined($image)) {
		fatal("Cannot lookup most recent version of $image");
	    }
	    # Reuse if not ready/released. Do not change this test,
	    # see below in CreateImage().
	    if ($image->ready() && $image->released()) {
		my $clone = CloneFromMetadata($image, $xmlparse, $user);
		if (!defined($clone)) {
		    fatal("Could not clone image descriptor $image");
		}
		$image = $clone;
	    }
	    UpdateImageFromMetadata($image, $xmlparse);
	    #
	    # Since the hash changed, clear the ready bit so that we know to
	    # get the image below.
	    #
	    $image->ClearReady();
	}
    }
    else {
	#
	# No local versioning, we update the image in place. 
	#
	if (defined($image->hash()) &&
	    $image->hash() ne $xmlparse->{'attribute'}->{"hash"}->{'value'}) {
	
	    UpdateImageFromMetadata($image, $xmlparse);
	    #
	    # Since the hash changed, clear the ready bit so that we know to
	    # get the image below.
	    #
	    $image->ClearReady();
	}
    }
}

#
# Now figure out what images we need to actually download.
#
if ($getimage) {
    my $didsomething = 0;
    
    #
    # When provenance is not enabled, we just get the one image.
    #
    if (!$doprovenance) {
	#
	# New images will not have their ready bit set, and if we did an update
	# earlier without -g, we cleared the ready bit then.
	#
	my $rval = maybeGetImage($image, 0);
	if ($rval < 0) {
	    fatal("Could not download $image from server");
	}
	$didsomething += $rval;
    }
    else {
	my @getlist = ($image);

	#
	# Get all *prior* versions of the image. Only makes sense when
	# provenance is enabled, which we checked for above. 
	#
	if ($getallimages) {
	    my $tmp = $image;

	    while (my $parent = $tmp->Parent()) {
		# Do not cross image boundry (yet).
		last
		    if ($parent->imageid() ne $tmp->imageid());

		push(@getlist, $parent);
		$tmp = $parent;
	    }
	}

	foreach my $imget (@getlist) {
	    my $dodelta = 0;

	    #
	    # When provenance is enabled, we also have to consider deltas.
	    # This needs more thought. At the moment, we always get the
634
	    # delta if it exists (and we have deltas enabled).
635 636
	    #
	    if ($imget->deltahash()) {
637 638 639 640 641
		if ($dodeltas) {
		    $dodelta = 1;
		}
		elsif (! $imget->hash()) {
		    fatal("This image has only deltas, but deltas are ".
642
			  "not enabled locally");
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
	    }
	    my $rval = maybeGetImage($imget, $dodelta);
	    if ($rval < 0) {
		fatal("Could not download $imget from server");
	    }
	    $didsomething += $rval;
	}
    }

    if ($copyback) {
	if ($didsomething) {
	    # Tell image owner that it has been updated.
	    my $name = $image->pid() . "/" . $image->imagename();
	    my $project = $image->GetProject();
	    my $TO;
	    my $CC = "Bcc: " . $project->LogsEmailAddress();
	    my $FROM = $project->OpsEmailAddress();
	    my $versname = $image->versname();
	    
	    my $creator = User->Lookup($image->creator_idx());
	    if (defined($creator)) {
		$TO = $creator->email();
	    }
	    if ($PGENISUPPORT && defined($image->creator_urn())) {
		require GeniUser;
		my $geniuser = GeniUser->Lookup($image->creator_urn(), 1);
		if (defined($geniuser)) {
		    if (defined($TO)) {
			$CC = $CC . "\n" . "CC: " . $geniuser->email();
		    }
		    else {
			$TO = $geniuser->email();
		    }
		}
	    }
	    $TO = $TBLOGS
		if (!defined($TO));
	    $image->GetProject()->SendEmail($TO,
		    "Image imported: $versname",
		    "Image $name has been sucessfully imported from\n".
		    $image->imagefile_url(),
		    $FROM, $CC);
	}
	# Delete entry from the updates table while we are still locked.
	my $imageid = $image->imageid();
	DBQueryWarn("delete from image_updates ".
		    "where imageid='$imageid'");

	# Clear this to make the image gets posted.
	$image->ClearIMSReported();

	# Mark the updater.
	$image->Update({'updater_urn' => $updater_urn})
	    if (defined($updater_urn));

	# Tell the IMS about this new image. If this fails, the daemon
	# will take care of it. 
	system("$POSTIMAGEINFO -d $imageid");
    }
}
$image->Unlock()
    if ($image->GotLock());
exit(0);

#
# If the image has not been downloaded or if the hash has changed,
# get a new copy.
#
sub maybeGetImage($$)
{
    my ($image, $dodelta) = @_;
    my $imagefile = ($dodelta ?
		     $image->DeltaImageFile() : $image->FullImageFile());
    
    # Run as root to access /proj
    $EUID = $UID = 0;
720
    if (! -e $imagefile || !$image->ready() || $force) { 
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 826 827 828
	$EUID = $UID = $SAVEUID;

	if (DownLoadImage($image, $dodelta, $user, $group)) {
	    $image->Unlock();
	    return -1;
	}
	# For imagevalidate, this is wrong I think. 
	if ($dodelta) {
	    $image->SetDelta($dodelta);
	}
	# Update DB info. 
	my $versname = $image->versname();
	# Run as root to access /proj
	$EUID = $UID = 0;
	if (system("$IMAGEVALIDATE -u $versname")) {
	    # XXX should this be fatal?
	    print STDERR "Could not update DB info for $image\n";
	}
	$EUID = $UID = $SAVEUID;
	$image->MarkReady();
	# Its more important to know when we brought the new version in.
	if ($update) {
	    $image->MarkUpdate($user);
	}
	return 1;
    }
    $EUID = $UID = $SAVEUID;
    return 0;
}

#
# Create a new image descriptor. We have to munge the XML file a bit
# though and write it out.
#
sub CreateImage($$$$$)
{
    my ($url, $xmlparse, $user, $group, $imagename) = @_;
    my $alltypes = "-a";
    my $global   = 0;
    my @versions = ();
    my $metadata_url;

    print Dumper($xmlparse);

    #
    # If we are doing image versioning, and the origin has an image
    # history, make sure we can get the metadata for those versions.
    #
    if ($doprovenance &&
	exists($xmlparse->{"version_history"})) {
	foreach my $vers (keys(%{ $xmlparse->{"version_history"} })) {
	    my $val = $xmlparse->{"version_history"}->{$vers};
	    my $parse = FetchMetadata($val);
	    fatal("Could not metadata for version $vers")
		if (!defined($parse));
	    $versions[$vers] = $parse;
	}
	#
	# Sanity check that there are no gaps.
	#
	if (scalar(@versions) !=
	    scalar(keys(%{ $xmlparse->{"version_history"} }))) {
	    fatal("Inconsistent number of version history records");
	}
	#
	# Okay, if we have an image history, we actually have to first
	# create the base version, and then add all the other versions on
	# top of it, ending with the metadata we initially fetched.
	#
	if (scalar(@versions)) {
	    my $latest =
		$xmlparse->{'attribute'}->{"image_version"}->{'value'};
	    
	    $versions[$latest] = $xmlparse;
	    $xmlparse = $versions[0];
	}
    }

    $xmlparse->{'attribute'}->{"pid"} = {};
    $xmlparse->{'attribute'}->{"gid"} = {};
    $xmlparse->{'attribute'}->{"pid"}->{'value'} = $group->pid();
    $xmlparse->{'attribute'}->{"gid"}->{'value'} = $group->gid();

    #
    # If the origin provided an image_metadata_url, this is the non-version
    # specific URL which we can store locally in the images table, for users
    # that request it via that URL. This avoids a needless duplicate import.
    #
    if (exists($xmlparse->{'attribute'}->{"image_metadata_url"})) {
	my $url = $xmlparse->{'attribute'}->{"image_metadata_url"}->{'value'};

	if (! TBcheck_dbslot($url, "images", "metadata_url",
			     TBDB_CHECKDBSLOT_ERROR)) {
	    fatal("Bad image_metadata_url: $url");
	}
    }
    
    #
    # Look for a parent osid; this means we should set the type
    # to pcvm since the image is for a VM. Well, we also use this
    # for subnodes, but I am not going to worry about that case.
    #
    if (exists($xmlparse->{'attribute'}->{"def_parentosid"})) {
	#
	# If parent does not exist, then ignore with warning.
	# This can be set later via the web interface. 
	#
	my $posid  = $xmlparse->{'attribute'}->{"def_parentosid"}->{'value'};
829
	my $parent = OSImage->Lookup($posid);
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
	if (defined($parent)) {
	    $xmlparse->{'attribute'}->{"mtype_pcvm"} = {};
	    $xmlparse->{'attribute'}->{"mtype_pcvm"}->{'value'} = 1;
	}
	else {
	    delete($xmlparse->{'attribute'}->{"def_parentosid"});
	    print STDERR
		"*** Parent $posid does not exist, skipping parent.\n";
	    print STDERR
		"    You can set the parent later via the web interface.\n";
	}
    }

    # For setting the path below.
    if (exists($xmlparse->{'attribute'}->{"global"}) &&
	$xmlparse->{'attribute'}->{"global"}->{'value'}) {
	$global = 1;
    }

    #
    # We check to see if the imagename is already in use. Hopefully
    # not, but if not we have to make something up. Note that I am
    # not going to worry about concurrent attempts to create a descriptor
    # with the same name. 
    #
    if (defined($imagename)) {
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
    elsif (! exists($xmlparse->{'attribute'}->{"imagename"})) {
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = 
	    substr(TBGenSecretKey(), 0, 12);
    }
862
    elsif (OSImage->Lookup($group->pid(),
863 864 865 866 867 868
			 $xmlparse->{'attribute'}->{"imagename"}->{'value'})) {
	my $index = 1;
	my $imagename;
	do {
	    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
	    $imagename .= "_" . $index++;
869
	} while ($index < 100 && OSImage->Lookup($group->pid(), $imagename));
870 871 872 873 874 875 876 877 878 879 880 881 882
	if ($index >= 100) {
	    fatal("Could not generate a unique image name");
	}
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
    if ($debug) {
	print STDERR "Using imagename: $imagename\n";
    }
    # do not trust path coming in.
    if ($global && $user->IsAdmin()) {
	$xmlparse->{'attribute'}->{"path"}->{'value'} = "$TB/images/";
    }
883
    elsif ($group->pid() eq $group->gid() || $global) {
884 885 886
	$xmlparse->{'attribute'}->{"path"}->{'value'} =
	    "$TBPROJ_DIR/" . $group->pid() . "/images/";
    }
887 888 889 890
    else {
	$xmlparse->{'attribute'}->{"path"}->{'value'} =
	    "$TBPROJ_DIR/" . $group->pid() . "/" . $group->gid() . "/images/";
    }
891
    if ($DOIMAGEDIRS) {
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
	$xmlparse->{'attribute'}->{"path"}->{'value'} .= "${imagename}/";
    }
    else {
	$xmlparse->{'attribute'}->{"path"}->{'value'} .= "${imagename}.ndz";
    }
    
    #
    # Generate a new XML description to feed into newimageid.
    #
    $xmlparse->{'attribute'}->{"imagefile_url"}->{'value'} =
	uri_escape($xmlparse->{'attribute'}->{"imagefile_url"}->{'value'});
    #
    # Old servers do not provide a metadata url in the blob, so we
    # have to set it. This is not ideal, since we do not know if the
    # URL we have is the version specific or the non-version specific.
    #
    if (!exists($xmlparse->{'attribute'}->{"metadata_url"})) {
	$xmlparse->{'attribute'}->{"metadata_url"}->{'value'} =
	    uri_escape($url);
    }
    # We need this to lookup the new image. 
    $metadata_url =
	uri_unescape($xmlparse->{'attribute'}->{"metadata_url"}->{'value'});

    my $newxml = "";
    foreach my $key (keys(%{ $xmlparse->{'attribute'} })) {
	# Skip these, we handle them elsewhere.
	next
	    if ($key =~
		/^(image_metadata_url|havefull|havedelta|version_history)$/);

	my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
	$newxml .=
	    "<attribute name=\"$key\"><value>$value</value></attribute>\n";
    }
    $newxml = "<image>$newxml</image>";
    if ($debug) {
	print STDERR "$newxml\n";
    }
    # Verify first, Use skip admin checks option.
    open(NEW, "| $NEWIMAGE_EZ $alltypes -f -s -v -")
	or fatal("Cannot start $NEWIMAGE_EZ");
    print NEW $newxml;
    if (!close(NEW)) {
	print STDERR "$newxml\n";
	fatal("Image xml did not verify");
    }
    return undef
	if ($verify);
    
    open(NEW, "| $NEWIMAGE_EZ $alltypes -f -s -")
	or fatal("Cannot start $NEWIMAGE_EZ");
    print NEW $newxml;
    if (!close(NEW)) {
	print STDERR "$newxml\n";
	fatal("Could not create new image from xml");
    }

950
    my $image = OSImage->LookupByURL($metadata_url);
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    if (!defined($image)) {
	fatal("Could not lookup new image for $url");
    }

    #
    # If the origin provided an image_metadata_url, this is the non-version
    # specific URL which we can store locally in the images table, for users
    # that request it via that URL. This avoids a needless duplicate import.
    #
    if (exists($xmlparse->{'attribute'}->{"image_metadata_url"})) {
	my $url = $xmlparse->{'attribute'}->{"image_metadata_url"}->{'value'};
	$image->SetImageMetadataURL($url);
    }
    
    #
    # We are going to mark as released but not ready, since this *is* the
    # image we want people to run, but we still have to actually get it.
    #
    $image->MarkReleased();

    #
    # Store this in case we need it later for -g option.
    #
    $image->_havedelta(0);
    $image->_havefull(0);

    if (exists($xmlparse->{'attribute'}->{"havefull"})) {
	$image->_havefull($xmlparse->{'attribute'}->{"havefull"}->{'value'});
    }
    if (exists($xmlparse->{'attribute'}->{"havedelta"})) {
	$image->_havedelta($xmlparse->{'attribute'}->{"havedelta"}->{'value'});
    }

    #
    # Now we can create the image history. All of these images are also
    # marked as released but not ready. Skip version zero of course, since
    # that is what we just created.
    #
    # @versions will be empty if not doing provenance, see above.
    #
    if (scalar(@versions)) {
	for (my $i = 1; $i < scalar(@versions); $i++) {
	    my $xmlparse = $versions[$i];
	    my $clone = CloneFromMetadata($image, $xmlparse, $user);
	    if (!defined($clone)) {
		$image->Unlock();
		fatal("Could not clone image descriptor $image");
	    }
	    $image = $clone;
	}
    }
1002 1003 1004 1005 1006 1007 1008 1009

    #
    # newimageid_ez is not setuid, so it cannot create the new directory.
    #
    if ($image->CreateImageDir()) {
	$image->Unlock();
	fatal("Could not create image directory");
    }
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    return $image;
}

#
# Clone an image with additional info from the parsed metadata.
#
sub CloneFromMetadata($$$)
{
    my ($image, $xmlparse, $user) = @_;
    
    my $clone = $image->NewVersion($user, $image, undef);
    return undef
	if (!defined($clone));

    #
    # So, here is a bit of a quandry. We want this new version of the
    # image to be the released version (for mapping), even though we
    # do not have image file yet. So we will force the image to be
    # released even though it is not "ready" yet. This will happen
    # to each version including the last version (the one we are really
    # trying to get to). 
    #
    $clone->MarkReady();
    $clone->Release();
    $clone->ClearReady();

    #
    # Store this in case we need it later for -g option.
    #
    $clone->_havedelta(0);
    $clone->_havefull(0);

    if (exists($xmlparse->{'attribute'}->{"havefull"})) {
	$clone->_havefull($xmlparse->{'attribute'}->{"havefull"}->{'value'});
    }
    if (exists($xmlparse->{'attribute'}->{"havedelta"})) {
	$clone->_havedelta($xmlparse->{'attribute'}->{"havedelta"}->{'value'});
    }

    UpdateImageFromMetadata($clone, $xmlparse) == 0
	or return undef;
	
    return $clone;
}

#
# Update descriptor stuff from the metadata, typically after we have
# created a new version (clone) of the descriptor.
#
sub UpdateImageFromMetadata($$)
{
    my ($image, $xmlparse) = @_;
    
1063 1064
    my @imslots = ("imagefile_url", "metadata_url", "hash", "deltahash",
		   "size", "deltasize");
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    foreach my $key (@imslots) {
	next
	    if (!exists($xmlparse->{'attribute'}->{$key}));
		
	my $value = $xmlparse->{'attribute'}->{$key}->{'value'};
	if (! TBcheck_dbslot($value, "images",
			     $key, TBDB_CHECKDBSLOT_ERROR)) {
	    print STDERR
		"Illegal value for $key: " . TBFieldErrorString() . "\n";
	    return -1;
	}
	$image->Update({$key => $value});
    }
    my @osslots = ("description", "version", "osfeatures");
    foreach my $key (@osslots) {
	next
	    if (!exists($xmlparse->{'attribute'}->{$key}));
		
	my $value = $xmlparse->{'attribute'}->{$key}->{'value'};
	if (! TBcheck_dbslot($value, "os_info",
			     $key, TBDB_CHECKDBSLOT_ERROR)) {
	    print STDERR
		"Illegal value for $key: " . TBFieldErrorString() . "\n";
	    return -1;
	}
1090
	$image->Update({$key => $value});
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    }
    return 0;
}

#
# Download the image file, which can be a delta. 
#
sub DownLoadImage($$$$)
{
    my ($image, $dodelta, $user, $group) = @_;
    my $image_url = uri_unescape($image->imagefile_url());
    my $localfile = ($dodelta ?
		     $image->DeltaImageFile() :
		     $image->FullImageFile()) . ".new";
    $image_url .= "&delta=1" if ($dodelta);

    if (FetchImageFile($image_url, $localfile)) {
	return -1;
    }

    #
    # Verify the hash which was created by FetchImageFile().
    #
    my $newhashfile = $localfile . ".sha1";
    print "Verifying the hash ...\n";
    my $filehash = `cat $newhashfile`;
    if ($?) {
	print STDERR "Could not read sha1 hash file $newhashfile\n";
	return -1;
    }
    chomp($filehash);
    if ($filehash =~ /^SHA1.*= (\w*)$/) {
	$filehash = $1;
    }
    else {
	print STDERR "Could not parse the sha1 hash: '$filehash'\n";
	return -1;
    }
    if ($filehash ne ($dodelta ? $image->deltahash() : $image->hash())) {
	print STDERR "sha1 hash of new file did not match\n";
	return -1;
    }

    #
    # Use imagedump to verify the ndz file.
    #
    print "Verifying ndz file format ...\n";
    system("$IMAGEDUMP $localfile");
    if ($?) {
	return -1;
    }
    return 0
	if ($verify);

    #
    # Now rename the image files and update the hash file.
    #
    my $hashfile = ($dodelta ?
1149
		    $image->DeltaImageSHA1File() : $image->FullImageSHA1File());
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 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 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 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 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 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
    my $ndzfile  = ($dodelta ?
		    $image->DeltaImageFile() : $image->FullImageFile());
    unlink($hashfile)
	if (-e $hashfile);
    system("/bin/mv -f $newhashfile $hashfile");
    if ($?) {
	return -1;
    }
    if (-e $ndzfile) {
	system("/bin/mv -f $ndzfile ${ndzfile}.old");
	if ($?) {
	    return -1;
	}
    }
    system("/bin/mv -f $localfile $ndzfile");
    if ($?) {
	return -1;
    }

    #
    # Try to download a sig file. We have to accept that this might
    # fail, which is okay since Mike says we can generate a new one,
    # it just takes a while to do.
    #
    FetchSigFile($image, $dodelta);
    return 0;
}

#
# Fetch a file.
#
sub FetchImageFile($$)
{
    my ($url, $localfile) = @_;
    my $safe_url  = User::escapeshellarg($url);
    my $user_uid  = $user->uid();
    
    #
    # Build up a new command line to do the fetch on ops
    # But no reason to do this if an admin, which is important
    # when the image is going into /usr/testbed/images.
    #
    if (!$user->IsAdmin()) {
	my $cmdargs = "$TB/bin/fetchtar.proxy -h -u $user_uid";
	my $glist = `/usr/bin/id -G $user_uid`;
	if ($glist =~ /^([\d ]*)$/) {
	    $glist = join(",", split(/\s+/, $1));
	}
	else {
	    print STDERR "Unexpected results from 'id -G $user': $glist\n";
	    return -1;
	}
	$cmdargs .= " -g '$glist' \"$safe_url\" $localfile";

	print "Downloading $url ...\n";
	if ($debug) {
	    print "$cmdargs\n";
	}
	$EUID = $UID = 0;
	system("sshtb -host $CONTROL $cmdargs ");
	if ($?) {
	    $EUID = $UID = $SAVEUID;
	    print STDERR "Fetch of image file failed\n";
	    return -1;
	}
	$UID = $SAVEUID;
    }
    else {
	print "Downloading $url ...\n";
	
	if (! open(GET, "| nice -15 $WGET --no-check-certificate ".
		   "--timeout=30 --waitretry=30 --retry-connrefused ".
		   "-q -O $localfile -i -")) {
	    print STDERR "Cannot start $WGET\n";
	    return -1;
	}
	print GET "$url\n";
	return -1
	    if (!close(GET));

	system("$SHA1 $localfile > ${localfile}.sha1");
	if ($?) {
	    print STDERR "Could not generate sha1 hash of $localfile\n";
	    return -1;
	}
    }
    return 0;
}

#
# Fetch the metadata from the provided URL. Return the XML parse,
#
sub FetchMetadata($)
{
    my ($url) = @_;
    $url .= "&clientversion=" . $METADATA_CLIENTVERSION;

    # We know this is valid, but must taint check anyway for shell command.
    if ($url =~/^(.*)$/) {
	$url = $1;
    }
    my $safe_url = User::escapeshellarg($url);
    my $xml  = "";
    my $opts = ($debug ? "" : "-q");
    my $cmd  = "$WGET $opts --no-check-certificate -O - $safe_url ";

    if ($debug) {
	print "$cmd\n";
    }
    if (open(META, "$cmd |")) {
	while (<META>) {
	    $xml .= $_;
	}
	close(META);
    }
    else {
	print STDERR "Could not read metadata from $url\n";
	return undef;
    }

    if ($xml eq "") {
	print STDERR "Failed to get metadata from $url\n";
	return undef;
    }
    my $xmlparse = eval { XMLin($xml,
				VarAttr => 'name',
				ContentKey => '-content',
				SuppressEmpty => undef); };
    if ($@) {
	print STDERR "$@\n";
	return undef;
    }
    if ($debug) {
	print STDERR Dumper($xmlparse);
    }

    #
    # Sanity checks; it must have a hash and a url inside. We let
    # newimageid do the rest of the checks though.
    #
    if (!((exists($xmlparse->{'attribute'}->{"hash"}) &&
	   $xmlparse->{'attribute'}->{"hash"}->{'value'} =~ /^\w{10,}$/) ||
	  (exists($xmlparse->{'attribute'}->{"deltahash"}) &&
	   $xmlparse->{'attribute'}->{"deltahash"}->{'value'} =~ /^\w{10,}$/))){
	print STDERR "Invalid hash in metadata\n";
	return undef;
    }
    if (! exists($xmlparse->{'attribute'}->{"imagefile_url"})) {
	print STDERR "Invalid imagefile url in metadata\n";
	return undef;
    }
    # Silly taint check.
    if (exists($xmlparse->{'attribute'}->{"hash"})) {
	if ($xmlparse->{'attribute'}->{"hash"}->{'value'} =~ /^(.*)$/) {
	    $xmlparse->{'attribute'}->{"hash"}->{'value'} = $1;	    
	}
    }
    else {
	if ($xmlparse->{'attribute'}->{"deltahash"}->{'value'} =~ /^(.*)$/) {
	    $xmlparse->{'attribute'}->{"deltahash"}->{'value'} = $1;	    
	}
    }
    return $xmlparse;
}

#
# Fetch sig file.
#
sub FetchSigFile($$)
{
    my ($image,$dodelta) = @_;
    my $image_url  = uri_unescape($image->imagefile_url()) . "&sigfile=1";
    my $localfile;
    my $sigfile;

    if ($dodelta) {
	$localfile = $image->DeltaImageSigFile() . ".new";
	$sigfile   = $image->DeltaImageSigFile();
	$image_url .= "&delta=1";
    }
    else {
	$localfile = $image->FullImageSigFile() . ".new";
	$sigfile   = $image->FullImageSigFile();
    }
    
    if (! FetchImageFile($image_url, $localfile)) {
	system("/bin/mv -f $localfile $sigfile");
	# Do not need this.
	unlink("${localfile}.sha1")
	    if (-e "${localfile}.sha1");
    }
    return 0;
}

sub fatal($)
{
    my ($mesg) = @_;

    $image->Unlock()
	if (defined($image) && $image->GotLock());

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}