postimagedata.in 15.5 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2019 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
# 
# {{{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()
{
41
    print "Usage: postimagedata [-u] [-n] [-d] [-a] all [datasets] | [imageid ...]\n";
42 43
    exit(1);
}
44
my $optlist  = "undva";
45
my $impotent = 0;
46
my $update   = 0;
47 48 49 50
my $debug    = 0;
my $verbose  = 0;
my $errors   = 0;
my $allvers  = 0;
Leigh Stoller's avatar
Leigh Stoller committed
51
my $datasets = 0;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

#
# 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 $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($);
75
sub PostImageAlias($);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

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

# Now we can load the libraries after setting the proper DB.
use lib '@prefix@/lib';
use emutil;
use GeniDB;
use EmulabConstants;
use GeniCertificate;
use GeniAuthority;
use GeniHRN;
use Genixmlrpc;
91
use GeniResponse;
92 93
use GeniRegistry;
use libEmulab;
94
use OSImage;
95 96
use User;
use Group;
97 98
use emdb qw();
use EmulabFeatures;
99
use GeniImage;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
$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();
}
119 120
if (defined($options{"u"})) {
    $update = 1;
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
}
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);
if ($ARGV[0] eq "all") {
    shift(@ARGV);
138 139 140 141
    if (@ARGV && $ARGV[0] eq "datasets") {
	shift(@ARGV);
	$datasets = 1;
    }
142 143
    usage() if
	(@ARGV);
144 145
    print "Posting for all local ". ($datasets ? "datasets" : "images") .
	", hope that is okay!\n";
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
}

# 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) {
168
	my $image = OSImage->Lookup($imageid);
169 170 171 172 173
	if (!defined($image)) {
	    print STDERR "Could not lookup image: $imageid\n";
	    $errors++;
	    next;
	}
174 175 176 177
	if ($image->isImageAlias()) {
	    if (PostImageAlias($image)) {
		$errors++;
	    }
178
	}
179 180 181 182 183 184
	else {
	    # 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";
185
		$errors++;
186 187 188
		next;
	    }
	    foreach my $tmp (@allversions) {
189 190 191
		next
		    if (defined($tmp->deleted()));
		    
192 193 194
		if (PostImageInfo($tmp)) {
		    $errors++;
		}
195 196 197 198 199
	    }
	}
    }
}
else {
200
    my $query_result;
201
    my $which_clause = ($datasets ? "isdataset=1" : "(ezid=1 or isdataset=1)");
202 203 204 205 206

    if (!$update) {
	# List of all images that have not been reported to the IMS.
	$query_result =
	    emdb::DBQueryFatal("select v.imageid,v.version from ".
207 208
			   "  image_versions as v ".
			   "left join images as i on i.imageid=v.imageid ".
209
			   "where $which_clause and ".
210
			   "      i.imageid is not null and ".
211
			   "      v.ready=1 and v.released=1 and ".
212
			   "      ims_noreport=0 and ".
213
			   "      origin_urn is null and ".
214
			   "      deleted is null and ".
215
                           "      v.metadata_url is null and ".
216 217
			   "      (creator_urn is not null or ".
			   "       (v.pid='$TBOPSPID' and v.global=1)) and ".
218
			   "      (ims_reported is null or ".
219 220 221
			   "       created > ims_reported or ".
			   "       updated > ims_reported) ".
			   "order by v.imageid,v.version");
222 223 224 225 226 227 228 229 230 231 232 233 234 235
    }
    else {
	my $dateclause = "and ims_reported<'2017-11-16 10:48:53'";
	
	# List of all images that have already been reported to the IMS.
	$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 $which_clause and ".
			       "      ims_reported is not null and ".
			       "      deleted is null ".
			       "order by ims_reported asc");
    }
236
    while (my ($imageid,$version) = $query_result->fetchrow_array()) {
237
	my $image = OSImage->Lookup($imageid,$version);
238 239 240 241 242
	if (!defined($image)) {
	    print STDERR "Could not lookup image: $imageid,$version\n";
	    $errors++;
	    next;
	}
243 244 245 246
	if (0) {
	    print "$image\n";
	    next;
	}
247 248 249 250 251 252 253 254 255 256
	if (PostImageInfo($image)) {
	    $errors++;
	}
    }
}
exit($errors);

sub PostImageInfo($)
{
    my ($image) = @_;
257 258
    my $osfeatures = "";
    
259 260
    my $imageid = $image->imageid();
    my $version = $image->version();
261 262

    if (!$image->isdataset()) {
263
	$osfeatures = $image->osfeatures();
264
    }
265 266 267 268 269
    if (!defined($image->hash())) {
	print STDERR "No sha1hash for $image\n";
	# Just skip.
	return 0;
    }
270 271 272 273 274 275 276 277 278 279 280 281
    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;
    }
