postimagedata.in 10.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/perl -w
#
# Copyright (c) 2008-2015 University of Utah and the Flux Group.
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
use Date::Parse;
use Data::Dumper;

#
# Upload image data to the image server.
# 
sub usage()
{
    print "Usage: postimagedata [-f] [-n] [-d] [-a] all | [imageid ...]\n";
    exit(1);
}
44
my $optlist  = "fndva";
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
my $impotent = 0;
my $force    = 0;
my $debug    = 0;
my $verbose  = 0;
my $errors   = 0;
my $allvers  = 0;

#
# Configure variables
#
my $TB		  = "@prefix@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBLOGS        = "@TBLOGSEMAIL@";
my $PGENIDOMAIN   = "@PROTOGENI_DOMAIN@";
my $PGENISUPPORT  = @PROTOGENI_SUPPORT@;
my $PGENILOCALUSER= @PROTOGENI_LOCALUSER@;
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
my $CMCERT	  = "$TB/etc/genicm.pem";
my $OURDOMAIN     = "@OURDOMAIN@";
#my $IMSURL        = "https://www.emulab.net:12369/protogeni/stoller/xmlrpc/ims";
my $IMSURL        = "https://www.emulab.net:12369/protogeni/xmlrpc/ims";
my $CLIENTVERS    = 1;

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/site/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

# Protos
sub fatal($);
sub GetServerCredential();
sub PostImageInfo($);

#
# Turn off line buffering on output
#
$| = 1; 

# Now we can load the libraries after setting the proper DB.
use lib '@prefix@/lib';
use libaudit;
use emutil;
use GeniDB;
use EmulabConstants;
use GeniCertificate;
use GeniAuthority;
use GeniHRN;
use Genixmlrpc;
use GeniRegistry;
use libEmulab;
use Image;
use OSinfo;
use emdb qw();
use EmulabFeatures;
$EmulabFeatures::verbose = 0;
my $TBOPSPID = TBOPSPID();

if (!$PGENISUPPORT) {
    print STDERR "You are not a protogeni site\n";
    exit(0);
}
if (!GetSiteVar("protogeni/use_imagetracker")) {
    print STDERR "Image tracking is not enabled for this site\n";
    exit(0);
}

#
# Check args.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"f"})) {
    $force = 1;
}
if (defined($options{"a"})) {
    $allvers = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"v"})) {
    $verbose = 1;
}
usage()
    if (!@ARGV);
# Avoid mistakes, force caller to say they want all images posted.
if ($ARGV[0] eq "all") {
    shift(@ARGV);
    usage() if
	(@ARGV);
    print "Posting for all local images, hope that is okay!\n";
    sleep(2);
}

# Record output in case of error.
LogStart(0)
    if (!$debug);

# Connect to the proper DB.
DBConnect(GENICM_DBNAME());

#
# Load the CM cert to act as caller context.
#
my $certificate = GeniCertificate->LoadFromFile($CMCERT);
if (!defined($certificate)) {
    fatal("Could not load certificate from $CMCERT\n");
}
my $context = Genixmlrpc->Context($certificate);
if (!defined($context)) {
    fatal("Could not create context to talk to image server");
}
Genixmlrpc->SetContext($context);
# Shorten default timeout.
Genixmlrpc->SetTimeout(15);


if (@ARGV) {
    foreach my $imageid (@ARGV) {
	my $image = Image->Lookup($imageid);
	if (!defined($image)) {
	    print STDERR "Could not lookup image: $imageid\n";
	    $errors++;
	    next;
	}
	# We post all versions with -a
	my @allversions = ($image);
	if ($allvers && $image->AllVersions(\@allversions)) {
	    print STDERR "Could not lookup all versions for image: $imageid\n";
	    $errors++;
	    next;
	}
	foreach my $tmp (@allversions) {
	    if (PostImageInfo($tmp)) {
		$errors++;
	    }
	}
    }
}
else {
    # Force allows updating all images previously reported
    my $ims_reported_clause =
	($force ? "1 or" : "ims_reported is null or");
    
    # List of all images that have not been reported to the IMS.
    my $query_result =
	emdb::DBQueryFatal("select v.imageid,v.version from ".
			   "  image_versions as v ".
			   "left join images as i on i.imageid=v.imageid ".
			   "where ezid=1 and isdataset=0 and ".
			   "      i.imageid is not null and ".
200
			   "      v.ready=1 and v.released=1 and ".
201
			   "      ims_noreport=0 and ".
202
			   "      origin_urn is null and ".
203
			   "      deleted is null and ".
204
205
206
                           "      metadata_url is null and ".
			   "      (creator_urn is not null or ".
			   "       (v.pid='$TBOPSPID' and v.global=1)) and ".
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
			   "      ($ims_reported_clause ".
			   "       created > ims_reported or ".
			   "       updated > ims_reported) ".
			   "order by v.imageid,v.version");

    while (my ($imageid,$version) = $query_result->fetchrow_array()) {
	my $image = Image->Lookup($imageid,$version);
	if (!defined($image)) {
	    print STDERR "Could not lookup image: $imageid,$version\n";
	    $errors++;
	    next;
	}
	if (PostImageInfo($image)) {
	    $errors++;
	}
    }
}
# No errors at this point, nothing to report.
AuditAbort()
    if (!$debug && !$errors);
exit($errors);

