create_image.in 40.4 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh Stoller's avatar
Leigh Stoller committed
2
#
3
# Copyright (c) 2000-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 Stoller's avatar
Leigh Stoller committed
23
#
24
use strict;
25 26
use English;
use Getopt::Std;
27
use POSIX qw(setsid :sys_wait_h);
28
use File::Basename;
29
use Cwd qw(realpath);
30

31
#
32
# Image Creation Tuneables.
33
#
34 35 36
# $maxwait	Max total wall clock time to allow for image collection.
#		We abort after this length of time even if we are still
#		actively making progress collecting the image.
37 38 39
#		Empirically we have observed about 1.6MB/sec on a pc850
#		for a Windows image (the slowest to create), so figuring
#		1.5MB/sec for a 6GB max image works out to around 72 minutes.
40
#		This value comes from sitevar images/create/maxwait if set.
41
#
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
# $idlewait	Max time to allow between periods of progress.
#		This value ensures that if we get stuck and stop making
#		progress, we don't have to wait the potentially very long
#		time til the $maxwait time expires to notice and abort.
#		This value comes from sitevar images/create/idlewait if set.
#
# $checkwait	Time between progress checks (must be int div of $idlewait)
#		Hardwired here, does not come from DB.
#
# $reportwait	Time between progress reports (must be multiple of $checkwait)
#		Hardwired here, does not come from DB.
#
# $maximagesize	Max size in bytes of an image.  Currently this is site-wide
#		and comes from sitevar images/create/maxsize if set. It should
#		probably be finer-grained (per-project? per-user?) than that.
57
#
58
my $maxwait      = (72 * 60);
59 60 61
my $idlewait     = ( 8 * 60);
my $reportwait   = ( 2 * 60);
my $checkwait    = 15;
62
my $maximagesize = (6 * 1024**3);
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
#
# Options for imagezipper on the client-side. These apply only to imagezip,
# i.e., the local node imaging process. They also only apply to the latest
# version of the client script (create-versioned-image). For the older path,
# options are hardwired into the create-image script.
#
# Note that since we cannot have spaces in the string passed to the client,
# options are encoded; e.g.:
#   -N -z 9 -d -a SHA1
# would be encoded as:
#   N,z=9,d,a=SHA1
#
# Specific options:
#
# By default we do not create relocations (-N) in the resulting image for a
# couple of reasons. One is that we never did relocation support for GRUB
# partition boot code, so modern Linux images would not have relocations
# anyway. For FreeBSD this does mean that we cannot relocate them (we use
# a relocation for correct disklabel construction), but we never really
# took advantage of this anyway. The second reason is that ranges with
# relocations are always considered different for hash comparisons, so an
# otherwise empty FreeBSD delta image would have 64K of data in it.
#
my $zipperopts = "N";

89 90 91 92 93 94 95 96
#
# Create a disk image.
#
# XXX: Device file should come from DB.
#      Start/count slice computation is not generalized at all.
#
sub usage()
{
97
    print(STDERR
98
	  "Usage: create_image [-wsN] [-p <pid>] <imagename> <node>\n" .
99
	  "switches and arguments:\n".
100
	  "-w          - wait for image to be fully created\n".
101 102
	  "-s          - use ssh instead of frisbee uploader\n".
	  "-N          - use NFS (if available) instead of frisbee uploader\n".
103
	  "-F          - create a full image even if deltas are on\n".
104 105
	  "-D          - create a 'delta' image rather than a full image\n".
	  "-S          - create a signature file for the new image\n".
106 107 108
	  "-A <pct>    - when -D is specified, automatically create a full\n".
	  "              image instead when a delta would be more than\n".
	  "              <pct> percent the size of a full image.\n".
109
	  "-M          - do not boot info MFS, run with ssh from current OS\n".
110 111 112
	  "-p <pid>    - project ID of the image; defaults to system project\n".
	  "<imagename> - imagename to use\n".
	  "<node>      - nodeid to create the image from\n");
113 114
    exit(-1);
}
115
my $optlist  = "p:wsNdfeDSMA:F";
116
my $waitmode = 0;
117 118 119 120
my $usessh   = 0;
my $usenfs   = 0;
my $usefup   = 1;
my $noemail  = 0;
121
my $delta    = 0;
122
my $nodelta  = 0;
123 124
my $nomfs    = 0;
my $signature= 0;
125
my $deltapct = 0;
126
my $webtask;
127 128 129 130 131 132

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
133
my $TBLOGS      = "@TBLOGSEMAIL@";
134
my $BOSSIP	= "@BOSSNODE_IP@";
135
my $CONTROL     = "@USERNODE@";
136
my $NONFS	= @NOSHAREDFS@;
137 138
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
my $WITHDELTAS  = @IMAGEDELTAS@;
139
my $ISFS        = ("@BOSSNODE_IP@" eq "@FSNODE_IP@") ? 1 : 0;
140 141 142 143 144 145

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
146
use EmulabConstants;
147
use libtestbed;
148
use libadminmfs;
149
use Experiment;
150
use Node;
151 152
use User;
use Image;
153
use OSinfo;
154
use Logfile;
155
use WebTask;
156 157
use Project;
use EmulabFeatures;
158 159 160 161 162 163 164 165 166 167 168 169

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

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/sbin:/usr/bin:";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

Leigh Stoller's avatar
Leigh Stoller committed
170 171 172 173 174 175 176 177
#
# 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");
}

178 179
sub cleanup();
sub fatal($);
180
sub check_progress($$);
181
sub run_with_ssh($$);
182

