libimageops_docker.pm.in 32.7 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 44 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
#!/usr/bin/perl -w
#
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
# 
# {{{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/>.
# 
# }}}
#
package libimageops_docker;
use strict;
use libimageops;
use base qw(libimageops_base);

use libdb;
use libtestbed;
use libtblog;
use User;
use Node;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');
use File::Temp qw/ :mktemp /;

my $TB = "@prefix@";
my $OURDOMAIN = "@OURDOMAIN@";
my $CREATEDOCKERIMAGE = "/usr/local/bin/create-docker-image";
my $DOCKREGCLI = "/usr/local/bin/docker-registry-cli";
# Prefer dev trees for docker creds, but bail to regular place.
my $DOCKCREDDIR = "$TB/etc/docker";
if (! -d "$TB/etc/docker" && -d "/usr/testbed/etc/docker") {
    $DOCKCREDDIR = "/usr/testbed/etc/docker";
}
my $ADMINDOCKREGCLI = "$DOCKREGCLI -C $DOCKCREDDIR/admin-boss.creds" .
    " --cert $DOCKCREDDIR/cert.pem --key $DOCKCREDDIR/privkey.pem";

sub New($)
{
    my ($class) = @_;

    my $self             = $class->SUPER::New();

    $self->{'HASH'}->{'maxwait'} = 8 * 60;
    $self->{'HASH'}->{'idlewait'} = 2 * 60;
    $self->{'HASH'}->{'reportwait'} = 1 * 60;
    $self->{'HASH'}->{'maximagesize'} = 1 * 1024 ** 3;

    bless($self, $class);
    return $self;
}

#
# No quotas in Docker-land for now.
#
sub CheckImageQuota($$$$) {
    my ($self,$pid,$gid,$user) = @_;
    my $rc = 0;
    my $msg;

    if (wantarray) {
	return ($rc,$msg);
    }
    else {
	return $rc;
    }
}

sub CreateImageValidateArgs($$$$) {
    my ($self,$image,$node,$args) = @_;
    my $rc = -1;
    my $msg;

    #
    # Need to know this is a docker-host to tailor method below.
    #
    if (!$node->isvirtnode()) {
	$msg = "$node does not appear to be a virtnode!";
	goto out;
    }

    my $pnode   = Node->Lookup($node->phys_nodeid());
    my $osimage = OSImage->Lookup($pnode->def_boot_osid());
    if (!defined($osimage)) {
	$msg = "Could not get OSImage for $pnode (virtnode $node)";
	goto errout;
    }

    if ($osimage->FeatureSupported("docker-host")) {
	$args->{'delta'} = $args->{'signature'} = 0;
    }

    $rc = 0;

  out:
    tbwarn("$self CreateImageValidateArgs: $msg ($rc)\n")
	if ($rc);
    if (wantarray) {
	return ($rc,$msg);
    }
    else {
	return $rc;
    }
}

sub GetLocalRegistryPathForImage($$;$$$) {
    my ($self,$image,$registry_ref,$repo_ref,$tag_ref) = @_;
    my ($rc,$msg) = (undef,"");

    my $registry;
    #
    # Find the local cluster's registry, if any.
    #
127 128
    if (!TBGetSiteVar("docker/registry",\$registry) || $registry eq "") {
	$msg = "no local registry specified in sitevar general/docker_registry";
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 200 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 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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 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 522 523 524 525 526 527 528 529 530
	goto out;
    }

    #
    # Docker registry does not accept uppercase characters in repo names.
    #
    my $repo = lc($image->pid() . "/" . $image->gid() . "/" .
		  $image->imagename());
    my $tag = $image->version();

    $rc = "$registry/$repo:$tag";

    $$registry_ref = $registry
	if (defined($registry_ref));
    $$repo_ref = $repo
	if (defined($repo_ref));
    $$tag_ref = $tag
	if (defined($tag_ref));

  out:
    if (wantarray) {
	return ($rc,$msg);
    }
    else {
	return $rc;
    }
}

