image_import.in 26 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2010-2018 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
# 
# {{{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/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33 34 35
#
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()
{
36
    print("Usage: image_import [-d] [-v] [-u <user>] [-g] [-p pid] ".
37
	  "[-i name] <url>\n");
38
    print("       image_import [-d] [-u <user>] -r [-c] <imageid>\n");
39 40 41 42 43
    print("Options:\n");
    print(" -d      - Turn on debugging\n");
    print(" -v      - Verify XML description only\n");
    print(" -g      - Download image after creating descriptor\n");
    print(" -u uid  - Create image as user instead of caller\n");
44 45
    print(" -p pid  - Create image in the specified project.\n".
	  "           Defaults to emulab-ops.\n");
46 47 48
    print(" -i name - Use name for imagename.\n".
	  "           Defaults to name in the desciptor\n");
    print(" -r      - Refresh (update ndz file) imported image.\n");
49
    print(" -s      - With -r just update the sig file\n");
50
    print(" -c      - With -r update ndz file using the updates table\n");
51 52
    exit(-1);
}
53
my $optlist = "dvu:p:gi:IrscR";
54 55 56 57
my $debug   = 0;
my $verify  = 0;
my $getimage= 0;
my $update  = 0;
58
my $dosig   = 0;
59
my $force   = 0;
60
my $copyback= 0;
61 62
my $user;
my $group;
63
my $image;
64
my $imagename;
65
my $copyback_urn;
66
my $copyback_credential;
67 68 69 70 71 72

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
73
my $TBLOGS      = "@TBLOGSEMAIL@";
74 75 76 77 78 79 80 81 82
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";
83
my $DD		= "/bin/dd";
84
my $SAVEUID	= $UID;
85
my $IMAGEVALIDATE = "$TB/sbin/imagevalidate";
86
my $DELETEIMAGE   = "$TB/sbin/delete_image";
87
my $POSTIMAGEINFO = "$TB/sbin/protogeni/postimagedata";
88
my $SECUREIMAGEGET= "$TB/sbin/protogeni/secureimageget";
89
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
90
my $DOIMAGEDIRS   = @IMAGEDIRECTORIES@;
91
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
92
my $doprovenance  = 0;
93

94 95 96 97 98
#
# 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.
#
99
my $METADATA_CLIENTVERSION = 3;
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
#
# 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;
125
use emutil;
126
use EmulabConstants;
127
use EmulabFeatures;
128 129 130 131
use libtestbed;
use User;
use Project;
use Group;
132
use OSImage;
133 134 135 136 137 138 139

# Locals;
my $url;

# Protos
sub fatal($);
sub FetchMetadata($);
140
sub CreateImage($$$$$);
141
sub DownLoadImage($$$$);
142
sub FetchImageFile($$$);
143
sub FetchSigFile($);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

#
# 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;
}
168 169 170
if (defined($options{"s"})) {
    $dosig = 1;
}
171
if (defined($options{"i"})) {
172 173 174 175
    $imagename = $options{i};
}
if (defined($options{"r"})) {
    $update   = 1;
176 177 178
    if (defined($options{"c"})) {
	$copyback = 1;
    }
179
}
180
if (defined($options{"R"})) {
181 182
    $update = 1;
    $force  = 1;
183 184 185
    if (defined($options{"c"})) {
	$copyback = 1;
    }
186
}
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
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));
    }
}
203 204 205 206 207
else {
    $group = Group->Lookup(TBOPSPID(), TBOPSPID());
    fatal("Error getting project group for " . TBOPSPID())
	if (!defined($group));
}
208 209 210 211 212 213 214 215 216 217 218 219

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