183
my $nodereboot	= "$TB/bin/node_reboot";
184
my $createimage = "/usr/local/bin/create-versioned-image";
185
my $createxenimage = "/usr/local/bin/create-xen-image";
186
my $ocreateimage= "/usr/local/bin/create-image";
187
my $reboot_prep = "@CLIENT_BINDIR@/reboot_prepare";
188
my $EC2SNAP     = "$TB/sbin/ec2import.proxy";
189
my $friskiller  = "$TB/sbin/frisbeehelper";
190
my $osselect    = "$TB/bin/os_select";
191
my $checkquota  = "$TB/sbin/checkquota";
192
my $imagehash	= "$TB/bin/imagehash";
193
my $imagevalidate = "$TB/sbin/imagevalidate";
194
my $SHA1	= "/sbin/sha1";
195
my $SCP		= "/usr/bin/scp";
196 197 198 199
my $def_devtype	= "ad";
my $def_devnum	= 0;
my $devtype;
my $devnum;
200
my $device;
201
my $mereuser    = 0;
202
my $debug       = 1;
203
my $foreground  = 0;
204
my $imagepid    = TB_OPSPID;
205 206
my $logfile;
my $oldlogfile;
207
my $needcleanup = 0;
208
my $needunlock  = 0;
209
my $isvirtnode  = 0;
210
my $isxenhost   = 0;
211
my $isec2node   = 0;
212
my $onsharednode= 0;
213
my $didbackup   = 0;
214 215 216
my $node_id;
my $node;
my ($experiment,$pid);
217
my $doprovenance = 0;
218
my $hacksigfile;
219 220 221 222 223

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
224
my %options = ();
225 226 227
if (! getopts($optlist, \%options)) {
    usage();
}
228 229 230
if (defined($options{"w"})) {
    $waitmode = 1;
}
231 232 233
if (defined($options{"e"})) {
    $noemail = 1;
}
234
if (defined($options{"s"})) {
235 236 237 238 239 240 241 242 243 244 245
    $usessh = 1;
    $usefup = $usenfs = 0;
}
if (defined($options{"N"})) {
    if (!$NONFS) {
	$usenfs = 1;
	$usefup = $usessh = 0;
    } else {
	print STDERR "NFS not available, cannot use -N\n";
	exit(1);
    }
246 247 248 249
}
if (defined($options{"d"})) {
    $debug = 1;
}
250 251
if (defined($options{"f"})) {
    $foreground = 1;
252
    $waitmode = 0;
253
}
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
if (defined($options{"D"})) {
    if (!$WITHDELTAS) {
	print STDERR "Delta image support not enabled\n";
	exit(1);
    }
    $delta = 1;
}
if (defined($options{"S"})) {
    if (!$WITHDELTAS) {
	print STDERR "Delta image support not enabled\n";
	exit(1);
    }
    $signature = 1;
}
if (defined($options{"M"})) {
    $nomfs = 1;
    $usessh = 1;
}
272 273 274 275 276 277 278 279 280 281 282 283
if (defined($options{"A"})) {
    if (!$WITHDELTAS) {
	print STDERR "Delta image support not enabled\n";
	exit(1);
    }
    if ($options{"A"} =~ /^(\d+)$/) {
	$deltapct = int($1);
    } else {
	print STDERR "Invalid percentage for -A\n";
	exit(1);
    }
}
284 285 286
if (defined($options{"F"})) {
    $nodelta = 1;
}
287
if (@ARGV != 2) {
288 289 290
    usage();
}

291
my $imagename  = $ARGV[0];
292
my $target     = $ARGV[1];
293

294 295 296 297 298 299 300
#
# There is no reason to run as root unless we are taking a snapshot
# of a VM on a shared node. In that case we will flip back when
# we do the ssh over.
#
$EUID = $UID;

301 302 303
#
# Untaint the arguments.
#
304
if ($imagename =~ /^([-\w\.\+:]+)$/) {
305 306 307
    $imagename = $1;
}
else {
308 309
    die("*** $0:\n".
	"    Bad data in $imagename.\n");
310 311 312 313 314
}
    
if (defined($options{"p"})) {
    $imagepid = $options{"p"};
	
315
    if ($imagepid =~ /^([-\w\.]+)$/) {
316 317 318
	$imagepid = $1;
    }
    else {
319 320
	die("*** $0:\n".
	    "    Bad data in $imagepid.\n");
321
    }
322 323
}

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
#
# Reset default values from site variables if they exist.
#
my $tmp;
if (TBGetSiteVar("images/create/maxwait", \$tmp)) {
    $maxwait = $tmp * 60;
}
if (TBGetSiteVar("images/create/idlewait", \$tmp)) {
    $idlewait = $tmp * 60;
}
if (TBGetSiteVar("images/create/maxsize", \$tmp)) {
    $maximagesize = $tmp * 1024**3;
}
$idlewait = $maxwait
    if ($maxwait < $idlewait);
$reportwait = $idlewait
    if ($idlewait < $reportwait);
$checkwait = $reportwait
    if ($reportwait < $checkwait);

344
#
345
# Verify user and get his DB uid and other info for later.
346
#
347 348
my $this_user = User->ThisUser();
if (! defined($this_user)) {
Mike Hibler's avatar
Mike Hibler committed
349
    die("You ($UID) do not exist!\n");
350
}
351 352 353
my $user_uid   = $this_user->uid();
my $user_name  = $this_user->name();
my $user_email = $this_user->email();
354

355 356
if ($UID && ! $this_user->IsAdmin()) {
    $mereuser = 1;
357 358
}

359 360 361 362 363
#
# Grab the imageid description from the DB. We do a permission check, but
# mostly to avoid hard to track errors that would result if the user picked
# the wrong one (which is likely to happen no matter what I do).
#
364 365
my $image = Image->Lookup($imagepid, $imagename);
if (!defined($image)) {
366 367
    die("*** $0:\n".
	"    No such image descriptor $imagename in project $imagepid!\n");
368
}
369
my $imageid = $image->imageid();
370
my $version = $image->version();
371
$imagename  = $image->imagename(); # strip any version
372

373
if ($mereuser &&
374
    ! $image->AccessCheck($this_user, TB_IMAGEID_ACCESS)) {
375 376
    die("*** $0:\n".
	"    You do not have permission to use imageid $imageid!\n");
377 378
}

379 380 381 382 383 384 385 386 387 388
#
# Before doing anything else, check for overquota ... lets not waste
# our time. Make sure user sees the error by exiting with 1.
#
if (system("$checkquota -p $imagepid $user_uid") != 0) {
    die("*** $0:\n".
	"    You are over your disk quota on $CONTROL; ".
	"please login there and cleanup!\n");
}