sub CaptureImage($$$$) {
    my ($self,$image,$node,$args) = @_;
    my $rc = -1;
    my $msg;

    my $node_id = $node->node_id();
    my $phys_node_id = $node->phys_nodeid();
    my $webtask = $args->{'webtask'};
    my $this_user = $args->{'user'};
    my $imagepid = $args->{'imagepid'} || $image->pid();
    my $imagename = $image->imagename();

    my ($path,$registry,$repo,$tag);
    my $rs = join("",(0..9,"A".."Z","a".."z")[map { rand(62) } (0..7)]);
    my $needunlock = 0;

    ($path,$msg) = $self->GetLocalRegistryPathForImage(
	$image,\$registry,\$repo,\$tag);
    if (!defined($path)) {
	$rc = -1;
	goto errout;
    }

    #
    # Before we do anything destructive, we lock the image.
    #
    if ($image->Lock()) {
	$msg = "Image is locked, please try again later ($PID)!";
	goto out;
    }
    $needunlock = 1;

    #
    # Update the image to point to the repo/tag; change its format.
    #
    $image->SetFormat("docker");
    $image->SetPath($path);
    # Save off the "filename".
    $args->{'filename'} = $path;

    #
    # Also update the image to run on type pcvm, so that we can do real
    # osloads of this image on pcvms.  This should probably be somewhere
    # else, but no big deal.
    #
    $image->SetRunsOnNodeType('pcvm');

    #
    # We need a temporary user/pass credential for the docker
    # login/commit/push on the node to login to our cluster's local
    # Docker registry.  So create that.  We need to remember these to
    # delete the token post-imaging.
    #
    my $experiment = $node->Reservation();
    my ($docker_user,$docker_pass);
    $docker_user = "exim" . $experiment->idx() . "-$rs";
    $docker_pass = TBGenSecretKey();

    if (User->AddTokenPassword(
	    $this_user,$this_user,"docker.registry","image.create",$repo,
	    $docker_user,$docker_pass,undef,3600,3600,0,1)) {
	$msg = "Could not create temporary Docker Registry credentials";
	goto out;
    }

    # XXX continuing... also need to fixup image descriptor creation,
    # which is pre-this file.
    my $debugarg = "";
    if ($self->debug()) {
	$debugarg = "-d 10";
    }
    my $command =
	"$CREATEDOCKERIMAGE $debugarg -R $registry -r $repo -t $tag" .
	" -u $docker_user -p $docker_pass $node_id";

    # Mark webtask
    $webtask->status("imaging")
	if (defined($webtask));

    # Clear the bootlog; see below.
    $node->ClearBootLog();

    #
    # Big hack; we want to tell the node to update the master password
    # files. But need to do this in a backwards compatable manner, and
    # in way that does not require too much new plumbing. So, just touch
    # file in /var/run, the current version of prepare looks for it.
    #
    my $SAVEUID;
    if ($args->{'update_prepare'}) {
	$SAVEUID = $UID;
	$EUID = $UID = 0;
	my $cmd = "$TB/bin/sshtb -n -o ConnectTimeout=10 ".
	    "-host $node_id touch /var/run/updatemasterpasswdfiles";
	print STDERR "About to: '$cmd'\n"
	    if ($self->debug());
	system($cmd);
	if ($?) {
	    $msg = "'$cmd' failed";
	    goto errout;
	}
	$EUID = $UID = $SAVEUID;
    }

    #
    # Now execute command and wait.  If we have a webtask, capture the
    # output of the command so we can spawn another child to process it;
    # but do that before suid.
    #
    my ($fname,$rpid);
    if (defined($webtask)) {
	$fname = mktemp("/tmp/create-docker-image-XXXXXX");
	open(TFD,">$fname");
	close(TFD);
	$rpid = fork();
	if ($rpid == 0) {
	    $SIG{INT} = sub { exit(0); };
	    while (!stat($fname)) {
		sleep(0.1);
	    }
	    open(FD,$fname);
	    while (1) {
		while (my $line = <FD>) {
		    if ($self->debug()) {
			print "CREATEIMAGE: $line";
		    }
		    chomp($line);
		    if ($line =~ /PUSHPROGRESS:\s+(\d+)\s+bytes/) {
			$webtask->Refresh();
			$webtask->imagesize(int($1)/(1024));
		    }
		}
		sleep(0.1);
	    }
	    exit(0);
	}
    }

    $SAVEUID = $UID;
    $EUID = $UID = 0;
    my $result = $self->RunWithSSH($phys_node_id,undef,$command,$fname);
    $EUID = $UID = $SAVEUID;

    if (defined($webtask)) {
	sleep(1);
	kill(2,$rpid);
	waitpid($rpid,0);
    }

    User->DeleteTokenPasswords($this_user,$this_user,"docker.registry",
			       $docker_user,$docker_pass);

    # Grab boot log now. Node will reboot and possibly erase it. We should
    # probably come up with a better way to handle this.
    my $bootlog;
    if ($node->GetBootLog(\$bootlog) == 0) {
	$args->{'bootlog'} = $bootlog;
    }
    if (defined($webtask)) {
	# Cause of the fork in run_with_ssh.
	$webtask->Refresh();
	$webtask->status("finishing");
    }

    #
    # If we timed out, if the result code was bad, or if the image size
    # grew too large.
    #
    if ($result eq "setupfailed") {
	$msg = "FAILED: Node setup failed ...";
	goto out;
    }
    if ($result eq "timeout") {
	$msg = "FAILED: Timed out generating image ...";
	goto out;
    }
    if ($result eq "toobig") {
	$msg = "FAILED: Maximum image size (".$self->maximagesize()." bytes) exceeded ...";
	goto out;
    }
    if ($result ne "0") {
	$msg = "FAILED: Returned error code $result generating image ...";
	goto out;
    }

    # We want to Validate that the image made it to the repository;
    # also, Validate has the side-effects of updating the DB with the
    # size/hash fields.
    ($rc,$msg) = $self->Validate($image,{'update'=>1,'validate'=>{'all'=>1}});
    if ($rc) {
	$msg = "$self CaptureImage: failed validation: $msg";
	goto out;
    }
    # Pick up the new size/hash info.
    #$image->Refresh();

    if (defined($webtask)) {
	$webtask->Refresh();
	my $sz = int($image->size());
	$webtask->imagesize($sz / 1024)
	    if ($sz > 0);
    }

    my $cname = "$imagepid/$imagename";
    $cname .= ":" . $image->version()
	if ($args->{'doprovenance'});
    print "$cname: ";
    print "image creation succeeded, written to $path.\n";
          "Final size: ".$image->size()." bytes.\n";

    ($rc,$msg) = $self->CreateImageFinalize($image,$node,$args);
    goto out
	if ($rc);

    $rc = 0;

  out:
    $image->Unlock()
        if ($needunlock);
    if ($rc) {
	tbwarn("$self CaptureImage: $msg\n");
    }
    if (wantarray) {
	return ($rc,$msg);
    }
    else {
	return $rc;
    }
}