282 283 284 285 286 287 288 289 290
    #
    # Grab image permissions.
    #
    my $perms_result =
	emdb::DBQueryWarn("select * from image_permissions ".
			  "where imageid='$imageid'");
    if (!defined($perms_result)) {
	return -1;
    }
291

292 293 294
    # This stuff is not needed for datasets.
    my $arch  = "";
    my $virtualization = "";
295
    my @types = ();
296
    if (!$image->isdataset()) {
297 298 299 300 301 302
	if ($image->architecture()) {
	    $arch = $image->architecture();
	}
	else {
	    $arch  = "x86_64";
	}
303
	$virtualization = "raw-pc";
304 305
	foreach my $nodetype ($image->TypeList()) {
	    my $type = $nodetype->type();
306 307 308 309 310
	    push(@types, $type);
	    if ($type eq "m400") {
		$arch = "aarch64";
	    }
	    if ($type eq "pcvm") {
311 312 313 314 315 316
		if ($image->format() eq "docker") {
		    $virtualization = "emulab-docker";
		}
		else {
		    $virtualization = "emulab-xen";
		}
317
	    }
318 319 320 321 322 323 324
	}
    }
    my $visibility  = ($image->global() ? "public" : "project");
    my $creator_urn = $image->creator_urn();
    if (!defined($creator_urn)) {
	$creator_urn = GeniHRN::Generate($OURDOMAIN, "user", $image->creator());
    }
325
    my $image_urn = $image->urn();
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

    #
    # 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");
    }
351 352 353 354
    if (!defined($project_urn)) {
	print STDERR "Could not form a project_urn for $image. Skipping ... \n";
	return 0;
    }
355
    my $isversioned = 
356
	($WITHPROVENANCE && 
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	 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(),
379
		"osfeatures"     => $osfeatures,
380 381
		"arch"           => $arch,
		"visibility"     => $visibility,
382
		"virtualizaton"  => $virtualization,
383 384
		"metadata_url"   => $image->LocalVersionURL(),
		"types_known_working" => join(",", @types),
385
		"image_permissions" => [],
386 387
    };
    #
388 389 390 391 392 393 394 395 396 397 398
    # Send along deprecated info.
    #
    if (defined($image->deprecated())) {
	$blob->{'deprecated'} = TBDateStringGMT(str2time($image->deprecated()));
	$blob->{'deprecated_iserror'} = $image->deprecated_iserror();
	if (defined($image->deprecated_message()) &&
	    $image->deprecated_message() ne "") {
	    $blob->{'deprecated_message'} = $image->deprecated_message();
	}
    }
    #
399 400 401 402 403 404
    # 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();
    }
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
    #
    # Add the local image permissions. 
    #
    while (my $row = $perms_result->fetchrow_hashref()) {
	my $ptype = $row->{'permission_type'};
	my $idx   = $row->{'permission_idx'};
	my $id    = $row->{'permission_id'};
	my $urn;
	
	if ($ptype eq "user") {
	    my $user = User->Lookup($idx);
	    if (!defined($user)) {
		print STDERR "No such user $id ($idx) in permissions table\n";
		next;
	    }
	    $urn = GeniHRN::Generate($OURDOMAIN, "user", $user->uid());
	}
	elsif ($ptype eq "group") {
	    my $group = Group->Lookup($idx);
	    if (!defined($group)) {
		print STDERR "No such group $id ($idx) in permissions table\n";
		next;
	    }
	    # IMS is not group aware.
	    $ptype = "project";

	    if (!$group->IsProjectGroup()) {
		print STDERR "Not a project group in permissions table: $group\n";
		next;
	    }
	    my $proj = $group->GetProject();
	    if ($proj->IsNonLocal()) {
		#
438 439 440
		# If we are doing real projects, then the nonlocal_id should
		# be in the proper format, but because of backwards compat
		# issue, lets generate it anyway.
441
		#
442 443 444
		my $hrn = GeniHRN->new($proj->nonlocal_id());
		$urn = GeniHRN::Generate($hrn->domain() . ":" . $proj->pid(),
					     "authority", $hrn->id());
445 446 447 448 449 450 451 452 453 454 455 456 457
	    }
	    else {
		$urn = GeniHRN::Generate($OURDOMAIN . ":" . $proj->pid(),
					 "authority", "sa");
	    }
	}
	else {
	    print STDERR "Invalid permission_type: $ptype\n";
	    return -1;
	}
	push(@{ $blob->{'image_permissions'} },
	     {"type" => $ptype, "urn" => $urn})
    }