389 390 391 392 393 394 395 396 397
#
# See if per-project/per-user provenance feature is set.
#
if ($WITHPROVENANCE) {
    my $project = Project->Lookup($image->pid());
    if (!defined($project)) {
	die("*** $0:\n".
	    "    Could not lookup project for $image\n");
    }
398 399

    # But allow feature override. 
400 401
    $doprovenance = EmulabFeatures->FeatureEnabled("ImageProvenance",
						   $this_user, $project);
402 403 404 405 406 407 408 409 410 411 412
    
    # Temporary override for all geni projects until we can export deltas.
    if ($project->IsNonLocal()) {
	my $feature = EmulabFeatures->Lookup("ImageProvenance");
	if ($feature && $feature->enabled()) {
	    # If globally enabled, disable. If not globally enabled but
	    # doprovenance is on, then it was a per-project enable which
	    # we wanr to respect.
	    $doprovenance = 0;
	}
    }
413 414 415 416 417 418 419 420
}

#
# When provenance is enabled and we have delta support, we always collect
# signatures and we always try to create deltas. Note that we set them to
# a different non-zero value so we can distinguish this case and not print
# various warnings below.
#
421 422 423 424
# XXX We really shouldn't be doing this implicitly--our caller should just
# be specifying the options when provenance is enabled--but this script is
# called from a surprisingly large number of places, so we do!
#
425 426 427 428 429
if ($doprovenance && $WITHDELTAS) {
    $delta = 2
	if ($delta == 0);
    $signature = 2
	if ($signature == 0);
430 431 432 433

    # XXX let's try this for now
    $deltapct = 50
	if ($deltapct == 0);
434 435 436 437

    # Override delta but still collect signatures. 
    $delta = 0
	if ($image->nodelta() || $nodelta);
438 439 440 441
}

my ($srcsigfile, $srcimage, $dstsigfile);

442 443 444 445 446 447 448 449 450 451 452 453
#
# Is it a local node or a remote EC2 node (need to generalize). 
#
if ($target =~ /^.*@.*$/) {
    if ($target =~ /^([-\w\@\+\.]+)$/) {
	$target = $1;
    }
    else {
	die("*** $0:\n".
	    "    Bad data in $target\n");
    }

454 455 456 457 458 459 460 461 462 463
    if ($delta || $signature) {
	# Only warn if they explicitly specified an option
	if ($delta == 1 || $signature == 1) {
	    print STDERR
		"*** WARNING: don't support delta imaging of EC2 images, ".
		"ignoring delta/signature options.\n";
	}
	$delta = $signature = 0;
    }

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
    $isec2node = 1;
    $usefup = $usessh = 0;
    $pid = $image->pid();
}
else {
    if ($target =~ /^([-\w]+)$/) {
	$node_id = $1;
    }
    else {
	die("*** $0:\n".
	    "    Bad data in $target\n");
    }

    # Check node and permission
    $node = Node->Lookup($node_id);
    if (!defined($node)) {
	die("*** $0:\n".
	    "    Invalid node name $node_id!\n");
    }
    $isvirtnode   = $node->isvirtnode();
    $onsharednode = $node->sharing_mode()
	if ($isvirtnode);

    if (! $node->AccessCheck($this_user, TB_NODEACCESS_LOADIMAGE)) {
	die("*** $0:\n".
	    "    You do not have permission to create an image from $node\n");
    }

492 493 494 495 496
    if ($node->IsTainted()) {
	die("*** $0:\n".
	    "    $node is tainted - image creation denied.\n");
    }

497 498 499 500 501 502 503 504 505 506 507 508
    #
    # We need the project id for test below. The target directory for the
    # output file has to be the node project directory, since that is the
    # directory that is going to be NFS mounted by default.
    #
    $experiment = $node->Reservation();
    if (!defined($experiment)) {
	die("*** $0:\n".
	    "    Could not map $node to its experiment object!\n");
    }
    $pid = $experiment->pid();

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    if ($isvirtnode) {
	#
	# Need to know this is a xen-host to tailor method below.
	#
	my $pnode  = Node->Lookup($node->phys_nodeid());
	my $osinfo = OSinfo->Lookup($pnode->def_boot_osid());
	if (!defined($osinfo)) {
	    fatal("Could not get osinfo for $pnode");
	}
	if ($osinfo->FeatureSupported("xen-host")) {
	    $isxenhost = 1;

	    if ($image->mbr_version() == 99) {
		$doprovenance = $delta = $signature = 0;
	    }
	}
    }

527 528 529 530
    # Do not create a delta for system images but still collect signatures.
    $delta = 0
	if ($pid eq TBOPSPID());

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    #
    # If we are creating a delta image, figure out what image we are
    # deriving from so that we can grab the signature.
    #
    if ($delta) {
	#
	# Find the source image we are creating a delta from. When provenance
	# is enabled, we can use the parent image. If not enabled, we attempt
	# to determine what is already on the node via the partitions table.
	#
	# If we cannot determine the source, we just warn and create a full
	# image instead.
	#
	if ($doprovenance) {
	    $srcimage = $image->Parent();
546 547
	}
	if (!defined($srcimage)) {
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
	    (undef, $srcimage) = $node->RunningOsImage();
	}
	if (defined($srcimage)) {
	    $srcsigfile = $srcimage->path() . ".sig";
	    if (! -e "$srcsigfile") {
		# XXX user may not have direct access to a shared image
		my $SAVEUID = $UID;
		$EUID = $UID = 0;
		if (! -e "$srcsigfile") {
		    $srcsigfile = undef;
		}
		$EUID = $UID = $SAVEUID;
	    }
	    if (!defined($srcsigfile)) {
		if ($delta == 1) {
		    print "*** WARNING: no signature file for source image, ".
			"cannot create delta; creating full image instead.\n";
		}
		$delta = 0;
	    }
	} else {
	    if ($delta == 1) {
		print "*** WARNING: no source for image, ".
		    "cannot create delta; creating full image instead.\n";
	    }
	    $delta = 0;
	}
    }

    #
    # If we are creating a signature file for this image, look up the path
    # so we derive the signature file name.
    #
    if ($signature) {
	if (defined($image->path())) {
	    $dstsigfile = $image->path() . ".sig";
	} else {
	    if ($signature == 1) {
		print "*** WARNING: no path for image, ".
		    "cannot create signature file.\n";
	    }
	    $signature = 0;
	}
    }

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    #
    # To avoid blowing a cavernous hole ("allow all TCP ports to boss")
    # in the per-experiment firewall, we don't use the frisbee uploader if
    # the node is firewalled.
    # 
    if ($usefup && $experiment->IsFirewalled()) {
	print "*** WARNING: $node_id is firewalled, not using Frisbee uploader\n";
	$usefup = 0;
	if ($NONFS) {
	    $usenfs = 0;
	    $usessh = 1;
	} else {
	    $usenfs = 1;
	    $usessh = 0;
	}
    }
}