sub CLI_FORCE_NONE() { return 0; }
sub CLI_FORCE_TOKEN() { return 1; }
sub CLI_FORCE_SETUID() { return 2; }

sub GetDockerRegCLICommandPrefix($$$$$$$) {
    my ($self,$op,$repo,$context,$force,$setuidref,$cleanupref) = @_;
    if (!defined($force)) {
	$force = CLI_FORCE_NONE();
    }

    my $dosetuid = 0;
    my $this_user;
    my $username;
    if ($UID != 0) {
	$this_user = User->ThisUser();
	if (!defined($this_user)) {
	    return (undef,"You ($UID) do not exist!");
	}
    }
    else {
	$username = "root";
    }

    my $debugarg = "";
    if ($self->debug()) {
	$debugarg = "-d";
    }

    #
    # First, see if we should be using the setuid root path, and the
    # admin ssl cert.
    #
    if (($force == CLI_FORCE_NONE()
	 && exists($ENV{"WITH_TB_ADMIN_PRIVS"})
	 && $ENV{"WITH_TB_ADMIN_PRIVS"} eq "1")
	|| $force == CLI_FORCE_SETUID()) {
	# Check if we have setuid privs, so we can use the admin cert;
	# or if we'll need a temp token.  No other way I know to do this
	# in perl other than to try!
	if ($EUID != 0) {
	    my $SAVEEUID = $EUID;
	    $EUID = 0;
	    if ($EUID == 0) {
		$dosetuid = 1;
	    }
	    $EUID = $SAVEEUID;

	    if ($dosetuid != 1) {
		if ($force == CLI_FORCE_SETUID()) {
		    return (undef,"not setuid!");
		}
		else {
		    tbwarn("$self: GetDockerRegCLICommandPrefix: invoked with".
			   " wap but not setuid; falling back to token auth!\n");
		    $force = CLI_FORCE_TOKEN();
		}
	    }
	}
    }
    if ($dosetuid == 1 || ($force != CLI_FORCE_TOKEN()
			   && ($UID == 0 || $EUID == 0))) {
	$$setuidref = 1;
	return ("$ADMINDOCKREGCLI $debugarg",undef);
    }
    else {
	$$setuidref = 0;
    }

    if ($this_user->uid() eq 'geniuser') {
	# If the current user is geniuser, there might be a localuser or
	# not; so just use token auth for this.
	$force = CLI_FORCE_TOKEN();
    }

    if ($force == CLI_FORCE_TOKEN()) {
	my ($docker_token_user,$docker_token_pass);
	$docker_token_user = $this_user->uid() . "-$context";
	$docker_token_pass = TBGenSecretKey();
	if (User->AddTokenPassword(
		$this_user,$this_user,"docker.registry",$op,$repo,
		$docker_token_user,$docker_token_pass,undef,600,600,0,1)) {
	    return (undef,
		    "Could not create temporary Docker Registry credentials");
	}
	else {
	    $$cleanupref = sub { User->DeleteTokenPasswords(
				     $this_user,$this_user,"docker.registry",
				     $docker_token_user,$docker_token_pass); };
	}

	return ("$DOCKREGCLI $debugarg".
		" -u $docker_token_user -p $docker_token_pass",undef);
    }
    else {
	my ($uid,$homedir) = ($this_user->uid(),$this_user->HomeDir());
	return ("$DOCKREGCLI $debugarg".
		" -u $uid -p '' --cert $homedir/.ssl/emulab.pem",undef);
    }
}