if ($update) {
    usage()
	if (!@ARGV);

220
    $image = OSImage->Lookup(shift(@ARGV));
221 222 223
    if (!defined($image)) {
	fatal("Image descriptor does not exist");
    }
224
    if ($copyback) {
225 226
	my ($updater_uid,$updater_idx);
	
227 228 229 230 231 232 233 234 235 236 237 238
	#
	# 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 =
239
	    DBQueryWarn("select * from image_updates ".
240 241 242 243 244 245 246 247 248 249
			"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);
	}
250 251 252 253 254
	my $row = $query_result->fetchrow_hashref();
	$url          = $row->{'url'};
	$updater_uid  = $row->{'updater'};
	$updater_idx  = $row->{'updater_idx'};
	$copyback_urn = $row->{'updater_urn'};
255 256 257 258 259 260 261 262 263 264 265
	if ($row->{'credential_string'} ne "") {
	    require GeniCredential;
	    
	    $copyback_credential =
		GeniCredential->CreateFromSigned($row->{'credential_string'});
	    if (!defined($copyback_credential)) {
		print STDERR "Image credential is not valid\n";
		$image->Unlock();
		exit(-1);
	    }
	}
266 267 268 269 270 271 272 273 274 275

	#
	# 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);
276 277 278 279 280
	    # Ick, setgroups skips nonlocal users, so user does not have
	    # permission to do this on ops. Needs thought.
	    if ($user->IsNonLocal()) {
		$user = undef;
	    }
281 282 283 284 285 286 287 288 289
	}
	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);
	}
290 291 292
	$EUID = 0;
	$UID  = $SAVEUID = $user->unix_uid();
	$EUID = $UID;
293 294 295 296 297 298
    }
    else {
	if (!defined($image->metadata_url())) {
	    fatal("Not an imported image");
	}
	$url = $image->metadata_url();
299 300 301 302 303 304 305
    }

    # 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 $image");
    }
306 307 308 309 310 311
    # Need this below.
    if ($WITHPROVENANCE && !$image->noversioning()) {
	$doprovenance =
	    EmulabFeatures->FeatureEnabled("ImageProvenance",
					   undef, $image->GetGroup());
    }
312 313 314
}
else {
    usage()
315
	if (! (@ARGV && defined($group)));
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

    $url = $ARGV[0];
    # 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 in $group");
    }
}

my $xmlparse = FetchMetadata($url);

#
# 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,}$/)) {
    fatal("Invalid hash in metadata");
}
if (! exists($xmlparse->{'attribute'}->{"imagefile_url"})) {
    fatal("Invalid imagefile url in metadata");
}
344 345 346 347 348
my $newhash = $xmlparse->{'attribute'}->{"hash"}->{'value'};
# Silly taint check.
if ($newhash =~/^(.*)$/) {
    $newhash = $1;
}
349 350 351 352 353
# Save off the origin path.
my $origin_path;
if (exists($xmlparse->{'attribute'}->{"path"})) {
    $origin_path = $xmlparse->{'attribute'}->{"path"}->{"value"};
}
354 355 356 357 358 359 360 361 362

#
# See if we already have an image in the DB for this URL.
# If not, we have to create it.
#
# Need to watch for two experiments causing this image to
# get created at the same time. It would be pretty silly,
# but users are users ... 
#
363
if (!$update) {
364 365
    # New mysal 5.7 limit of 64 chars on locks. Use the uuid.
    my $lockname;
366 367 368 369
    if (length($url) < 64) {
	$lockname = $1;
    }
    elsif ($url =~ /uuid=([-\w]+)$/) {
370 371 372 373 374 375
	$lockname = $1;
    }
    else {
	fatal("Bad URL, cannot find the uuid in it");
    }
    my $query_result = DBQueryWarn("select GET_LOCK('$lockname', 120)");
376 377 378 379
    if (!$query_result ||
	!$query_result->numrows) {
	fatal("Could not get the SQL lock for a long time!");
    }
380
    $image = OSImage->LookupByURL($url);
381 382 383
    if (!defined($image)) {
	$image = CreateImage($url, $xmlparse, $user, $group, $imagename);
    }
384
    DBQueryWarn("select RELEASE_LOCK('$lockname')");
385 386 387 388
}
exit(0)
    if ($verify);

389
if ($update || $getimage) {
390 391 392 393 394
    #
    # 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.
    #
395
    if (!$copyback && $image->Lock()) {
396 397 398 399 400 401 402 403 404 405 406
	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");
	}
    }