611
#
612 613
# Make sure that the directory exists and is writeable for the user.
# We test this by creating the file. Its going to get wiped anyway.
614
#
615 616
my $filename = $image->path();
my $isglobal = $image->global();
617
my $usepath  = 0;
618 619

#
620
# Redirect pathname for global images. See equiv code in clone_image.
621 622
# XXX if the project of the experiment creating the image is not emulab-ops,
# we make a feeble attempt to avoid clobbering existing files.
623
#
624 625 626 627 628 629 630 631
my $hackprefix;
if ($pid eq TBOPSPID()) {
    $hackprefix = PROJROOT() . "/$pid/images/";
} else {
    $hackprefix = PROJROOT() . "/$pid/images/E_O_";
}
if ($isglobal && ($filename =~ /^$TB/)) {
    $filename = $hackprefix . basename($filename);
632
    print "*** WARNING: Writing global descriptor to $filename instead!\n";
633 634 635 636 637 638 639 640

    #
    # Ditto for the signature file
    #
    if ($dstsigfile && ($dstsigfile =~ /^$TB/)) {
	$dstsigfile = $hackprefix . basename($dstsigfile);
    }

641 642 643 644
    #
    # XXX the Emulab config of the master server doesn't know this trick
    # so when it tries to lookup imageid emulab-ops/<whatever> it would
    # still map to /usr/testbed and fail because it cannot update images
645
    # outside of /{users,group,proj}. So we skirt the issue by passing
646 647 648
    # it the full path contructed here rather than the imageid.
    #
    $usepath = 1;
649
}
650

651 652 653 654 655 656 657 658 659 660 661 662
#
# For the source signature file, we actually have to copy it to
# somewhere where we can read it as well as just fixup the path.
#
if ($srcsigfile && ($srcsigfile =~ /^$TB/)) {
    my $osrcsigfile = $srcsigfile;
    $srcsigfile = $hackprefix . basename($srcsigfile);
    if (system("cp -fp $osrcsigfile $srcsigfile")) {
	die("*** $0:\n".
	    "    Could not copy source signature file ".
	    "$osrcsigfile to $srcsigfile\n");
    }
663 664
    # XXX remember so we can cleanup later
    $hacksigfile = $srcsigfile;
665 666
}

667 668 669 670 671
#
# Make sure real path is someplace that makes sense; remember that the
# image is created on the nodes, and it NFS mounts directories on ops.
# Writing the image to anyplace else is just going to break things.
#
672 673 674
# Use realpath to validate the path. The still use the original path
# for passing to the client-side since boss and the client may not have
# the same real path for a file.
675
#
676
my $ofilename = $filename;
677
my $translated = realpath($filename);
678
if ($translated =~ /^([-\w\.\/\+:]+)$/) {
679 680 681 682 683 684
    $filename = $1;
}
else {
    die("*** $0:\n".
	"    Bad data returned by realpath: $translated\n");
}
685 686 687 688 689
# Make sure not a directory.
if (-d $filename) {
    die("*** $0:\n".
	"    $filename is a directory! Must be a plain file.\n");
}
690 691

#
692
# The file must reside in an allowed directory. Since this script
693 694 695
# runs as the caller, regular file permission checks ensure its a file
# the user is allowed to use. 
#
696
if (! TBValidUserDir($filename, $ISFS)) {
697 698 699 700
    die("*** $0:\n".
	"    $filename does not resolve to an allowed directory!\n");
}

701
#
702
# Before we do anything destructive, we lock the image.
703 704 705
#
if ($image->Lock()) {
    die("*** $0:\n".
706
	"    Image is locked, please try again later!\n");
707 708 709
}
$needunlock = 1;

710
if ($doprovenance && $image->ready()) {
711 712 713 714 715
    $image->Unlock();
    die("*** $0:\n".
	"    $image ready flag is set, this is inconsistent!\n");
}

716 717 718 719 720 721
# See if a web task is tracking this image creation.
$webtask = WebTask->LookupByObject($image->uuid());
if (defined($webtask)) {
    $webtask->AutoStore(1);
}

722 723
#
# Be sure to kill off running frisbee. If a node is trying to load that
724
# image, well tough.
725
#
726 727 728 729 730
if (0) {
    system("$friskiller -k $imageid");
    if ($?) {
	fatal("Could not kill running frisbee for $imageid!");
    }
731
}
732

733
if (-e $filename) {
734 735 736 737 738 739 740 741 742 743 744
    #
    # Back it up in case of failure. Note that the frisbee upload server
    # does this, so we do it only for the ssh/nfs case.
    #
    if (!$usefup) {
	system("/bin/mv -f $filename ${filename}.bak");
	if ($?) {
	    fatal("Could not back up $filename");
	}
	$didbackup = 1;
    }
745 746
}

747
#
748 749 750 751 752 753 754
# We want to truncate the file (we backed it up above), which also
# confirms the user can really create a new file.
#
# XXX The problem is that frisbee upload server does this too, which
# is why we have a lot of zero length backup files. So, in uploader
# mode, make sure the user can create the tmp file that the uploader
# uses.
755
#
756 757 758 759 760 761 762 763 764
if ($usefup) {
    $tmp = "$filename.tmp";
    if (-e "$tmp") {
	unlink("$tmp") ||
	    fatal("Could not remove $tmp: $!");
    }
} else {
    $tmp = $filename;
}
765 766 767 768
open(FILE, "> $tmp") or
    fatal("Could not create $tmp: $!");