sub DeleteImageFiles($$$) {
    my ($self,$image,$args) = @_;
    if (!defined($args)) {
	$args = {};
    }
    my $versonly = $args->{'versonly'} || 0;
    my $purge = $args->{'purge'} || 0;
    my $rename = $args->{'rename'} || 0;
    my $impotent = $args->{'impotent'} || 0;
    my $msg = "";
    my $rc = -1;
    my $cmd;

    #
    # When doing image provenance, we have to deal with all versions
    # of the image. This will not return deleted versions.
    #
    my @images = ();
    if ($image->AllVersions(\@images)) {
	$msg = "Could not get list of image (versions)";
	goto out;
    }
    #
    # When deleting just a single version, if this is the last or only
    # version, then turn off version only. Makes no sense to have a
    # descriptor with no non-deleted versions.
    #
    if ($versonly && scalar(@images) == 1) {
	$versonly = 0;
    }
    if ($versonly) {
	@images = ($image);
    }

    my $setuid = 0;
    my $cleanup;
    my $SAVEEUID;

    #
    # Grab our command prefix.  If that creates a token for us, we use
    # it for all versions.
    #

    foreach my $imageversion (@images) {
531 532 533 534
	# Skip NULL or '' paths.
	next
	    if (!defined($imageversion->path()) || $imageversion->path() eq "");

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 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 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 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 781 782 783 784 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 815 816 817 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 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
	# Split the path into server, repo, and tag.
	my ($server,$repo,$tag);
	if ($imageversion->path() =~ /^([^\/]+)\/([^:]+):(.*)$/) {
	    ($server,$repo,$tag) = ($1,$2,$3);
	}
	else {
	    $msg = "$self DeleteImageFiles: bad path ".$imageversion->path().
		"; aborting!";
	    goto out;
	}

	if ($impotent) {
	    print STDERR "$self DeleteImageFiles: would have deleted" .
		" $server $repo $tag\n";
	    next;
	}

	if ($rename) {
	    my $newtag = $imageversion->imageid() . "-$tag";
	    ($setuid,$cleanup) = (0,undef);
	    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
		"image.rename",$repo,"image-delete-rename",CLI_FORCE_NONE(),
		\$setuid,\$cleanup);
	    if (!defined($cmd)) {
		$msg = "$self DeleteImageFiles: $msg";
		goto errout;
	    }
	    my $tcmd = "$cmd -s $server tag_image -r $repo -t $tag -n $newtag";
	    if ($self->debug()) {
		print STDERR "$self DeleteImageFiles: running '$tcmd'\n";
	    }
	    if ($setuid) {
		$SAVEEUID = $EUID;
		$EUID = 0;
	    }
	    $rc = system($tcmd);
	    $EUID = $SAVEEUID
		if ($setuid);
	    $cleanup->()
		if (defined($cleanup));
	    if ($rc) {
		$msg = "$self DeleteImageFiles: failed to rename tag" .
		    " $imageversion ($server $repo $tag) to $newtag!";
		goto out;
	    }

	    $tcmd = "$cmd -s $server delete_tag -r $repo -t $tag";
	    if ($self->debug()) {
		print STDERR "$self DeleteImageFiles: running '$tcmd'\n";
	    }
	    if ($setuid) {
		$SAVEEUID = $EUID;
		$EUID = 0;
	    }
	    $rc = system($tcmd);
	    $EUID = $SAVEEUID
		if ($setuid);
	    $cleanup->()
		if (defined($cleanup));
	    if ($rc) {
		$msg = "$self DeleteImageFiles: failed to delete old tag" .
		    " in rename of $imageversion ($server $repo $tag) to" .
		    " $newtag!";
		goto out;
	    }
	}
	elsif ($purge) {
	    ($setuid,$cleanup) = (0,undef);
	    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
		"image.pull",$repo,"image-delete-check",CLI_FORCE_NONE(),
		\$setuid,\$cleanup);
	    if (!defined($cmd)) {
		$msg = "$self DeleteImageFiles: $msg";
		goto errout;
	    }
	    my $tcmd = "$cmd -s $server check_image -r $repo -t $tag";
	    if ($self->debug()) {
		print STDERR "$self DeleteImageFiles: running '$tcmd'\n";
	    }
	    if ($setuid) {
		$SAVEEUID = $EUID;
		$EUID = 0;
	    }
	    $rc = system($tcmd);
	    $EUID = $SAVEEUID
		if ($setuid);
	    $cleanup->()
		if (defined($cleanup));
	    if ($rc) {
		if ($self->debug()) {
		    print STDERR "$self DeleteImageFiles: $image ($server".
			" $repo $tag) file already gone; nothing to delete.\n";
		}
		($rc,$msg) = (0,0);
		goto out;
	    }

	    ($setuid,$cleanup) = (0,undef);
	    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
		"image.delete",$repo,"image-delete-tag",CLI_FORCE_NONE(),
		\$setuid,\$cleanup);
	    if (!defined($cmd)) {
		$msg = "$self DeleteImageFiles: $msg";
		goto errout;
	    }
	    $tcmd = "$cmd -s $server delete_image -r $repo -t $tag";
	    if ($self->debug()) {
		print STDERR "$self DeleteImageFiles: running '$tcmd'\n";
	    }
	    if ($setuid) {
		$SAVEEUID = $EUID;
		$EUID = 0;
	    }
	    $rc = system($tcmd);
	    $EUID = $SAVEEUID
		if ($setuid);
	    $cleanup->()
		if (defined($cleanup));
	    if ($rc) {
		$msg = "$self DeleteImageFiles: failed to delete image" .
		    " $imageversion ($server $repo $tag)!";
		goto out;
	    }
	}
	elsif ($self->debug()) {
	    print STDERR "$self DeleteImageFiles: nothing to do for" .
		" $server $repo $tag\n";
	}
    }

    $rc = 0;

  out:
    tbwarn("$self DeleteImageFiles: $msg\n")
	if ($rc);
    if (wantarray) {
	return ($rc,$msg);
    }
    else {
	return $rc;
    }
}