407 408 409 410 411 412
}
#
# If updating, see if we need a new version of the image descriptor.
#
if ($update && $newhash ne $image->hash()) {
    if ($doprovenance) {
413
	#
414 415
	# This will include unreleased images (in image_versions, but
	# not the one pointed to by the images table). 
416
	#
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
	$image = $image->LookupMostRecent();
	if (!defined($image)) {
	    $image->Unlock();
	    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 = $image->NewVersion($user, undef, undef);
	    if (!defined($clone)) {
		$image->Unlock();
		fatal("Could not clone image descriptor $image");
	    }
	    $image = $clone;

432 433 434 435 436 437 438 439 440 441
	    #
	    # 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.
	    #
	    $image->MarkReady();
	    $image->Release();
	    $image->ClearReady();
442
	}
443 444
    }
    # Update these in the descriptor.
445
    my @slots = ("imagefile_url", "origin_name");
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    foreach my $key (@slots) {
	next
	    if (!exists($xmlparse->{'attribute'}->{$key}));
		
	my $value = $xmlparse->{'attribute'}->{$key}->{'value'};
	if (! TBcheck_dbslot($value, "images",
			     $key, TBDB_CHECKDBSLOT_ERROR)) {
	    $image->Unlock();
	    fatal("Illegal value for $key: " . TBFieldErrorString());
	}
	$image->Update({$key => $value});
    }
}
#
# If the image has not been downloaded or if the hash has changed,
# get a new copy.
#
if ($getimage) {
464 465 466 467 468
    my $downloaded = 0;
    my $versname = $image->versname();

    if ($image->format() eq 'docker') {
	use libimageops;
469

470 471
	libimageops::setDebug($debug);
	my %args = (
472
	    'origin_path' => $origin_path,
473 474 475 476 477 478
	    'downloaded_ref' => \$downloaded,'force' => $force,
	    'newhash' => $newhash,'locked' => 1 );
	my $iops = libimageops::Factory("image" => $image);
	my ($rc,$msg) = $iops->ImportImageContent($image,\%args);
	if ($rc) {
	    print STDERR "Error: $msg\n";
479 480 481
	    $image->Unlock();
	    exit(1);
	}
482 483
    }
    else {
484 485
	# Run as root to access /proj
	$EUID = $UID = 0;
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
	if (! -e $image->FullImageFile() || $newhash ne $image->hash() || $force) {
	    # Make sure the path directory exists.
	    if ($image->CreateImageDir()) {
		$image->Unlock();
		exit(1);
	    }
	    $EUID = $UID = $SAVEUID;

	    if (DownLoadImage($image, $newhash, $user, $group)) {
		$image->Unlock();
		exit(1);
	    }
	    # Update DB info. 
	    # 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;

	    $downloaded = 1;
508
	}
509 510 511
    }

    if ($downloaded) {
512 513
	$image->MarkReady();
	$image->Release();
514
	# Its more important to know when we brought the new version in.
515
	if ($update) {
516 517
	    $image->MarkUpdate($user);
	}
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
	if ($copyback) {
	    # 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 $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);
	}
550
    }
551
    $EUID = $UID = $SAVEUID;
552 553 554 555 556 557 558 559 560
    if ($copyback) {
	# 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();

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

565 566 567 568
	# Tell the IMS about this new image. If this fails, the daemon
	# will take care of it. 
	system("$POSTIMAGEINFO -d $imageid");
    }
569
}
570 571 572 573
elsif ($update && $dosig) {
    FetchSigFile($image) == 0
	or exit(1);
}
574 575 576
else {
    print "Not downloading image ... add -g option\n";
}
577 578 579
if ($update || $getimage) {
    $image->Unlock();
}
580 581 582 583 584 585
exit(0);

#
# Create a new image descriptor. We have to munge the XML file a bit
# though and write it out.
#
586
sub CreateImage($$$$$)
587
{
588
    my ($url, $xmlparse, $user, $group, $imagename) = @_;
589
    my $alltypes = "-a";
590
    my $global   = 0;
591 592 593 594 595 596

    # We do not care about or handle these here.
    foreach my $key ("metadata_url", "havefull", "havedelta") {
	delete($xmlparse->{'attribute'}->{$key})
	    if (exists($xmlparse->{'attribute'}->{$key}));
    }
597 598 599 600 601 602 603 604 605 606 607
    
    $xmlparse->{'attribute'}->{"pid"} = {};
    $xmlparse->{'attribute'}->{"gid"} = {};
    $xmlparse->{'attribute'}->{"pid"}->{'value'} = $group->pid();
    $xmlparse->{'attribute'}->{"gid"}->{'value'} = $group->gid();

    #
    # 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.
    #
608
    if (exists($xmlparse->{'attribute'}->{"def_parentosid"})) {
609 610 611 612 613
	#
	# 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'};
614
	my $parent = OSImage->Lookup($posid);
615 616 617 618 619 620 621 622 623 624 625
	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";
	}
626 627
    }

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