close(FILE) or
    fatal("Could not truncate $tmp: $!");
769 770 771 772 773 774 775 776
#
# XXX this script runs as the user creating the image.
# However, in the uploader case, the uploader runs as the creator of
# the image. In the case those two are not the same, we need to make
# sure that the file we create here is group writable.
#
chmod(0664, $tmp) or
    fatal("Could not make $tmp group writable: $!");
777

778
if (! ($isvirtnode || $isec2node)) {
779 780 781 782 783 784 785 786 787 788 789 790
    #
    # Get the disktype for this node
    #
    $node->disktype(\$devtype);
    $node->bootdisk_unit(\$devnum);

    $devtype = $def_devtype
	if (!defined($devtype));
    $devnum = $def_devnum
	if (!defined($devnum));
    $device = "/dev/${devtype}${devnum}";
}
791

792 793 794 795 796 797
#
# Okay, we want to build up a command line that will run the script on
# on the client node. We use the imageid description to determine what
# slice (or perhaps the entire disk) is going to be zipped up. We do not
# allow arbitrary combos of course. 
#
798 799
my $startslice;
my $loadlength;
800
my $command;
801

802 803 804
#
# EC2 images use a special command which is hardwired below.
#
805
if ($isec2node) {
806
    ;
807
}
808 809
#
# Virtnode images use a version of the old create-image script on the vhost
810
# XXX needs to be fixed.
811
#
812
elsif ($isvirtnode && (!$doprovenance || !$isxenhost)) {
813 814 815 816
    $command = "$ocreateimage";
    if ($usefup) {
	my $id;
	if ($usepath) {
817
	    $id = $ofilename;
818
	} else {
819
	    $id = $image->pid() . "/" . $image->imagename();
820 821 822 823
	}
	$command .= " -S $BOSSIP -F $id";
    }

824 825 826
    #
    # XXX Need to add XEN package flag to descriptor.
    #
827
    if ($isxenhost) {
828 829 830 831 832 833
	if ($image->mbr_version() == 99) {
	    $command .= " -p";
	}
	if ($image->loadpart()) {
	    $command .= " -s " . $image->loadpart();
	}
834
    }
835
    $command .= " $node_id";
836 837 838 839

    if ($usefup || $usessh) {
	$command .= " -";
    } else {
840
	$command .= " $ofilename";
841
    }
842
}
843
#
844 845 846 847 848 849 850
# Regular nodes with provenance tracking is turned off, use the old script.
#
elsif (!$doprovenance) {
    $command = "$ocreateimage";
    if ($usefup) {
	my $id;
	if ($usepath) {
851
	    $id = $ofilename;
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	} else {
	    $id = $image->pid() . "/" . $image->imagename();
	}
	$command .= " -S $BOSSIP -F $id";
    }

    $startslice = $image->loadpart();
    $loadlength = $image->loadlength();
    if ($startslice || $loadlength == 1) {
	$command .= " -s $startslice";
    }
    $command .= " $device";

    if ($usefup || $usessh) {
	$command .= " -";
    } else {
868
	$command .= " $ofilename";
869 870 871
    }
}
#
872
# Otherwise, use the new script with different argument syntax.
873
#
874
else {
875 876 877 878 879 880 881 882 883 884 885
    $command = ($isxenhost ? "$createxenimage" : "$createimage");

    #
    # XEN Hosts cannot do provenance/delta without client side update.
    # We need to provide these arguments for backwards compat though.
    #
    if ($isxenhost) {
	$command .= " $node_id";
	if ($usefup || $usessh) {
	    $command .= " -";
	} else {
886
	    $command .= " $ofilename";
887 888
	}
    }
889 890 891 892

    my $id;
    if ($usefup) {
	$command .= " METHOD=frisbee SERVER=$BOSSIP";
893 894 895 896 897 898 899 900

	# if the node has a subboss, use that for downloads
	my $subboss;
	$node->GetSubboss("frisbee", \$subboss);
	if (defined($subboss)) {
	    $command .= " DOWNSERVER=$subboss";
	}

901
	if ($usepath) {
902
	    $id = $ofilename;
903
	} else {
904
	    $id = $image->pid() . "/" . $image->imagename() . ":$version";
905 906
	}
    } else {
907
	$id = $ofilename;
908 909 910 911 912 913
    }
    $command .= " IMAGENAME=$id";
    if ($srcsigfile) {
	if (!$usefup) {
	    $command .= " OLDSIGFILE=$srcsigfile";
	} else {
914 915
	    my $sid = $srcimage->pid() . "/" . $srcimage->imagename() .
		":" . $srcimage->version();
916 917 918 919 920 921 922 923 924 925
	    $command .= " OLDSIGFILE=$sid,sig";
	}
    }
    if ($dstsigfile) {
	if (!$usefup || $usepath) {
	    $command .= " NEWSIGFILE=$dstsigfile";
	} else {
	    $command .= " NEWSIGFILE=$id,sig";
	}
    }
926 927 928 929 930
    if ($deltapct > 0) {
	$zipperopts .= ","
	    if ($zipperopts);
	$zipperopts .= "P=$deltapct";
    }
931

932 933 934 935
    $startslice = $image->loadpart();
    $loadlength = $image->loadlength();

    if ($startslice || $loadlength == 1) {
936
	$command .= " PART=$startslice";
937
    }
938 939 940 941
    if (!$isxenhost) {
 	# The XEN host will figure out what device on its own.
	$command .= " DISK=$device";
    }
942

943 944 945 946
    if ($zipperopts) {
	$command .= " IZOPTS=$zipperopts";
    }

947 948 949 950 951
    #
    # XXX always use ssh for now to get better log info; i.e., all
    # the log info winds up in one logfile.
    #
    $usessh = 1;
952 953 954 955 956
}