sub Validate($$;$) {
    my ($self,$image,$args) = @_;
    my ($rc,$msg,$cmd,$userperm);

    if (!defined($args)) {
	$args = {};
    }
    if ($self->debug()) {
	use Data::Dumper;
	print STDERR "$self Validate: args: ".Dumper($args)."\n";
    }

    if (!defined($image) || !ref($image)
	|| !($image->isa("Image") || $image->isa("OSImage"))) {
	$msg = "image ($image) is not an Image!";
	goto errout;
    }

    if ($args->{'update'}) {
	$userperm = TB_IMAGEID_MODIFYINFO();
    }
    else {
	$userperm = TB_IMAGEID_READINFO();
    }

    # Split the path into server, repo, and tag.
    my ($server,$repo,$tag);
    if ($image->path() =~ /^([^\/]+)\/([^:]+):(.*)$/) {
	($server,$repo,$tag) = ($1,$2,$3);
    }
    else {
	$msg = "Invalid Docker image path: ".$image->path()."!";
	goto errout;
    }

    my $setuid = 0;
    my $cleanup;
    my $SAVEEUID;

    #
    # Ensure the manifest and layers are all present.
    #
    ($setuid,$cleanup) = (0,undef);
    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
	"image.pull",$repo,"validate",CLI_FORCE_NONE(),\$setuid,\$cleanup);
    if (!defined($cmd)) {
	$msg = "$self Validate: $msg";
	goto errout;
    }
    $cmd .= " -s $server check_image -r $repo -t $tag";
    if ($self->debug()) {
	print STDERR "$self: validating Docker image ($server,$repo,$tag)\n";
	print STDERR "$self: validation command: $cmd\n";
    }
    if ($setuid) {
	$SAVEEUID = $EUID;
	$EUID = 0;
    }
    $rc = system($cmd);
    $EUID = $SAVEEUID
	if ($setuid);
    $cleanup->()
	if (defined($cleanup));
    if ($rc) {
	$msg = "Error validating Docker image!";
	goto errout;
    }

    # Now grab the manifest metadata to populate the DB, if we're
    # supposed to update:
    if ($args->{'update'}) {
	if ($self->debug()) {
	    print STDERR "$self: updating Docker image metadata" .
		" ($server,$repo,$tag)\n";
	}
	my @lines;

	($setuid,$cleanup) = (0,undef);
	($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
	    "image.pull",$repo,"validate",CLI_FORCE_NONE(),\$setuid,\$cleanup);
	if (!defined($cmd)) {
	    $msg = "$self Validate: $msg";
	    goto errout;
	}
	$cmd .= " -s $server get_image_metadata -r $repo -t $tag";
	if ($self->debug()) {
	    print STDERR "$self: metadata command: $cmd\n";
	}
	if ($setuid) {
	    $SAVEEUID = $EUID;
	    $EUID = 0;
	}
	@lines = `$cmd`;
	$rc = $?;
	$EUID = $SAVEEUID
	    if ($setuid);
	$cleanup->()
	    if (defined($cleanup));
	if ($rc) {
	    $msg = "Error getting Docker image reference metadata!";
	    goto errout;
	}
	if ($self->debug()) {
	    print STDERR "$self Validate: ".join('',@lines)."\n";
	}
	for my $line (@lines) {
	    chomp($line);
	}

	if ($args->{'validate'}{'all'} || $args->{'validate'}{'hash'}) {
	    if ($self->debug()) {
		print STDERR "$self Validate: updating hashes\n";
	    }
	    my ($alg,$hash);
	    my ($lnum,$lalg,$lhash,$lsize);
	    my $maxlayer = -1;
	    for my $line (@lines) {
		if ($line =~ /^digest:\s+([^:]+):([\w\d]+)$/) {
		    ($alg,$hash) = ($1,$2);
		    if ($self->debug()) {
			print STDERR "$self: digest: $alg, $hash\n";
		    }
		}
		elsif ($line =~ /^layer\[(\d+)\]:\s+([^:]+):(\w+),\s+(\d+)$/) {
		    if (int($1) > $maxlayer) {
			$lnum = int($1);
			$maxlayer = $lnum;
			($lalg,$lhash,$lsize) = ($2,$3,$4);
		    }
		    if ($self->debug()) {
			print STDERR "$self: layer: $1, $2, $3, $4\n";
		    }
		}
	    }
	    if (!defined($alg) || !defined($hash)) {
		$msg = "Unrecognized algorithm:hash digest for tag $tag!";
		goto errout;
	    }
	    elsif ($alg ne 'sha256') {
		$msg = "unexpected Docker digest algorithm $alg; not inserting!";
		goto errout;
	    }
	    if (!defined($lalg) || !defined($lhash)) {
		$msg = "Unrecognized algorithm:hash digest for layers for" .
		    " tag $tag!";
		goto errout;
	    }
	    elsif ($lalg ne 'sha256') {
		$msg = "unexpected Docker digest algorithm $alg for layer" .
		    " $lhash; not inserting as delta hash!";
		goto errout;
	    }

	    $image->SetHash($hash);
	    $image->SetDeltaHash($lhash);
	    if ($self->debug()) {
		print STDERR "$self Validate: set hash $hash, delta hash $lhash\n";
	    }
	}
	if ($args->{'validate'}{'all'} || $args->{'validate'}{'size'}) {
	    if ($self->debug()) {
		print STDERR "$self Validate: updating sizes\n";
	    }
	    my ($size,$lalg,$lhash,$lsize,$lnum);
	    my $maxlayer = -1;
	    for my $line (@lines) {
		if ($line =~ /^size:\s+(\d+)$/) {
		    $size = $1;
		    if ($self->debug()) {
			print STDERR "$self: size: $size\n";
		    }
		}
		elsif ($line =~ /^layer\[(\d+)\]:\s+([^:]+):(\w+),\s+(\d+)$/) {
		    if (int($1) > $maxlayer) {
			$lnum = int($1);
			$maxlayer = $lnum;
			($lalg,$lhash,$lsize) = ($2,$3,$4);
		    }
		    if ($self->debug()) {
			print STDERR "$self: layer size: $1, $2, $3, $lsize\n";
		    }
		}
	    }
	    if (!defined($size)) {
		$msg = "No size for tag $tag!";
		goto errout;
	    }
	    elsif (!defined($lsize)) {
		$msg = "No layer size for tag $tag!";
		goto errout;
	    }

	    $image->SetSize(int($size));
	    $image->SetDeltaSize(int($lsize));
	    if ($self->debug()) {
		print STDERR "$self Validate: size $size, delta size $lsize\n";
	    }
	}

	#
	# Sanitize the updated timestamp for any update.  If it is NULL,
	# that will break tmcd and anything else that assumes a non-null
	# mtime.  So, if it is NULL, one was never set; just use the
	# ctime.  Otherwise, do nothing.
	#
	my $stamp;
	$image->GetUpdate(\$stamp);
	if (!defined($stamp) || $stamp eq '' || $stamp == 0) {
	    $image->GetCreate(\$stamp);
	    $image->MarkUpdate(undef,$stamp);
	}
    }

  out:
    if (wantarray) {
	return (0,"");
    }
    return 0;

  errout:
    tbwarn("$self Validate: $msg\n");
    if (wantarray) {
	return (-1,$msg);
    }
    return -1;
}

