image_import.in 24.9 KB
Newer Older
Leigh B Stoller's avatar
Leigh B Stoller committed
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
# 
# {{{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/>.
# 
# }}}
Leigh B Stoller's avatar
Leigh B Stoller committed
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");
Leigh B Stoller's avatar
Leigh B Stoller committed
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");
Leigh B Stoller's avatar
Leigh B Stoller committed
51
52
    exit(-1);
}
53
my $optlist = "dvu:p:gi:IrscR";
Leigh B Stoller's avatar
Leigh B Stoller committed
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;
Leigh B Stoller's avatar
Leigh B Stoller committed
61
62
my $user;
my $group;
63
my $image;
64
my $imagename;
65
my $copyback_urn;
66
my $copyback_credential;
Leigh B Stoller's avatar
Leigh B Stoller committed
67
68
69
70
71
72

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
73
my $TBLOGS      = "@TBLOGSEMAIL@";
Leigh B Stoller's avatar
Leigh B Stoller committed
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";
Leigh B Stoller's avatar
Leigh B Stoller committed
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@;
Leigh B Stoller's avatar
Leigh B Stoller committed
90
my $DOIMAGEDIRS   = @IMAGEDIRECTORIES@;
91
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
92
my $doprovenance  = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
93

Leigh B Stoller's avatar
Leigh B Stoller committed
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;
Leigh B Stoller's avatar
Leigh B Stoller committed
100

Leigh B Stoller's avatar
Leigh B Stoller committed
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;
Leigh B Stoller's avatar
Leigh B Stoller committed
128
129
130
131
use libtestbed;
use User;
use Project;
use Group;
132
use OSImage;
Leigh B Stoller's avatar
Leigh B Stoller committed
133
134
135
136
137
138
139

# Locals;
my $url;

# Protos
sub fatal($);
sub FetchMetadata($);
140
sub CreateImage($$$$$);
Leigh B Stoller's avatar
Leigh B Stoller committed
141
sub DownLoadImage($$$$);
142
sub FetchImageFile($$$);
143
sub FetchSigFile($);
Leigh B Stoller's avatar
Leigh B Stoller committed
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;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
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;
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
179
}
180
if (defined($options{"R"})) {
181
182
    $update = 1;
    $force  = 1;
183
184
185
    if (defined($options{"c"})) {
	$copyback = 1;
    }
186
}
Leigh B Stoller's avatar
Leigh B Stoller committed
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));
}
Leigh B Stoller's avatar
Leigh B Stoller committed
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));
Leigh B Stoller's avatar
Leigh B Stoller committed
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();
Leigh B Stoller's avatar
Leigh B Stoller committed
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());
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
312
313
314
}
else {
    usage()
315
	if (! (@ARGV && defined($group)));
Leigh B Stoller's avatar
Leigh B Stoller committed
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;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
349
350
351
352
353
354
355
356
357

#
# 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 ... 
#
358
if (!$update) {
359
360
    # New mysal 5.7 limit of 64 chars on locks. Use the uuid.
    my $lockname;
361
362
363
364
    if (length($url) < 64) {
	$lockname = $1;
    }
    elsif ($url =~ /uuid=([-\w]+)$/) {
365
366
367
368
369
370
	$lockname = $1;
    }
    else {
	fatal("Bad URL, cannot find the uuid in it");
    }
    my $query_result = DBQueryWarn("select GET_LOCK('$lockname', 120)");
371
372
373
374
    if (!$query_result ||
	!$query_result->numrows) {
	fatal("Could not get the SQL lock for a long time!");
    }
375
    $image = OSImage->LookupByURL($url);
376
377
378
    if (!defined($image)) {
	$image = CreateImage($url, $xmlparse, $user, $group, $imagename);
    }
379
    DBQueryWarn("select RELEASE_LOCK('$lockname')");
Leigh B Stoller's avatar
Leigh B Stoller committed
380
381
382
383
}
exit(0)
    if ($verify);

384
if ($update || $getimage) {
Leigh B Stoller's avatar
Leigh B Stoller committed
385
386
387
388
389
    #
    # 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.
    #
390
    if (!$copyback && $image->Lock()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
391
392
393
394
395
396
397
398
399
400
401
	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");
	}
    }
402
403
404
405
406
407
}
#
# If updating, see if we need a new version of the image descriptor.
#
if ($update && $newhash ne $image->hash()) {
    if ($doprovenance) {
408
	#
409
410
	# This will include unreleased images (in image_versions, but
	# not the one pointed to by the images table). 
411
	#
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
	$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;

	    if (!$getimage) {
428
		#
429
430
431
432
433
		# 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.
434
		#
435
436
437
		$image->MarkReady();
		$image->Release();
		$image->ClearReady();
Leigh B Stoller's avatar
Leigh B Stoller committed
438
	    }
439
	}
440
441
    }
    # Update these in the descriptor.
442
    my @slots = ("imagefile_url", "origin_name");