#
# Go to the background since this is going to take a while.
# 
957
if (! $foreground) {
958 959
    $logfile = Logfile->Create((defined($experiment) ?
				$experiment->gid_idx() : $image->gid_idx()));
960 961 962 963
    fatal("Could not create a logfile")
	if (!defined($logfile));
    # Mark it open since we are going to start using it right away.
    $logfile->Open();
964

965 966
    # Logfile becomes the current spew.
    $image->SetLogFile($logfile);
967

968
    if (my $childpid = TBBackGround($logfile->filename())) {
969 970
	#
	# Parent exits normally, except if in waitmode. 
971
	#
972
	if (!$waitmode) {
973
	    print("Your image from $target is being created\n".
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
		  "You will be notified via email when the image has been\n".
		  "completed, and you can load the image on another node.\n");
	    exit(0);
	}
	print("Waiting for image creation to complete\n");
	print("You may type ^C at anytime; you will be notified via email;\n".
	      "later; you will not actually interrupt image creation.\n");
	
	# Give child a chance to run.
	select(undef, undef, undef, 0.25);
	
	#
	# Reset signal handlers. User can now kill this process, without
	# stopping the child.
	#
	$SIG{TERM} = 'DEFAULT';
	$SIG{INT}  = 'DEFAULT';
	$SIG{QUIT} = 'DEFAULT';

993
	#
994 995 996 997 998 999
	# Wait until child exits or until user gets bored and types ^C.
	#
	waitpid($childpid, 0);
	
	print("Done. Exited with status: $?\n");
	exit($? >> 8);
1000
    }
1001 1002
}

1003
#
1004 1005 1006
# New process group since we get called from the web interface,
# and so the child does not get zapped if the user types ^C
# in waitmode. 
1007
#
1008
if (! $foreground) {
1009 1010 1011
    POSIX::setsid();
}

1012 1013 1014 1015 1016
#
# From here on out, we should take care to clean up the DB, and
# reboot the source node.
#
$needcleanup = 1;
1017

1018
# Clear the bootlog; see below.
1019 1020
$node->ClearBootLog()
    if (defined($node));
1021

1022 1023 1024 1025 1026 1027 1028 1029 1030
# check_progress state
my $runticks	 = 0;
my $maxticks	 = int($maxwait / $checkwait);
my $reportticks  = int($reportwait / $checkwait);
my $idleticks    = 0;
my $maxidleticks = int($idlewait / $checkwait);
my $lastsize     = 0;
my $result;

1031
#
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
# XXX initial idle period. This is the period before any write is performed
# to the file. When creating or checking signatures, it can take a long time
# before anything is written to the new image file. So we give them some
# extra time to get the ball rolling.
#
my $maxiidleticks = $maxidleticks;
if ($delta || $signature) {
    $maxiidleticks *= 2;
}

#
# EC2 nodes.
# Run on ops.
1045
#
1046 1047 1048 1049
if ($isec2node) {
    my $safe_target = User::escapeshellarg($target);
    
    my $cmd = "$TB/bin/sshtb -host $CONTROL $EC2SNAP -u $user_uid ".
1050
	"$safe_target $pid $user_uid $imageid $ofilename";
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    print STDERR "About to: '$cmd'\n" if (1 || $debug);

    my $SAVEUID	= $UID;
    $EUID = $UID = 0;

    system($cmd);
    fatal("'$cmd' failed")
	if ($?);

    $EUID = $UID = $SAVEUID;
    goto ec2done;
}
1063 1064 1065 1066 1067 1068

#
# Virtnodes.
# Run on vnode host.
#
if ($isvirtnode) {
1069
    #
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    # XEN creates a problem; the physical host cannot actually
    # execute a command inside the guest, but we need to run
    # reboot_prepare and reboot it. FreeBSD creates an additional
    # problem in that shutdown has to run to invoke prepare; reboot
    # does not run it, and a shutdown from outside the VM has the
    # sae effect; prepare does not run. What a pain. 
    #
    my $SAVEUID	= $UID;
    $EUID = $UID = 0;

    my $cmd = "$TB/bin/sshtb -n -o ConnectTimeout=10 ".
	"-host $node_id $reboot_prep";
    print STDERR "About to: '$cmd'\n" if ($debug);
    system($cmd);
    fatal("'$cmd' failed")
	if ($?);

1087 1088 1089 1090
    # Mark webtask
    $webtask->status("imaging")
	if (defined($webtask));

1091 1092
    #
    # Now execute command and wait.
1093 1094
    #
    if ($NONFS) {
1095
	$result = run_with_ssh($command, $ofilename);
1096 1097 1098
    } else {
	$result = run_with_ssh($command, undef);
    }
1099
    $EUID = $UID = $SAVEUID;
1100 1101 1102
    goto done;
}

1103
#
1104
# Normal nodes.
Russ Fish's avatar
Russ Fish committed
1105
# Reboot into admin mode and run the command.
1106 1107
# Note that without a shared FS, we just boot the node into the admin MFS
# and run the command via SSH, capturing the output.
1108 1109 1110 1111
#
my $me           = $0;
my %args         = ();
$args{'name'}    = $me;
1112
$args{'prepare'} = 1;
1113