sub UpdateHash($$;$) {
    my ($self,$image,$args) = @_;
    my ($cmd,$msg,$rc);

    my $debugarg = "";
    if ($self->debug()) {
	$debugarg = "-d";
    }
    my $userperm;
    my $impotent = 0;
    if (exists($args->{"impotent"})) {
	$impotent = $args->{"impotent"};
    }
    if ($impotent) {
	$userperm = TB_IMAGEID_MODIFYINFO();
    }
    else {
	$userperm = TB_IMAGEID_READINFO();
    }

    if (!defined($image) || !ref($image)
	|| !($image->isa("Image") || $image->isa("OSImage"))) {
	$msg = "image ($image) is not an Image!";
	goto errout;
    }

    # Split the path into server, repo, and tag.
    my ($server,$repo,$tag);
    if ($image->path() =~ /^([^\/]+)\/([^:]+):(.*)$/) {
	($server,$repo,$tag) = ($1,$2,$3);
    }
    else {
	$msg = "Invalid Docker image path: ".$image->path()."!";
	goto errout;
    }

    if ($self->debug()) {
	print STDERR "$self: updating Docker image hash ($server,$repo,$tag)\n";
    }

    my $setuid = 0;
    my $cleanup;
    my $SAVEEUID;

    ($setuid,$cleanup) = (0,undef);
    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
	"image.pull",$repo,"updatehash",CLI_FORCE_NONE(),\$setuid,\$cleanup);
    if (!defined($cmd)) {
	$msg = "$self UpdateHash: $msg";
	goto errout;
    }
    $cmd .= " -s $server get_reference_metadata -r $repo --reference $tag";
    if ($self->debug()) {
	print STDERR "$self: validating Docker image ($server,$repo,$tag)\n";
	print STDERR "$self: validation command: $cmd\n";
    }
    if ($setuid) {
	$SAVEEUID = $EUID;
	$EUID = 0;
    }
    my @lines = `$cmd`;
    $rc = $?;
    $EUID = $SAVEEUID
	if ($setuid);
    $cleanup->()
	if (defined($cleanup));
    if ($rc) {
	$msg = "Error getting Docker image digest!";
	goto errout;
    }

    my ($alg,$hash);
    for my $line (@lines) {
	chomp($line);
	if ($line =~ /^digest:\s+([^:]+):(\w+)$/) {
	    ($alg,$hash) = ($1,$2);
	    if ($self->debug()) {
		print STDERR "$self: $alg, $hash\n";
	    }
	    last;
	}
    }
    if (!defined($alg) || !defined($hash)) {
	$msg = "Unrecognized algorithm:hash digest for reference $tag!";
	goto errout;
    }
    elsif ($alg ne 'sha256') {
	$msg = "unexpected Docker digest algorithm $alg; not inserting!";
	goto errout;
    }

    if (!$impotent) {
	if ($image->SetHash($hash) != 0) {
	    $msg = "Failed to set the hash for $image";
	    goto errout;
	}
    }

  out:
    if (wantarray) {
	return ($hash,"");
    }
    return $hash;

  errout:
    tbwarn("$self UpdateHash: $msg\n");
    if (wantarray) {
	return (undef,$msg);
    }
    return undef;
}