sub PostImageInfo($)
{
    my ($image) = @_;
    my $imageid = $image->imageid();
    my $version = $image->version();
    my $osinfo  = OSinfo->Lookup($imageid,$version);
    if (!defined($osinfo)) {
	print STDERR "Could not lookup osinfo: $imageid,$version\n";
	# Just skip, something is very wrong.
	return 0;
    }
    my $project = $image->GetProject();
    if (!defined($project)) {
	print STDERR "Could not lookup project: $imageid,$version\n";
	# Just skip, something is very wrong.
	return 0;
    }
    my $group = $image->GetGroup();
    if (!defined($group)) {
	print STDERR "Could not lookup group: $imageid,$version\n";
	# Just skip, something is very wrong.
	return 0;
    }

    my $credential = GetServerCredential();

    #
    # Grab the current type list.
    #
    my $types_result =
	emdb::DBQueryWarn("select distinct type from osidtoimageid ".
			  "where imageid='$imageid'");
    
    if (!defined($types_result)) {
	return -1;
    }
    my $arch  = "x86_64";
    my $virtualizaton = "raw-pc";
    my @types = ();
    while (my ($type) = $types_result->fetchrow_array()) {
	push(@types, $type);
	if ($type eq "m400") {
	    $arch = "aarch64";
	}
	if ($type eq "pcvm") {
	    my $virtualizaton = "emulab-xen";
	}
    }
    my $visibility  = ($image->global() ? "public" : "project");
    my $creator_urn = $image->creator_urn();
    if (!defined($creator_urn)) {
	$creator_urn = GeniHRN::Generate($OURDOMAIN, "user", $image->creator());
    }
    my $image_urn = GeniHRN::Generate($OURDOMAIN, "image",
			      $image->pid() . "//" . $image->imagename());

    #
    # We want a project URN.
    #
    my $project_urn;
    
    if ($project->IsNonLocal()) {
	#
	# If we are doing real projects, then the nonlocal_id is in the
	# proper subauth format. 
	#
	if ($PGENILOCALUSER) {
	    $project_urn = $project->nonlocal_id();
	}
	else {
	    my ($domain, undef, $id) = GeniHRN::Parse($project->nonlocal_id());

	    $project_urn = GeniHRN::Generate($domain . ":" . $image->gid(),
					     "authority", $id);
	}
    }
    else {
	$project_urn = GeniHRN::Generate($OURDOMAIN . ":" . $image->pid(),
					 "authority", "sa");
    }
    my $isversioned = 
	($WITHPROVENANCE &&
	 EmulabFeatures->FeatureEnabled("ImageProvenance",
					undef, $group) ? 1 : 0);

    my $blob = {"client_version" => $CLIENTVERS,
		"urn"		 => $image_urn,
		"project_urn"    => $project_urn,
		"imagename"      => $image->imagename(),
		"version"        => $image->version(),
		"image_uuid"     => $image->image_uuid(),
		"version_uuid"   => $image->uuid(),
		"isdataset"      => $image->isdataset(),
		"isversioned"    => $isversioned,
		"issystem"       => $image->pid() eq TBOPSPID() ? '1' : '0',
		"sha1hash"       => $image->hash(),
		"creator_urn"    => $creator_urn,
		"created"        => TBDateStringGMT(str2time($image->created())),
		"description"    => $image->description(),
		"filesize"       => $image->size() . ".0",
		"lba_low"        => $image->lba_low() . ".0",
		"lba_high"       => $image->lba_high() . ".0",
		"lba_size"       => $image->lba_size(),
		"mbr_version"    => $image->mbr_version(),
		"osfeatures"     => $osinfo->osfeatures(),
		"arch"           => $arch,
		"visibility"     => $visibility,
		"virtualizaton"  => $virtualizaton,
		"metadata_url"   => $image->LocalVersionURL(),
		"types_known_working" => join(",", @types),
    };
    #
    # If this is a nonlocal image, send the origin along so that the
    # image server knows we are a copy.
    #
    if (!$image->IsLocal()) {
	$blob->{'origin_url'} = $image->metadata_url();
    }
    print Dumper($blob)
	if ($debug);
    if ($impotent) {
	print "Would push $image\n";
	return 0;
    }

    if ($verbose) {
	print "Pushing $image\n";
    }
    #
    # Push the blob to the image server.
    #
    my $response =
	Genixmlrpc::CallMethod($IMSURL, undef, "PostImageInfo",
			       {"credential" => $credential->asString(),
				"imageinfo"  => $blob});
    if (!defined($response) || $response->code()) {
	my $msg = "PostImageInfo failed for image " . $image->versname() . " :";
	
	if (!defined($response)) {
	    # Bail, we will try again later.
	    print STDERR "$msg RPC error\n";
	    return -1;
	}
	elsif (defined($response->output())) {
	    print STDERR "$msg " . $response->output() . "\n";
	    return -1;
	}
	else {
	    print STDERR "$msg " . $response->code() . "\n";
	    return -1;
	}
    }
    # Mark as reported.
    $image->MarkIMSReported();
    return 0;
}

#
# Get a credential to talk to the IMS.
#
my $IMS_credential;

sub GetServerCredential()
{
    return $IMS_credential
	if (defined($IMS_credential));
    
    my $response =
	Genixmlrpc::CallMethod($IMSURL, undef, "GetCredential");
    if (!defined($response)) {
	fatal("RPC error getting credential");
    }
    if ($response->IsError()) {
	print STDERR "GetCredential: " . $response->Dump() . "\n";
	fatal("Error getting credential");
    }
    $IMS_credential = GeniCredential->CreateFromSigned($response->value(), 1);
    if (!defined($IMS_credential)) {
	print STDERR $GeniCredential::CreateFromSignedError . "\n";
	fatal("Error getting credential");
    }
    return $IMS_credential;
}

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

    print STDERR "*** $0:\n".
	         "    $msg\n";
    # exit value important.
    exit(-1);
}