443
444
445
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) {
    # Run as root to access /proj
    $EUID = $UID = 0;
    if (! -e $image->FullImageFile() || $newhash ne $image->hash() || $force) {
464
465
466
467
468
	# Make sure the path directory exists.
	if ($image->CreateImageDir()) {
	    $image->Unlock();
	    exit(1);
	}
469
470
	$EUID = $UID = $SAVEUID;

Leigh B Stoller's avatar
Leigh B Stoller committed
471
472
473
474
	if (DownLoadImage($image, $newhash, $user, $group)) {
	    $image->Unlock();
	    exit(1);
	}
475
476
	# Update DB info. 
	my $versname = $image->versname();
477
478
	# Run as root to access /proj
	$EUID = $UID = 0;
479
	if (system("$IMAGEVALIDATE -u $versname")) {
480
481
482
	    # XXX should this be fatal?
	    print STDERR "Could not update DB info for $image\n";
	}
483
	$EUID = $UID = $SAVEUID;
484
485
	$image->MarkReady();
	$image->Release();
486
	# Its more important to know when we brought the new version in.
487
	if ($update) {
488
489
	    $image->MarkUpdate($user);
	}
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
518
519
520
521
	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);
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
522
    }
523
    $EUID = $UID = $SAVEUID;
524
525
526
527
528
529
530
531
532
    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();

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

537
538
539
540
	# Tell the IMS about this new image. If this fails, the daemon
	# will take care of it. 
	system("$POSTIMAGEINFO -d $imageid");
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
541
}
542
543
544
545
elsif ($update && $dosig) {
    FetchSigFile($image) == 0
	or exit(1);
}
546
547
548
else {
    print "Not downloading image ... add -g option\n";
}
549
550
551
if ($update || $getimage) {
    $image->Unlock();
}
Leigh B Stoller's avatar
Leigh B Stoller committed
552
553
554
555
556
557
exit(0);

#
# Create a new image descriptor. We have to munge the XML file a bit
# though and write it out.
#
558
sub CreateImage($$$$$)
Leigh B Stoller's avatar
Leigh B Stoller committed
559
{
560
    my ($url, $xmlparse, $user, $group, $imagename) = @_;
Leigh B Stoller's avatar
Leigh B Stoller committed
561
    my $alltypes = "-a";
562
    my $global   = 0;
563
564
565
566
567
568

    # 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}));
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
569
570
571
572
573
574
575
576
577
578
579
    
    $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.
    #
580
    if (exists($xmlparse->{'attribute'}->{"def_parentosid"})) {
581
582
583
584
585
	#
	# 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'};
586
	my $parent = OSImage->Lookup($posid);
587
588
589
590
591
592
593
594
595
596
597
	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";
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
598
599
    }

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

Leigh B Stoller's avatar
Leigh B Stoller committed
606
607
608
609
610
611
    #
    # 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. 
    #
612
613
614
615
    if (defined($imagename)) {
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
    elsif (! exists($xmlparse->{'attribute'}->{"imagename"})) {
Leigh B Stoller's avatar
Leigh B Stoller committed
616
617
618
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = 
	    substr(TBGenSecretKey(), 0, 12);
    }
619
    elsif (OSImage->Lookup($group->pid(),
Leigh B Stoller's avatar
Leigh B Stoller committed
620
621
622
623
624
625
			 $xmlparse->{'attribute'}->{"imagename"}->{'value'})) {
	my $index = 1;
	my $imagename;
	do {
	    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
	    $imagename .= "_" . $index++;
626
	} while ($index < 100 && OSImage->Lookup($group->pid(), $imagename));
Leigh B Stoller's avatar
Leigh B Stoller committed
627
628
629
630
631
	if ($index >= 100) {
	    fatal("Could not generate a unique image name");
	}
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
632
    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
Leigh B Stoller's avatar
Leigh B Stoller committed
633
634
635
636
    if ($debug) {
	print STDERR "Using imagename: $imagename\n";
    }
    # do not trust path coming in.
637
    if ($global && $user->IsAdmin()) {
Leigh B Stoller's avatar
Leigh B Stoller committed
638
	$xmlparse->{'attribute'}->{"path"}->{'value'} = "$TB/images/";
639
640
641
    }
    else {
	$xmlparse->{'attribute'}->{"path"}->{'value'} =
Leigh B Stoller's avatar
Leigh B Stoller committed
642
643
644
	    "$TBPROJ_DIR/" . $group->pid() . "/images/";
    }
    if ($DOIMAGEDIRS) {
Leigh B Stoller's avatar
Leigh B Stoller committed
645
	$xmlparse->{'attribute'}->{"path"}->{'value'} .= "${imagename}/";
Leigh B Stoller's avatar
Leigh B Stoller committed
646
647
    }
    else {
Leigh B Stoller's avatar
Leigh B Stoller committed
648
	$xmlparse->{'attribute'}->{"path"}->{'value'} .= "${imagename}.ndz";
649
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    
    #
    # 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.
669
    open(NEW, "| $NEWIMAGE_EZ $alltypes -f -s -v -")
Leigh B Stoller's avatar
Leigh B Stoller committed
670
671
672
673
674
675
676
677
678
	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);
    
679
    open(NEW, "| $NEWIMAGE_EZ $alltypes -f -s -")
Leigh B Stoller's avatar
Leigh B Stoller committed
680
681
682
683
684
685
686
	or fatal("Cannot start $NEWIMAGE_EZ");
    print NEW $newxml;
    if (!close(NEW)) {
	print STDERR "$newxml\n";
	fatal("Could not create new image from xml");
    }

687
    my $image = OSImage->LookupByURL($url);
Leigh B Stoller's avatar
Leigh B Stoller committed
688
689
690
    if (!defined($image)) {
	fatal("Could not lookup new image for $url");
    }
691
692
693
694
    #
    # 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.
    #
695
    $image->MarkReleased();
Leigh B Stoller's avatar
Leigh B Stoller committed
696
697
698
699
700
701
702
703
    return $image;
}

#
# Download the image file. 
#
sub DownLoadImage($$$$)
{
704
    my ($image, $newhash, $user, $group) = @_;
Leigh B Stoller's avatar
Leigh B Stoller committed
705
    my $localfile = $image->FullImageFile() . ".new";
Leigh B Stoller's avatar
Leigh B Stoller committed
706

707
    if (FetchImageFile($image, "", $localfile)) {
708
	return -1;
Leigh B Stoller's avatar
Leigh B Stoller committed
709
710
711
    }

    #
712
    # Verify the hash which was created by FetchImageFile().
Leigh B Stoller's avatar
Leigh B Stoller committed
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
    #
    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.
    #
Leigh B Stoller's avatar
Leigh B Stoller committed
748
749
    my $hashfile = $image->FullImageSHA1File();
    my $ndzfile  = $image->FullImageFile();
Leigh B Stoller's avatar
Leigh B Stoller committed
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
    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;
    }
766
767
768
769
770
771

    #
    # 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.
    #
772
    FetchSigFile($image);
Leigh B Stoller's avatar
Leigh B Stoller committed
773
774
775
    return 0;
}

776
777
778
#
# Fetch a file.
#
779
sub FetchImageFile($$$)
780
{
781
782
    my ($image, $urlarg, $localfile) = @_;
    my $url       = uri_unescape($image->imagefile_url()) . $urlarg;
783
    my $safe_url  = User::escapeshellarg($url);
784
    my $user_uid  = $user->uid();
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

    #
    # 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;
	}
    }