sub Release($$;$) {
    my ($self,$image,$args) = @_;
    my ($rc,$msg) = (-1,"");

    my ($quiet,$force,$markready,$impotent,$validate) = (0,0,0,0,1);
    if (!defined($args)) {
	$args = {};
    }
    if (exists($args->{'impotent'})) {
	$impotent = $args->{'impotent'};
    }
    if (exists($args->{'quiet'})) {
	$quiet = $args->{'quiet'};
    }
    if (exists($args->{'force'})) {
	$force = $args->{'force'};
    }
    if (exists($args->{'markready'})) {
	$markready = $args->{'markready'};
    }

    ($rc,$msg) = $self->_ReleaseChecks($image,$args);
    if ($rc) {
	goto errout;
    }

    if ($force && $markready) {
	if ($impotent) {
	    print "Would mark image ready/released, but not do anything else\n"
		if (!$quiet);
	}
	else {
	    print "Marking image ready/released, but not doing anything else\n"
		if (!$quiet);
	    $image->MarkReady();
	    $image->MarkReleased();
	}
	goto out;
    }

    my $needunlock = 0;

    #
    # Before we do anything destructive, we lock the image.
    #
    if ($image->Lock()) {
	$msg = "Image is locked, please try again later!";
	goto errout;
    }
    $needunlock = 1;

    if ($validate) {
	if ($impotent) {
	    print STDERR "Would run imagevalidate on " .
		$image->versname() . "\n" if (!$quiet);
	}
	else {
	    if ($self->debug()) {
		print STDERR "Running imagevalidate on " .
		    $image->versname() . "\n";
	    }
	    ($rc,$msg) = $self->Validate($image);
	    if ($rc) {
		$msg = "Failed to validate the image: $msg";
		goto errout;
	    }
	}
    }
    # Now mark as released.
    if ($impotent) {
	print STDERR "Would mark image as released\n"
	    if (!$quiet);
    }
    elsif ($image->Release()) {
	$msg = "Could not mark image as released!";
	goto errout;
    }

  out:
    $image->Unlock()
	if ($needunlock);
    if (wantarray) {
	return (0,"");
    }
    return 0;

  errout:
    $image->Unlock()
        if ($needunlock);
    tbwarn("$self Release: $msg\n");
    if (wantarray) {
	return (-1,$msg);
    }
    return -1;
}

