image_import.in 15.6 KB
Newer Older
Leigh B Stoller's avatar
Leigh B Stoller committed
1
2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2010-2014 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: import_image [-d] [-v] [-u <user>] [-g] [-p pid] <url>\n");
Leigh B Stoller's avatar
Leigh B Stoller committed
37
38
39
40
41
42
    print("       import_image [-d] [-u <user>] [-g] -i <imageid>\n");
    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");
43
44
    print(" -p pid  - Create image in the specified project.\n".
	  "           Defaults to emulab-ops.\n");
Leigh B Stoller's avatar
Leigh B Stoller committed
45
46
47
    print(" -i id   - Update existing imported image.\n");
    exit(-1);
}
48
my $optlist = "dvu:p:giI";
Leigh B Stoller's avatar
Leigh B Stoller committed
49
50
51
52
my $debug   = 0;
my $verify  = 0;
my $getimage= 0;
my $update  = 0;
53
my $force   = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
my $user;
my $group;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
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;
72
my $IMAGEVALIDATE = "$TB/sbin/imagevalidate";
73
74
75
my $DELETEIMAGE   = "$TB/sbin/delete_image";
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
my $doprovenance  = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

#
# 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;
101
use EmulabConstants;
102
use EmulabFeatures;
Leigh B Stoller's avatar
Leigh B Stoller committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use libtestbed;
use User;
use Project;
use Group;
use Image;
use OSinfo;

# Locals;
my $url;

# Protos
sub fatal($);
sub FetchMetadata($);
sub CreateImage($$$$);
sub DownLoadImage($$$$);

#
# 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{"i"})) {
    $update = 1;
}
145
146
147
148
if (defined($options{"I"})) {
    $update = 1;
    $force  = 1;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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));
    }
}
165
166
167
168
169
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
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

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

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

    my $image = Image->Lookup($ARGV[0]);
    if (!defined($image)) {
	fatal("Image descriptor does not exist");
    }
    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 $image");
    }
}
else {
    usage()
200
	if (! (@ARGV && defined($group)));
Leigh B Stoller's avatar
Leigh B Stoller committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

    $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");
}
229
230
231
232
233
my $newhash = $xmlparse->{'attribute'}->{"hash"}->{'value'};
# Silly taint check.
if ($newhash =~/^(.*)$/) {
    $newhash = $1;
}
Leigh B Stoller's avatar
Leigh B Stoller committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278

#
# 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 ... 
#
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!");
}
my $image = Image->LookupByURL($url);
if (!defined($image)) {
    $image = CreateImage($url, $xmlparse, $user, $group);
}
DBQueryWarn("select RELEASE_LOCK($safe_url)");
exit(0)
    if ($verify);

#
# If the image has not been downloaded or if the hash has changed,
# get a new copy.
#
if ($getimage) {
    #
    # 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 ($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");
	}
    }
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
    if (! -e $image->path() || $newhash ne $image->hash() || $force) {
	#
	# When updating an image ... 
	#
	if ($update && $WITHPROVENANCE) {
	    $doprovenance =
		EmulabFeatures->FeatureEnabled("ImageProvenance",
					       undef, $image->GetProject());
	    if ($doprovenance) {
		#
		# This will include unreleased images (in image_versions, but
		# not the one pointed to by the images table). 
		#
		$image = $image->LookupMostRecent();
		if (!defined($image)) {
		    $image->Unlock();
		    fatal("Cannot lookup most recent version of $image");
		}
		# Reuse is not ready/released.
		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;
		}
	    }
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
308
309
310
311
	if (DownLoadImage($image, $newhash, $user, $group)) {
	    $image->Unlock();
	    exit(1);
	}
312
313
	# Update DB info. Use the hash we were given, no need to recalculate.
	my $imageid = $image->imageid();
314
315
	# Run as root to access /proj
	$EUID = $UID = 0;
316
317
318
319
	if (system("$IMAGEVALIDATE -uq -H '$newhash' $imageid")) {
	    # XXX should this be fatal?
	    print STDERR "Could not update DB info for $image\n";
	}
320
	$EUID = $UID = $SAVEUID;
321
322
	$image->MarkReady();
	$image->Release();
323
	# Its more important to know when we brought the new version in.
Leigh B Stoller's avatar
Leigh B Stoller committed
324
	if ($WITHPROVENANCE && $doprovenance && $update) {
325
326
	    $image->MarkUpdate($user);
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
327
328
329
330
331
332
333
334
335
336
337
338
339
    }
    $image->Unlock();
}
exit(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) = @_;
    my $alltypes = "-a";
340
    my $global   = 0;