815
816
817
818
819
    #
    # 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.
    #
820
    elsif (!$user->IsAdmin()) {
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
	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;
    }
845
846
847
848
849
850
851
852
853
854
855
856
    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;
	}
    }
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
    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;
	}
    }
876
    return 0;
877
878
}

Leigh B Stoller's avatar
Leigh B Stoller committed
879
880
881
882
883
884
885
886
#
# Fetch the metadata from the provided URL. Return the XML parse,
#
sub FetchMetadata($)
{
    my ($url) = @_;
    my $xml  = "";

887
888
889
890
891
892
893
    if ($url =~ /^file:\/\/(.*)/) {
	open(META, $1) or
	    fatal("Could not open $1: $!");
	while (<META>) {
	    $xml .= $_;
	}
	close(META);
Leigh B Stoller's avatar
Leigh B Stoller committed
894
    }
895
896
897
898
899
    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 ";
900
	$cmd .= "| $DD 2>/dev/null bs=1 count=5k ";
901
902
903
904
905
906
907
908
909
910
911

	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");
Leigh B Stoller's avatar
Leigh B Stoller committed
912
913
914
915
916
917
918
919
920
921
    }

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

    my $xmlparse = eval { XMLin($xml,
				VarAttr => 'name',
				ContentKey => '-content',
				SuppressEmpty => undef); };
922
923
924
925
    if ($@) {
	print STDERR $xml . "\n";
	fatal($@);
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
926
927
928
929
930
931
932
933
934
935
    if ($debug) {
	print STDERR Dumper($xmlparse);
    }

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

936
937
938
939
940
941
#
# Fetch sig file.
#
sub FetchSigFile($)
{
    my ($image) = @_;
Leigh B Stoller's avatar
Leigh B Stoller committed
942
943
    my $localfile  = $image->FullImageSigFile() . ".new";
    my $sigfile    = $image->FullImageSigFile();
944
    
945
    if (! FetchImageFile($image, "&sigfile=1", $localfile)) {
946
947
948
949
950
951
952
953
	system("/bin/mv -f $localfile $sigfile");
	# Do not need this.
	unlink("${localfile}.sha1")
	    if (-e "${localfile}.sha1");
    }
    return 0;
}

Leigh B Stoller's avatar
Leigh B Stoller committed
954
955
956
957
sub fatal($)
{
    my ($mesg) = @_;

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

Leigh B Stoller's avatar
Leigh B Stoller committed
961
962
963
964
965
    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}