sub ImportImageContent($$;$) {
    my ($self,$image,$args) = @_;
    if (!defined($args)) {
	$args = {};
    }
    my ($rc,$msg) = (-1,"");

    my ($origin_path,$newhash,$downloaded_ref,$force) = (undef,undef,undef,0);
    my $locked = 0;
    my $needunlock = 0;
    if (exists($args->{'origin_path'})) {
	$origin_path = $args->{'origin_path'};
    }
    else {
	$msg = "No origin docker registry path provided";
	goto errout;
    }
    if (exists($args->{'newhash'})) {
	$newhash = $args->{'newhash'};
    }
    if (exists($args->{'downloaded_ref'})) {
	$downloaded_ref = $args->{'downloaded_ref'};
    }
    if (exists($args->{'force'})) {
	$force = $args->{'force'};
    }
    if (exists($args->{'locked'})) {
	$locked = $args->{'locked'};
    }

    #
    # Make sure we are already locked; lock if not.
    #
    if (!$locked) {
	if ($image->Lock()) {
	    $msg = "$self ImportImageContent: $image is already locked,".
		" please try again later ($PID)!";
	    goto out;
	}
	$needunlock = 1;
    }

    #
    # Like in CaptureImage, we need to fixup the path to point to our
    # local registry; and a few other things below:
    #
    my ($path,$server,$repo,$tag);
    ($path,$msg) = $self->GetLocalRegistryPathForImage(
	$image,\$server,\$repo,\$tag);
    if (!defined($path)) {
	$rc = -1;
	goto errout;
    }

    my $doit = 0;
    if ((defined($newhash) && $newhash ne $image->hash()) || $force) {
	$doit = 1;
    }
    else {
	#
	# Check to see if the image already exists at the path; don't
	# need it if it's here.
	#
	my $setuid = 0;
	my $cleanup;
	my $SAVEEUID;
	my $cmd;

	($setuid,$cleanup) = (0,undef);
	($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
	    "image.pull",$repo,"validate",CLI_FORCE_NONE(),\$setuid,\$cleanup);
	if (!defined($cmd)) {
	    tbwarn("$self ImportImageContent: $msg; skipping validation");
	}
	else {
	    $cmd .= " -s $server check_image -r $repo -t $tag";
	    if ($self->debug()) {
		print STDERR "$self: checking Docker image ($server,$repo,$tag)\n";
		print STDERR "$self: validation command: $cmd\n";
	    }
	    if ($setuid) {
		$SAVEEUID = $EUID;
		$EUID = 0;
	    }
	    $rc = system($cmd);
	    $EUID = $SAVEEUID
		if ($setuid);
	    $cleanup->()
		if (defined($cleanup));
	    if ($rc) {
		if ($self->debug()) {
		    print STDERR "$self ImportImageContent: $image not".
			" present; will download\n";
		}
		$doit = 1;
	    }
	}
    }

    #
    # Just return if we already have the right image and aren't forcing.
    #
    if (!$doit) {
	goto out;
    }

    #
    # Update the image to point to the repo/tag; change its format.
    #
    $image->SetPath($path);
    $image->SetFormat("docker");
    #
    # Also update the image to run on type pcvm, so that we can do real
    # osloads of this image on pcvms.  This should probably be somewhere
    # else, but no big deal.
    #
    $image->SetRunsOnNodeType('pcvm');

    my ($rserver,$rrepo,$rtag);
    if ($origin_path =~ /^([^\/]+)\/([^:]+):(.*)$/) {
	($rserver,$rrepo,$rtag) = ($1,$2,$3);
    }
    else {
	$msg = "$self ImportImageContent: could not extract remote docker".
	    " registry info from $origin_path!";
	goto errout;
    }

    #
    # Now we can pull and push the image all in one go, using our local
    # admin credentials both times.  NB: for this one, we *require*
    # admin credential access so we can pull any image from the remote
    # cluster.
    #
    my $setuid = 1;
    my $cleanup;
    my $SAVEEUID;
    my $cmd;

    my $idir = File::Temp->newdir(TEMPLATE=>"docker-image-XXXXXX",DIR=>"/tmp");
    my $filebasename = $idir->dirname() . "image";
    ($setuid,$cleanup) = (0,undef);
    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
	"image.pull",$rrepo,"validate",CLI_FORCE_SETUID(),
	\$setuid,\$cleanup);
    if (!defined($cmd) || !$setuid) {
	$msg = "$self ImportImageContent: error getting admin CLI prefix;".
	    " aborting!";
	goto errout;
    }
    $cmd .= " -s $rserver pull_image -r $rrepo -t $rtag -f $filebasename";
    if ($self->debug()) {
	print STDERR "$self: pulling remote Docker image into $filebasename".
	    " ($rserver,$rrepo,$rtag)\n";
	print STDERR "$self: command: $cmd\n";
    }
    $SAVEEUID = $EUID;
    $EUID = 0;
    $rc = system($cmd);
    $EUID = $SAVEEUID;
    if ($rc) {
	$msg = "$self ImportImageContent: error pulling remote image!";
	goto errout;
    }

    #
    # And now we push it into our local registry.
    #
    ($setuid,$cleanup) = (0,undef);
    ($cmd,$msg) = $self->GetDockerRegCLICommandPrefix(
	"image.push",$repo,"push",CLI_FORCE_SETUID(),\$setuid,\$cleanup);
    if (!defined($cmd) || !$setuid) {
	$msg = "$self ImportImageContent: error getting admin CLI prefix;".
	    " aborting!";
	goto errout;
    }
    $cmd .= " -s $server push_image -r $repo -t $tag -f $filebasename";
    if ($self->debug()) {
	print STDERR "$self: pushing remote Docker image from $filebasename".
	    " ($server,$repo,$tag)\n";
	print STDERR "$self: command: $cmd\n";
    }
    $SAVEEUID = $EUID;
    $EUID = 0;
    $rc = system($cmd);
    $EUID = $SAVEEUID;
    if ($rc) {
	$msg = "$self ImportImageContent: error pushing remote image to".
	    " local registry!";
	goto errout;
    }

    #
    # Now we validate the image, just as in CaptureImage.
    #
    if ($self->debug()) {
	print STDERR "Running imagevalidate on " . $image->versname() . "\n";
    }
    ($rc,$msg) = $self->Validate($image,{'update'=>'1','validate'=>{'all'=>1}});
    if ($rc) {
	$msg = "Failed to validate $image: $msg";
	goto errout;
    }

    if (defined($downloaded_ref)) {
	$$downloaded_ref = 1;
    }

  out:
    $image->Unlock()
	if ($needunlock);
    if (wantarray) {
	return (0,"");
    }
    return 0;

  errout:
    $image->Unlock()
        if ($needunlock);
    tbwarn("$self ImportImageContent: $msg\n");
    if (wantarray) {
	return (-1,$msg);
    }
    return -1;
}

1;