458 459 460 461 462 463 464 465 466 467
    print Dumper($blob)
	if ($debug);
    if ($impotent) {
	print "Would push $image\n";
	return 0;
    }

    if ($verbose) {
	print "Pushing $image\n";
    }
468 469 470
    # Does not return if error.
    my $credential = GetServerCredential();
    
471
    #
472 473
    # Push the blob to the image server. Retry a couple of times on
    # tranient RPC error.
474
    #
475 476 477
    my $errmsg;
    my $count = 3;
    while ($count) {
478
	my $msg = "PostImageInfo failed for image " . $image->versname() . " :";
479 480 481 482 483 484 485 486 487 488
	my $args ={"credential" => $credential->asString(),
		   "imageinfo"  => $blob};

	my $rval = GeniImage::PostImageData($args, \$errmsg);

	last
	    if ($rval == 0);

	if ($rval != GENIRESPONSE_RPCERROR) {
	    print STDERR "$msg: $errmsg\n";
489 490
	    return -1;
	}
491 492 493
	$count--;
	if ($count == 0) {
	    print STDERR "$msg: Too many RPC failures, done trying.\n";
494 495
	    return -1;
	}
496 497
	print "Transient RPC error, will retry in five seconds.\n";
	sleep(5);
498 499 500 501 502 503
    }
    # Mark as reported.
    $image->MarkIMSReported();
    return 0;
}

504 505 506 507 508 509
sub PostImageAlias($)
{
    my ($image) = @_;
    my @target_urns = ();

    foreach my $tmp ($image->imagelist()) {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
	my $target_urn;
	if ($tmp->IsLocal()) {
	    $target_urn = $tmp->urn();
	}
	else {
	    #
	    # Need to provide the URN it is known by. Need a better way
	    # to get this. 
	    #
	    my $authurn = GeniHRN->new($tmp->origin_urn());
	    my ($ospid,$os,undef,$vers) =
		($tmp->origin_name() =~ m{([^/]+)/([^:]+)(:(\d+))?});
	    $target_urn = GeniHRN::Generate($authurn->authority(), "image",
					    "${ospid}//${os}");
	}
	push(@target_urns, $target_urn);
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    }
    my $blob = {"client_version" => $CLIENTVERS,
		"isimagealias"   => 1,
		"urn"		 => $image->urn(),
		"uuid"           => $image->uuid(),
		"target_urns"    => \@target_urns,

    };
    print Dumper($blob)
	if ($debug);
    if ($impotent) {
	print "Would push $image\n";
	return 0;
    }

    if ($verbose) {
	print "Pushing $image\n";
    }
544 545 546
    # Does not return if error.
    my $credential = GetServerCredential();
    
547
    #
548 549
    # Push the blob to the image server. We retry a few times if we get
    # an RPC error since that is usually transient.
550
    #
551 552 553
    my $errmsg;
    my $count = 3;
    while ($count) {
Leigh Stoller's avatar
Leigh Stoller committed
554 555
	my $msg = "PostImageInfo failed for alias " .
	    $image->imagename() . " :";
556 557 558 559 560 561 562 563 564 565
	my $args ={"credential" => $credential->asString(),
		   "imageinfo"  => $blob};

	my $rval = GeniImage::PostImageData($args, \$errmsg);

	last
	    if ($rval == 0);

	if ($rval != GENIRESPONSE_RPCERROR) {
	    print STDERR "$msg: $errmsg\n";
566 567
	    return -1;
	}
568 569 570
	$count--;
	if ($count == 0) {
	    print STDERR "$msg: Too many RPC failures, done trying.\n";
571 572
	    return -1;
	}
573 574
	print "Transient RPC error, will retry in five seconds.\n";
	sleep(5);
575 576 577 578
    }
    return 0;
}

579 580 581 582 583 584 585 586 587 588 589
#
# Get a credential to talk to the IMS.
#
my $IMS_credential;

sub GetServerCredential()
{
    return $IMS_credential
	if (defined($IMS_credential));
    
    my $response =
590
	Genixmlrpc::CallMethod(IMSURL(), undef, "GetCredential");
591 592 593 594 595
    if (!defined($response)) {
	fatal("RPC error getting credential");
    }
    if ($response->IsError()) {
	print STDERR "GetCredential: " . $response->Dump() . "\n";
596 597 598 599
	if ($response->code() == GENIRESPONSE_RPCERROR()) {
	    # Will catch it later.
	    exit(1);
	}
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	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);
}