634 635 636 637 638 639
    #
    # 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. 
    #
640 641 642 643
    if (defined($imagename)) {
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
    elsif (! exists($xmlparse->{'attribute'}->{"imagename"})) {
644 645 646
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = 
	    substr(TBGenSecretKey(), 0, 12);
    }
647
    elsif (OSImage->Lookup($group->pid(),
648 649 650 651 652 653
			 $xmlparse->{'attribute'}->{"imagename"}->{'value'})) {
	my $index = 1;
	my $imagename;
	do {
	    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
	    $imagename .= "_" . $index++;
654
	} while ($index < 100 && OSImage->Lookup($group->pid(), $imagename));
655 656 657
	if ($index >= 100) {
	    fatal("Could not generate a unique image name");
	}
658 659 660 661 662
	# This can happen if the munged name is too long. 
	if (! TBcheck_dbslot($imagename, "images",
			     "imagename", TBDB_CHECKDBSLOT_ERROR)) {
	    $imagename = substr(TBGenSecretKey(), 0, 12);
	}
663 664
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
665
    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
666 667 668 669
    if ($debug) {
	print STDERR "Using imagename: $imagename\n";
    }
    # do not trust path coming in.
670
    if ($global && $user->IsAdmin()) {
671
	$xmlparse->{'attribute'}->{"path"}->{'value'} = "$TB/images/";
672 673 674
    }
    else {
	$xmlparse->{'attribute'}->{"path"}->{'value'} =
675 676 677
	    "$TBPROJ_DIR/" . $group->pid() . "/images/";
    }
    if ($DOIMAGEDIRS) {
Leigh Stoller's avatar
Leigh Stoller committed
678
	$xmlparse->{'attribute'}->{"path"}->{'value'} .= "${imagename}/";
679 680
    }
    else {
Leigh Stoller's avatar
Leigh Stoller committed
681
	$xmlparse->{'attribute'}->{"path"}->{'value'} .= "${imagename}.ndz";
682
    }
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    
    #
    # Generate a new XML description to feed into newimageid.
    #
    $xmlparse->{'attribute'}->{"imagefile_url"}->{'value'} =
	uri_escape($xmlparse->{'attribute'}->{"imagefile_url"}->{'value'});
    $xmlparse->{'attribute'}->{"metadata_url"}->{'value'} = uri_escape($url);

    my $newxml = "";
    foreach my $key (keys(%{ $xmlparse->{'attribute'} })) {
	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.
702
    open(NEW, "| $NEWIMAGE_EZ $alltypes -f -s -v -")
703 704 705 706 707 708 709 710 711
	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);
    
712
    open(NEW, "| $NEWIMAGE_EZ $alltypes -f -s -")
713 714 715 716 717 718 719
	or fatal("Cannot start $NEWIMAGE_EZ");
    print NEW $newxml;
    if (!close(NEW)) {
	print STDERR "$newxml\n";
	fatal("Could not create new image from xml");
    }

720
    my $image = OSImage->LookupByURL($url);
721 722 723
    if (!defined($image)) {
	fatal("Could not lookup new image for $url");
    }
724 725 726 727
    #
    # 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.
    #
728
    $image->MarkReleased();
729 730 731 732 733 734 735 736
    return $image;
}

#
# Download the image file. 
#
sub DownLoadImage($$$$)
{
737
    my ($image, $newhash, $user, $group) = @_;
738
    my $localfile = $image->FullImageFile() . ".new";
739

740
    if (FetchImageFile($image, "", $localfile)) {
741
	return -1;
742 743 744
    }

    #
745
    # Verify the hash which was created by FetchImageFile().
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
    #
    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 $newhash) {
	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.
    #
781 782
    my $hashfile = $image->FullImageSHA1File();
    my $ndzfile  = $image->FullImageFile();
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
    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;
    }
799 800 801 802 803 804

    #
    # 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.
    #
805
    FetchSigFile($image);
806 807 808
    return 0;
}