Leigh B Stoller's avatar
Leigh B Stoller committed
341
342
343
344
345
346
347
348
349
350
351
    
    $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.
    #
352
    if (exists($xmlparse->{'attribute'}->{"def_parentosid"})) {
Leigh B Stoller's avatar
Leigh B Stoller committed
353
354
355
356
357
	$xmlparse->{'attribute'}->{"mtype_pcvm"} = {};
	$xmlparse->{'attribute'}->{"mtype_pcvm"}->{'value'} = 1;
	$alltypes = "";
    }

358
359
360
361
362
363
    # 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    #
    # 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 (! exists($xmlparse->{'attribute'}->{"imagename"})) {
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = 
	    substr(TBGenSecretKey(), 0, 12);
    }
    elsif (Image->Lookup($group->pid(),
			 $xmlparse->{'attribute'}->{"imagename"}->{'value'})) {
	my $index = 1;
	my $imagename;
	do {
	    $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
	    $imagename .= "_" . $index++;
	} while ($index < 100 && Image->Lookup($group->pid(), $imagename));
	if ($index >= 100) {
	    fatal("Could not generate a unique image name");
	}
	$xmlparse->{'attribute'}->{"imagename"}->{'value'} = $imagename;
    }
    my $imagename = $xmlparse->{'attribute'}->{"imagename"}->{'value'};
    if ($debug) {
	print STDERR "Using imagename: $imagename\n";
    }
    # do not trust path coming in.
392
393
394
395
396
397
398
399
    if ($global && $user->IsAdmin()) {
	$xmlparse->{'attribute'}->{"path"}->{'value'} =
	    "$TB/images/${imagename}.ndz";
    }
    else {
	$xmlparse->{'attribute'}->{"path"}->{'value'} =
	    "$TBPROJ_DIR/" . $group->pid() . "/images/${imagename}.ndz";
    }
Leigh B Stoller's avatar
Leigh B Stoller committed
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
    
    #
    # 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.
    open(NEW, "| $NEWIMAGE_EZ $alltypes -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 -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");
    }

    my $image = Image->LookupByURL($url);
    if (!defined($image)) {
	fatal("Could not lookup new image for $url");
    }
441
442
    $image->MarkReady();
    $image->MarkReleased();
Leigh B Stoller's avatar
Leigh B Stoller committed
443
444
445
446
447
448
449
450
    return $image;
}

#
# Download the image file. 
#
sub DownLoadImage($$$$)
{
451
    my ($image, $newhash, $user, $group) = @_;
Leigh B Stoller's avatar
Leigh B Stoller committed
452
453
454
455
456
457
    my $image_url = uri_unescape($image->imagefile_url());
    my $safe_url  = User::escapeshellarg($image_url);
    my $localfile = $image->path() . ".new";

    #
    # Build up a new command line to do the fetch on ops
458
459
    # But no reason to do this if an admin, which is important
    # when the image is going into /usr/testbed/images.
Leigh B Stoller's avatar
Leigh B Stoller committed
460
    #
461
462
463
464
465
466
467
468
469
470
471
    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";
Leigh B Stoller's avatar
Leigh B Stoller committed
472

473
474
475
476
477
478
479
480
481
482
483
484
	print "Downloading $image_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;
Leigh B Stoller's avatar
Leigh B Stoller committed
485
    }
486
    else {
487
488
	print "Downloading $image_url ...\n";
	
489
	if (! open(GET, "| nice -15 $WGET --no-check-certificate ".
490
		   "--timeout=30 --waitretry=30 -q -O $localfile -i -")) {
491
492
493
494
495
496
497
498
499
500
501
502
	    print STDERR "Cannot start $WGET\n";
	    return -1;
	}
	print GET "$image_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;
	}
Leigh B Stoller's avatar
Leigh B Stoller committed
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
    }

    #
    # Verify the hash.
    #
    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.
    #
    my $hashfile = $image->path() . ".sha1";
    my $ndzfile  = $image->path();
    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;
    }
    $EUID = $SAVEUID;
    return 0;
}

#
# Fetch the metadata from the provided URL. Return the XML parse,
#
sub FetchMetadata($)
{
    my ($url) = @_;
    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";
    }
    open(META, "$cmd |") or
	fatal("Could not fetch metadata from $url");
    while (<META>) {
	$xml .= $_;
    }
    close(META)
	or fatal("Could not read metadata from $url");

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

    my $xmlparse = eval { XMLin($xml,
				VarAttr => 'name',
				ContentKey => '-content',
				SuppressEmpty => undef); };
    fatal($@)
	if ($@);

    if ($debug) {
	print STDERR Dumper($xmlparse);
    }

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

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

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