1114
if ($usessh) {
1115 1116 1117
    #
    # Put the node in admin mode...
    #
1118 1119 1120 1121 1122 1123 1124
    if (!$nomfs) {
	$args{'on'} = 1;
	$args{'clearall'} = 0;
	if (TBAdminMfsSelect(\%args, undef, $node_id)) {
	    $result = "setupfailed";
	    goto done;
	}
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
	#
	# ...boot it...
	#
	$args{'reboot'} = 1;
	$args{'retry'} = 0;
	$args{'wait'} = 1;
	my @failed = ();
	if (TBAdminMfsBoot(\%args, \@failed, $node_id)) {
	    $result = "setupfailed";
	    goto done;
	}
1137 1138
    }

1139 1140 1141 1142
    # Mark webtask
    $webtask->status("imaging")
	if (defined($webtask));

1143 1144
    #
    # ...execute command and wait!
1145 1146
    # Note: we do not pass the filename, that is part of the key/value
    # string we built up.
1147
    #
1148 1149
    my $SAVEUID	= $UID;
    $EUID = $UID = 0;
1150
    $result = run_with_ssh($command, undef);
1151
    $EUID = $UID = $SAVEUID;
1152
    if ($result eq "setupfailed") {
1153 1154 1155 1156 1157 1158 1159 1160
	goto done;
    }
} else {
    $args{'command'} = $command;
    $args{'timeout'} = $maxwait + $checkwait;
    $args{'pfunc'}     = \&check_progress;
    $args{'pinterval'} = $checkwait;

1161 1162 1163 1164
    # Mark webtask
    $webtask->status("imaging")
	if (defined($webtask));

1165 1166 1167 1168 1169 1170 1171
    my $retry = 1;
    while ($retry) {
	$retry = 0;
	if (TBAdminMfsRunCmd(\%args, undef, $node_id)) {
	    $result = "setupfailed"
		if (!defined($result));
	}
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
#
# XXX woeful backward compat hack.
# The old client-side script will not recognize the -S and -F options
# we pass in and will exit(-1).  We detect that here and retry with ssh/nfs.
#
# Note that we only do this in the old, non-provenance world since you
# must have an up-to-date MFS to handle provenance.
#
if (!$doprovenance && $usefup && $result eq "255") {
    print STDERR "MFS does not support frisbee upload, falling back on ",
                 $NONFS ? "ssh" : "nfs", "...\n";

    $command = "$ocreateimage ";

    $startslice = $image->loadpart();
    $loadlength = $image->loadlength();
    if ($startslice || $loadlength == 1) {
	$command .= " -s $startslice";
    }
    $command .= " $device";
    if ($usessh) {
	$command .= " -";
    } else {
1198
	$command .= " $ofilename";
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    }

    # reset state for check_progress
    $usefup = 0;
    $runticks = 0;
    $idleticks = 0;
    $lastsize = 0;
    $result = undef;

    if ($NONFS) {
1209
	$result = run_with_ssh($command, $ofilename);
1210 1211 1212 1213 1214
    } else {
	$result = run_with_ssh($command, undef);
    }
}

1215 1216
done:

1217 1218 1219 1220 1221 1222 1223
# 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)) {
    $bootlog = undef;
}

1224 1225
if (! cleanup()) {
    fatal("Problem encountered while cleaning up!\n");
1226 1227 1228
}

#
1229 1230
# If we timed out, if the result code was bad, or if the image size
# grew too large.
1231
#
1232 1233
if ($result eq "setupfailed") {
    fatal("FAILED: Node setup failed ... \n");
1234
}
1235 1236
if ($result eq "timeout") {
    fatal("FAILED: Timed out generating image ... \n");
1237
}
1238
if ($result eq "toobig") {
1239 1240
    fatal("FAILED: Maximum image size ($maximagesize bytes) exceeded ... \n");
}
1241
if ($result != 0) {
Mike Hibler's avatar
Mike Hibler committed
1242
    fatal("FAILED: Returned error code $result generating image ... \n");
1243
}
1244

1245
ec2done:
1246 1247 1248
if (defined($webtask)) {
    $webtask->status("finishing");
}
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
#
# XXX ugh! If we were doing the autodelta thing, we have to check our logfile
# to see if imagezip reported creating a full image instead of a delta.
# Here we are relying on the fact that we are using SSH, that we are in the
# background and thus keeping a log (so the message will wind up in our log),
# and we depend on the format of the message itself.
#
# Ugly? Yes, but worst case one of our assumptions fails and we record an
# image as a delta when it isn't, which is just inefficient when it comes to
# loading the image.
#
if ($delta && $deltapct > 0 && defined($logfile)) {
    if (open(FD, "<" . $logfile->filename())) {
	# XXX should occur early in the log
	my $maxlines = 100;
	while ($maxlines--) {
	    my $line = <FD>;
	    if ($line =~ /^Auto image selection creating (\S+) image/) {
		if ($1 eq "full") {
		    print "Chose to create full image rather than delta.\n";
		    $delta = 0;
		}
		last;
	    }
	}
	close(FD);
    }
}

1279
#
1280
# Update fields in the DB related to the image.
1281
#
1282 1283 1284 1285 1286
# Note that we do not do this for "standard" images since they get uploaded
# into /proj/emulab-ops rather than /usr/testbed. We could automatically move
# the image into place here, but that makes us nervous. We prefer an admin do
# that by hand after testing the new image!
#
1287 1288 1289
my $cname = "$imagepid/$imagename";
$cname .= ":$version"
    if ($doprovenance);
1290 1291 1292
my $tbopsmsg = "";
if ($isglobal && $usepath) {
    $tbopsmsg =
1293 1294
	"Did not update DB state for global image $cname\n".
	"since image was written to '$filename' instead of $TB/images.\n".
1295 1296 1297 1298 1299
	($doprovenance ?
	 "Please run imagerelease when ready for release:\n".
	 "    imagerelease -q $cname\n" :
	 "Move image into place and run:\n".
	 "    $imagevalidate -uq $cname\n");
1300
}
1301
elsif (system("$imagevalidate -uq $cname") != 0) {
1302
    $tbopsmsg =
1303 1304
	"DB state update for image $cname failed, try again with:\n".
	"    $imagevalidate -u $cname\n";
1305 1306 1307
}
if ($tbopsmsg) {
    SENDMAIL($TBOPS,
1308
	     "Image DB state update failure for $cname",
1309 1310 1311 1312
	     $tbopsmsg,
	     $TBOPS,
	     undef,
	     ());
1313 1314
}

1315 1316
print "$cname: ";
print "delta "
1317
    if ($delta);
1318
print "image creation succeeded, written to $filename.\n";
1319
#      "Final size: " . (stat($filename))[7] . " bytes.\n";
1320

1321
# Append bootlog (which has prepare output)
1322
if (defined($bootlog)) {
1323 1324
    print "\n\n";
    print "------------------ Prepare Output ----------------\n";
1325
    print "$bootlog\n";
1326 1327
}

1328
SENDMAIL("$user_name <$user_email>",
1329
	 "Image Creation on $target Completed: $imagepid/$imagename",
1330
	 "Image creation on $target has completed. As you requested, the\n".
1331
	 "image has been written to $filename.\n".
1332
	 "You may now os_load this image on other nodes in your experiment.\n",
1333 1334
	 "$user_name <$user_email>",
	 "Bcc: $TBLOGS",
1335
	 defined($logfile) ? ($logfile->filename()) : ()) if (!$noemail);
1336

1337
if (defined($logfile)) {
1338
    # Close up the log file so the webpage stops.
1339
    $logfile->Close();
1340
    $image->ClearLogFile();
1341
}
1342 1343 1344 1345
if (defined($webtask)) {
    $webtask->status("ready");
    $webtask->Exited(0);
}
1346 1347 1348 1349 1350 1351 1352
#
# If we created a delta image, set it in the DB
#
if ($delta) {
    $image->SetDelta(1);
}

1353 1354 1355 1356 1357
#
# Normal images are immediately marked as "released" (and ready),
# but global system images are just marked ready, and must be explicitly
# released.
#
1358
$image->MarkReady();
1359
if (! ($isglobal && $pid eq TBOPSPID()) || !$doprovenance) {
1360 1361 1362 1363 1364
    if ($image->Release()) {
	$image->Unlock();
	exit(1);
    }
}
1365
$image->Unlock();
1366
exit(0);
1367 1368 1369

sub cleanup ()
{
1370 1371
    $needcleanup = 0;

1372 1373 1374 1375
    if (defined($hacksigfile)) {
	unlink($hacksigfile);
    }

1376
    if ($isvirtnode || $isec2node) {
1377 1378 1379 1380 1381 1382
	#
	# Nothing to do; the clientside script rebooted the container.
	#
	return 1;
    }

1383
    #
1384
    # Turn admin mode back off and reboot back to the old OS
1385
    #
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    if (!$nomfs) {
	my %args          = ();
	$args{'name'}     = $me;
	$args{'on'}       = 0;
	$args{'clearall'} = 0;
	if (TBAdminMfsSelect(\%args, undef, $node_id)) {
	    print("*** $me:\n".
		  "    Could not turn admin mode off for $node_id!\n");
	    return 0;
	}
1396

1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
	%args           = ();
	$args{'name'}   = $me;
	$args{'on'}     = 0;
	$args{'reboot'} = 1;
	$args{'wait'}   = 0;
	if (TBAdminMfsBoot(\%args, undef, $node_id)) {
	    print("*** $me:\n".
		  "    Failed to reboot $node_id on cleanup!\n");
	    return 0;
	}
1407 1408
    }

1409
    return 1;
1410 1411 1412 1413 1414
}

sub fatal($)
{
    my($mesg) = $_[0];
1415 1416

    print "$mesg\n";
1417 1418 1419 1420

    if ($needcleanup && !cleanup()) {
        print "Encountered problems cleaning up!\n";
    }
1421 1422
    
    #
1423
    # Send a message to the testbed list. 
1424
    #
1425
    SENDMAIL("$user_name <$user_email>",
1426
	     "Image Creation Failure on $target: $imagepid/$imagename:$version",
1427 1428 1429
	     $mesg,
	     "$user_name <$user_email>",
	     "Cc: $TBOPS",
1430
	     defined($logfile) ? ($logfile->filename()) : ());
1431
    
1432 1433 1434
    if (defined($logfile)) {
	# Close up the log file so the webpage stops.
	$logfile->Close();
1435
	$image->ClearLogFile();
1436
    }
1437 1438 1439 1440 1441 1442
    
    if (defined($webtask)) {
	$webtask->status("failed");
	$webtask->imagesize(0);
	$webtask->Exited(1);
    }
1443 1444
    $image->Unlock()
	if ($needunlock);
1445 1446 1447 1448
    # Restore old image file. 
    if ($didbackup) {
	system("/bin/mv -f ${filename}.bak $filename");
    }
1449 1450 1451
    exit(-1);
}

1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
#
# Check progress of image creation by periodically checking the image size.
#
# Called every $checkwait seconds.
# Reports progress every $reportwait seconds.
# Gives up after $idlewait seconds without a size change.
#
sub check_progress($$)
{
    my (undef, $statusp) = @_;

1463
    if ($runticks == 0) {
1464 1465 1466
	print "$node_id: started image capture for '$filename', ".
	    "waiting up to " . int($maxwait/60) . " minutes total or ".
	    int($idlewait/60) . " minutes idle.\n";
1467 1468
    }

1469 1470 1471 1472 1473 1474 1475 1476 1477
    #
    # XXX frisbee uploader uploads into a temporary file and then moves
    # it into place. So track that tmp file here.
    #
    my $fname = $filename;
    if ($usefup) {
	$fname .= ".tmp";
    }

1478 1479 1480
    #
    # Command has finished for better or worse, record status and finish.
    #
1481
    if (defined($statusp) && $statusp->{$node_id} ne "none") {
1482
	$result = $statusp->{$node_id};
1483
	print "$node_id: image capture has completed: status='$result'\n";
1484 1485 1486 1487 1488 1489 1490 1491 1492
	return 0;
    }

    #
    # Has run too long
    #
    $runticks++;
    if ($runticks >= $maxticks) {
	$result = "timeout";
1493
	print "$node_id: image capture has completed: timeout\n";
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	return 0;
    }

    #
    # See if imagezip on the node is making progress.  If not, we need to
    # check the idle timer and timeout if we have taken too long.
    #
    # Also, check to see if the (somewhat arbitrary) maximum filesize has 
    # been exceeded.
    #
1504
    my $cursize = (stat($fname))[7];
1505 1506 1507 1508 1509 1510 1511 1512 1513
    if ($usefup && !defined($cursize)) {
	#
	# XXX avoid an ugly race.
	# When done, frisuploadd moves foo.tmp -> foo
	# If we didn't find foo.tmp, try foo now.
	#
	$fname =~ s/\.tmp$//;
	$cursize = (stat($fname))[7];
    }
1514 1515
    if ($cursize > $maximagesize) {
	$result = "toobig";
Mike Hibler's avatar