809 810 811
#
# Fetch a file.
#
812
sub FetchImageFile($$$)
813
{
814 815
    my ($image, $urlarg, $localfile) = @_;
    my $url       = uri_unescape($image->imagefile_url()) . $urlarg;
816
    my $safe_url  = User::escapeshellarg($url);
817
    my $user_uid  = $user->uid();
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847

    #
    # If we have a credential, we use the secure image download path,
    # which at the moment only runs on boss. And only for datasets.
    #
    if (defined($copyback_credential) || $image->HasCredential()) {
	my $credarg = "";
	
	if ($copyback_credential) {
	    # This will auto delete.
	    my $credfile = $copyback_credential->WriteToFile();
	    $credarg = "-c " . $credfile;
	}
	# We need to operate as the user since we are not calling
	# over to ops.
	$user->FlipTo($image->GetProject()->unix_gid());
	
	my $cmdargs = "$SECUREIMAGEGET $credarg -o $localfile ".
	    $image->versname();

	system($cmdargs);
	return -1
	    if ($?);

	system("$SHA1 $localfile > ${localfile}.sha1");
	if ($?) {
	    print STDERR "Could not generate sha1 hash of $localfile\n";
	    return -1;
	}
    }
848 849 850 851 852
    #
    # 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.
    #
853
    elsif (!$user->IsAdmin()) {
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
	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;
873 874 875 876 877
	    if ($urlarg =~ /sigfile=1/) {
		print STDERR "WARNING: Fetch of image signature file failed\n";
	    } else {
		print STDERR "Fetch of image file failed\n";
	    }
878 879 880 881
	    return -1;
	}
	$UID = $SAVEUID;
    }
882 883 884 885 886 887 888 889 890 891 892 893
    elsif ($url =~ /^file:\/\/(.*)/) {
	system("/bin/cp -fp '$1' $localfile");
	if ($?) {
	    print STDERR "Could not copy $1 to $localfile\n";
	    return -1;
	}
	system("$SHA1 $localfile > ${localfile}.sha1");
	if ($?) {
	    print STDERR "Could not generate sha1 hash of $localfile\n";
	    return -1;
	}
    }
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    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;
	}
    }
913
    return 0;
914 915
}

916 917 918 919 920 921 922 923
#
# Fetch the metadata from the provided URL. Return the XML parse,
#
sub FetchMetadata($)
{
    my ($url) = @_;
    my $xml  = "";

924 925 926 927 928 929 930
    if ($url =~ /^file:\/\/(.*)/) {
	open(META, $1) or
	    fatal("Could not open $1: $!");
	while (<META>) {
	    $xml .= $_;
	}
	close(META);
931
    }
932 933 934 935 936
    else {
	$url .= "&clientversion=" . $METADATA_CLIENTVERSION;
	my $safe_url = User::escapeshellarg($url);
	my $opts = ($debug ? "" : "-q");
	my $cmd  = "$WGET $opts --no-check-certificate -O - $safe_url ";
937
	$cmd .= "| $DD 2>/dev/null bs=1 count=5k ";
938 939 940 941 942 943 944 945 946 947 948

	if ($debug) {
	    print "$cmd\n";
	}
	open(META, "$cmd |") or
	    fatal("Could not fetch metadata from $url");
	while (<META>) {
	    $xml .= $_;
	}
	close(META)
	    or fatal("Could not read metadata from $url");
949 950 951 952 953 954 955 956 957 958
    }

    if ($xml eq "") {
	fatal("Failed to get metadata from $url");
    }

    my $xmlparse = eval { XMLin($xml,
				VarAttr => 'name',
				ContentKey => '-content',
				SuppressEmpty => undef); };
959 960 961 962
    if ($@) {
	print STDERR $xml . "\n";
	fatal($@);
    }
963 964 965 966 967 968 969 970 971 972
    if ($debug) {
	print STDERR Dumper($xmlparse);
    }

    #
    # We are going to let newimageid do the real checking.
    #
    return $xmlparse;
}

973 974 975 976 977 978
#
# Fetch sig file.
#
sub FetchSigFile($)
{
    my ($image) = @_;
979 980
    my $localfile  = $image->FullImageSigFile() . ".new";
    my $sigfile    = $image->FullImageSigFile();
981
    
982
    if (! FetchImageFile($image, "&sigfile=1", $localfile)) {
983 984 985 986
	system("/bin/mv -f $localfile $sigfile");
	# Do not need this.
	unlink("${localfile}.sha1")
	    if (-e "${localfile}.sha1");
987 988
    } else {
	unlink($localfile);
989 990 991 992
    }
    return 0;
}

993 994 995 996
sub fatal($)
{
    my ($mesg) = @_;

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

1000 1001 1002 1003 1004
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}