libosload.pm.in 47.5 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2000-2018 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/>.
# 
# }}}
23 24 25 26 27 28 29 30 31 32 33
#
# Osload library. Basically the backend to the osload script, but also used
# where we need finer control of loading of nodes.
#
package libosload;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
34
@EXPORT = qw ( osload osload_wait osload_setupswapinfo );
35 36

# Must come after package declaration!
37
use libtestbed; # for TBGenSecretKey();
38 39
use libdb;
use libreboot;
40
use libtblog_simple;
41 42
use Node;
use NodeType;
43
use OSImage;
44
use User;
45
use EmulabConstants;
46
use English;
47 48
use event;
use Data::Dumper;
49 50 51 52 53 54 55
use File::stat;
use IO::Handle;

# Configure variables
my $TB		= "@prefix@";
my $TESTMODE    = @TESTMODE@;
my $TBOPS       = "@TBOPSEMAIL@";
56
my $ELABINELAB  = @ELABINELAB@;
57
my $PROJROOT    = "@PROJROOT_DIR@";
58
my $WITHPROVENANCE= @IMAGEPROVENANCE@;
59
my $WITHDELTAS	= @IMAGEDELTAS@;
60
my $IMAGEINFO	= "$TB/sbin/imageinfo";
61 62 63 64 65

# Max number of retries (per node) before its deemed fatal. This allows
# for the occasional pxeboot failure.
my $MAXRETRIES  = 1;

66 67 68 69
# Hack constant factor (slop) to add to the max reload wait time for any node
# This is set based on testbed-wide factors (like multicast being dog slow!)
my $TBLOADWAIT  = (10 * 60);

70
my $osselect	    = "$TB/bin/os_select";
71
my $TBUISP	    = "$TB/bin/tbuisp";
72
my $TBADB           = "$TB/bin/tbadb";
73 74 75 76

# Locals
my $debug           = 0;
my %children        = ();	# Child pids in when asyncmode=1
77
my $remote_mult     = 5;        # Wait lots longer for remote nodes!
78 79 80 81 82

sub osload ($$) {
    my ($args, $result) = @_;

    # These come in from the caller.
83
    my @imageids;
84
    my @reqimages;
85
    my $waitmode    = 1;
86
    my $usecurrent  = 0;
87 88 89
    my @nodes       = ();
    my $noreboot    = 0;
    my $asyncmode   = 0;
90
    my $zerofree    = 0;
91
    my $prepare     = 0;
92
    my $swapinfo    = 0;
93
    my %nodeflags   = ();
94

95 96 97 98
    # Reset
    $debug          = 0;
    %children       = ();

99 100 101 102 103
    # Locals
    my %retries	    = ();
    my $failures    = 0;
    my $usedefault  = 1;
    my $mereuser    = 0;
104
    my $this_user;
105 106

    if (!defined($args->{'nodelist'})) {
107
	tberror "Must supply a node list!"; # INTERNAL
108 109 110 111 112 113 114 115 116 117 118 119 120
	return -1;
    }
    @nodes = sort(@{ $args->{'nodelist'} });
    
    if (defined($args->{'waitmode'})) {
	$waitmode = $args->{'waitmode'};
    }
    if (defined($args->{'noreboot'})) {
	$noreboot = $args->{'noreboot'};
    }
    if (defined($args->{'debug'})) {
	$debug = $args->{'debug'};
    }
121 122 123 124
    if (defined($args->{'usecurrent'}) && $args->{'usecurrent'}) {
	$usecurrent = 1;
	$usedefault = 0;
    }
125
    if (defined($args->{'image'})) {
126
	@reqimages = split(/,/, $args->{'image'});
127
	$usedefault = $usecurrent = 0;
128
    }
129
    elsif (defined($args->{'images'})) {
130
	@reqimages = @{$args->{'images'}};
131
	$usedefault = $usecurrent = 0;
132 133
    }
    elsif (defined($args->{'imageids'})) {
134
	@imageids = @{$args->{'imageids'}};
135
	$usedefault = $usecurrent = 0;
136
    }
137 138
    elsif (defined($args->{'imageid'})) {
	@imageids = split(/,/, $args->{'imageid'});
139
	$usedefault = $usecurrent = 0;
140
    }
141 142 143
    if (defined($args->{'asyncmode'})) {
	$asyncmode = $args->{'asyncmode'};
    }
144 145 146
    if (defined($args->{'zerofree'})) {
	$zerofree = $args->{'zerofree'};
    }
147 148 149
    if (defined($args->{'prepare'})) {
	$prepare = $args->{'prepare'};
    }
150 151 152
    if (defined($args->{'swapinfo'})) {
	$swapinfo = $args->{'swapinfo'};
    }
153 154 155
    if (defined($args->{'nodeflags'})) {
	%nodeflags = %{$args->{'nodeflags'}};
    }
156

157 158 159 160 161
    #
    # Figure out who called us. Root and admin types can do whatever they
    # want. Normal users can only change nodes in experiments in their
    # own projects.
    #
162 163 164 165 166 167 168 169 170 171 172 173 174
    if ($UID) {
	$this_user = User->ThisUser();
	return -1
	    if (!defined($this_user));

	if (!$this_user->IsAdmin()) {
	    $mereuser = 1;

	    if (! TBNodeAccessCheck($UID, TB_NODEACCESS_LOADIMAGE, @nodes)) {
		tberror("Not enough permission to load images on one or ".
			"more nodes!");
		return -1;
	    }
175 176 177
	}
    }

178 179
    if (@imageids) {
	foreach my $imageid (@imageids) {
180
	    my $image = OSImage->Lookup($imageid);
181 182 183 184
	    if (!defined($image)) {
		tberror("No such imageid $imageid");
		return -1;
	    }
185
	    push(@reqimages, $image);
186
	}
187 188
    }

189 190
    foreach my $i (0 .. $#reqimages) {
	my $image = $reqimages[$i];
191

192 193 194 195 196 197 198 199
	#
	# Check permission to use the imageid.
	# 
	if ($mereuser &&
	    ! $image->AccessCheck($this_user, TB_IMAGEID_READINFO)) {
	    tberror "You do not have permission to load $image";
	    return -1;
	}
200

201 202 203 204 205 206 207 208 209
	#
	# If there's a maxiumum number of concurrent loads listed for the image,
	# check to see if we'll go over the limit, by checking to see how many
	# other nodes are currently booting thie image's default_osid. This is
	# NOT intended to be strong enforcement of license restrictions, just a
	# way to catch mistakes.
	#
	if (!TBImageLoadMaxOkay($image->imageid(), scalar(@nodes), @nodes)) {
	    tberror 
210
	    "Would exceed maxiumum concurrent instances ".
211
		"limitation for $image";
212 213
	    return -1;
	}
214 215
    }

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    #
    # This is somewhat hackish. To promote parallelism during os_setup, we
    # want to fork off the osload from the parent so it can do other things.
    # The problem is how to return status via the results vector. Well,
    # lets do it with some simple IPC. Since the results vector is simply
    # a hash of node name to an integer value, its easy to pass that back.
    #
    # We return the pid to the caller, which it can wait on either directly
    # or by calling back into this library if it wants to actually get the
    # results from the child!
    # 
    if ($asyncmode) {
	#
	# Create a pipe to read back results from the child we will create.
	#
231 232
	my $PARENT_READER = new IO::Handle; # Need a new handle for each child
	if (! pipe($PARENT_READER, CHILD_WRITER)) {
233
	    tberror "creating pipe: $!";
234 235 236 237 238 239
	    return -1;
	}
	CHILD_WRITER->autoflush(1);

	if (my $childpid = fork()) {
	    close(CHILD_WRITER);
240
	    $children{$childpid} = [ $PARENT_READER, $result ];
241 242 243 244 245
	    return $childpid;
	}
	#
	# Child keeps going. 
	#
246
	close($PARENT_READER);
247 248 249
	TBdbfork();
    }

250 251 252 253
    # This will store information about each node, so that if we have to try
    # again later, we'll have it all.
    my %reload_info;

254 255
    # Loop for each node.
    foreach my $node (@nodes) {
256
	my @images;
257 258
	# All nodes start out as being successful; altered later as needed.
	$result->{$node} = 0;
259 260 261 262 263 264

	my $nodeobject = Node->Lookup($node);
	if (!defined($nodeobject)) {
	    tberror "$node: Could not map to object!";
	    goto failednode;
	}
265 266 267 268 269 270

	# Check to see if the node is tainted.  If so, then the disk
	# needs to be cleaned up (zeroed).  If there was an explicit request
	# to zero all node disks, then capture that here too.
	my $zeronode = 0;
	if ($nodeobject->IsTainted()) {
271
	    $zeronode = 2;
272 273 274 275
	}
	elsif ($zerofree) {
	    $zeronode = $zerofree;
	}
276 277
	
	# Get default imageid for this node.
278 279 280
	# NOTE that virtnodes don't have default imageids -- they are only 
	# loaded (and thus arrive here) if the user specifically set a loadable
	# subOS for the node.
281 282 283 284 285 286
	if ($usedefault) {
	    if ($nodeobject->isvirtnode()) {
		tberror("Virtnodes do not have default images!");
		goto failednode;
	    }
	    else {
287 288 289 290 291 292 293 294
		my $default_imageid = $nodeobject->default_imageid();
		if (! defined($default_imageid)) {
		    tberror "$node: No default imageid defined!";
		    goto failednode;
		}
		my @default_imageids = split(/,/, $default_imageid);
		my @default_images;
		foreach my $default_imageid (@default_imageids) {
295
		    my $default_image = OSImage->Lookup($default_imageid);
296 297 298 299 300 301
		    if (!defined($default_image)) {
			tberror("Could not find $default_imageid in the DB!");
			goto failednode;
		    }
		    push @default_images, $default_image;
		}
302 303 304
		$prepare = 1;
		@images   = @default_images;
	    }
305 306 307
	}
	elsif ($usecurrent) {
	    my $def_boot_osid  = $nodeobject->def_boot_osid();
308
	    my $def_boot_vers  = $nodeobject->def_boot_osid_vers();
309
	    my $osimage = OSImage->Lookup($def_boot_osid, $def_boot_vers);
310

311
	    if (! defined($osimage)) {
312 313 314
		tberror("Could not find OS $def_boot_osid in the DB!");
		goto failednode;
	    }
315
	    my $best_image = $osimage->MapToImage($nodeobject->type());
316
	    if (!defined($best_image)) {
317
		tberror("Could not map $osimage to an image for $node!");
318
		goto failednode;
319
	    }
320
	    @images   = ($best_image);
321
	}
322 323 324 325 326 327 328 329 330 331 332 333 334
	else {
	    foreach my $image (@reqimages) {
		if ($image->isImageAlias()) {
		    my $tmp = $image->MapToImage($nodeobject->type());
		    if (!defined($tmp)) {
			tberror("Could not map $image to an image for $node!");
			goto failednode;
		    }
		    $image = $tmp;
		}
		push(@images, $image);
	    }
	}
335
	
336
	my @imageidxs = (0 .. $#images);
337
	my $defosid;
338
	my $defvers;
339 340
	my $maxwait = 0;
	my @access_keys;
341

342
	#
343 344 345 346 347
	# Most of the DB work related to images is determining what
	# disk partitions should be clobbered and which should survive
	# the loading of all the images. To make this more efficient,
	# we loop through the images updating our parititions hash
	# and then just do one DB partitions table access at the end.
348
	#
349 350
	my %partitions = ();
	my $curmbrvers = 0;
351

352
	#
353 354
	# XXX assumes a DOS MBR, but this is ingrained in the DB schema
	# as well (i.e., the images.part[1234]_osid fields).
355
	#
356 357 358 359 360 361 362
	my $MINPART = 1;
	my $MAXPART = 4;

	#
	# If doing a prepare, all current partition info is going to
	# be invalidated, so we start with an empty hash. Otherwise
	# we read the current DB values to initialize it.
363
	#
364 365
	if (!$prepare) {
	    my $dbresult =
366
		DBQueryWarn("select p.*,v.mbr_version ".
367
			    " from `partitions` as p,image_versions as v ".
368 369 370
			    " where p.imageid=v.imageid and ".
			    "       p.imageid_version=v.version and ".
			    "       v.deleted is null ".
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
			    "  and p.node_id='$node'");
	    if (!$dbresult) {
		tberror("$node: Could not read partition table!");
		goto failednode;
	    }
	    while (my $href = $dbresult->fetchrow_hashref()) {
		if (!$curmbrvers) {
		    $curmbrvers = $href->{'mbr_version'};
		} elsif ($href->{'mbr_version'} &&
			 $href->{'mbr_version'} != $curmbrvers) {
		    tbwarn("$node: inconsistent MBR version info, ".
			   "invalidating all partitions!");
		    %partitions = ();
		    last;
		}
		$partitions{$href->{'partition'}} = $href;
	    }
	}
389

390 391 392
	#
	# For each image, update the necessary node state.
	#
393 394
	foreach my $i (@imageidxs) {
	    my $image = $images[$i];
395
	
396 397 398 399
	    print STDERR "osload: Using $image for $node\n"
		if $debug;

	    #
400 401 402 403
	    # We can have both a full image and/or a delta image. We
	    # always prefer the full image if we have it.
	    #
	    if (! ($image->HaveFullImage() || $image->HaveDeltaImage())) {
404 405 406 407 408 409 410 411
		#
		# This should be an error, but until we run imagevalidate
		# over all images, we want to do it here.
		#
		if (GetImageSize($image, $node)) {
		    tberror "$node: no full or delta image file!";
		    goto failednode;
		}
412
	    }
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
	    my $isfull     = $image->HaveFullImage();
	    my $loadpart   = $image->loadpart();
	    my $loadlen    = $image->loadlength();
	    my $imagepid   = $image->pid();
	    my $imagesize  = ($isfull ? $image->size() : $image->deltasize());
	    #
	    # Compute a maxwait time based on the image size plus a constant
	    # factor for the reboot cycle.  This is used later in
	    # WaitTillReloadDone().  Arguably, this should be part of the
	    # image DB state, so we store it in the imageinfo array too.
	    #
	    # size may be > 2^31, shift is unsigned
	    #
	    my $chunks = $imagesize >> 20;
	    $maxwait += int((($chunks / 100.0) * 65)) + $TBLOADWAIT;
    
	    $access_keys[$i] = $image->access_key();
430

431
	    #
432
	    # Set the default boot OSID.
433
	    # Note: when loading multiple images, use the last image.
434
	    #
435 436
	    if ($i == $imageidxs[-1]) {
		print "osload ($node): Loading $image\n" if $i > 0;
437
		print "osload ($node): Changing default OS to $image\n";
438
		if (!$TESTMODE) {
439 440
		    if ($nodeobject->OSSelect($image, "def_boot_osid", 0)) {
			tberror "$node: os_select $image failed!";
441
			goto failednode;
442 443
		    }
		}
444 445
	    } else {
		print "osload ($node): Loading $image\n";
446
	    }
447
	    
448
	    #
449 450
	    # Assign partition table entries for each partition in the image
	    # that has an OSID associated with it.
451
	    #
452 453 454 455 456
	    # This is complicated by the fact that an image that covers only
	    # part of the slices should only change the partition table entries
	    # for the subset of slices that are written to disk...
	    #
	    # ...UNLESS, the new image requires a different version of the MBR
457 458
	    # in which case we must invalidate all existing partitions since
	    # the partition boundaries may have changed...
459 460 461 462 463
	    #
	    # ...OR, the prepare flag has been specified, which will tell the
	    # client to invalidate all partition metadata on the disk so we
	    # might as well mark the partition as "empty".  In particular,
	    # this case is used by the reload_daemon when a node is between
464 465 466 467
	    # experiments.  In this case we need to invalidate all existing
	    # partition(s) to ensure that a user later on doesn't accidentally
	    # get some left over partition OS when they should have been
	    # loading a new instance. This case was handled earlier.
468 469 470 471
	    #
	    my $startpart = $loadpart == 0 ? $MINPART : $loadpart;
	    my $endpart   = $startpart + $loadlen;
	    
472 473 474 475
	    #
	    # If image MBR is incompatible with what is on the disk right
	    # now, invalidate all the existing partitions ("...UNLESS" above).
	    #
476 477 478
	    if (defined($image->mbr_version())) {
		if ($image->mbr_version() && $curmbrvers &&
		    $image->mbr_version() != $curmbrvers) {
479
		    %partitions = ();
480
		}
481
		$curmbrvers = $image->mbr_version();
482 483 484 485 486 487
	    }

	    #
	    # Now we loop through the image partitions and set/clear
	    # the existing partition info as appropriate.
	    #
488 489 490
	    # NOTE: We no longer do multi-os images ... but this loop
	    # is harmless. 
	    #
491 492
	    for (my $i = $startpart; $i < $endpart; $i++) {
		my $partname = "part${i}_osid";
493
		my $partvers = "part${i}_vers";
494

495 496
		my $osid = $image->field($partname);
		my $vers = $image->field($partvers);
497
		if (defined($osid)) {
498 499 500
		    my $osimage = OSImage->Lookup($osid, $vers);
		    if (!defined($osimage)) {
			tberror "No OSImage found for $osid!\n";
501 502
			goto failednode;
		    }
503 504 505 506
		    my %part = (
			'node_id' => $node,
			'partition' => $i,
			'osid' => $osid,
507 508 509
			'osid_vers' => $osimage->version(),
			'imageid' => $osimage->imageid(),
			'imageid_version' => $osimage->version(),
510 511 512 513
			'imagepid' => $imagepid,
			'mbr_version' => $curmbrvers
		    );
		    $partitions{$i} = \%part;
514 515
		}
		else {
516
		    delete $partitions{$i};
517
		}
518
	    }
519 520 521 522 523 524 525 526 527 528 529 530
	}

	#
	# Now that we have processed all images, update the actual DB
	# partitions table entries for this node.
	#
	for (my $i = $MINPART; $i <= $MAXPART; $i++) {
	    my $dbresult;

	    if (exists($partitions{$i})) {
		my $href = $partitions{$i};
		my $osid = $href->{'osid'};
531
		my $osvers = $href->{'osid_vers'};
532
		my $imid = $href->{'imageid'};
533
		my $imvers = $href->{'imageid_version'};
534 535
		my $impid = $href->{'imagepid'};
		$dbresult =
536 537
		    DBQueryWarn("replace into `partitions` ".
				"(node_id,`partition`,osid,imageid,imagepid,".
538
				" osid_vers,imageid_version) ".
539
				"values ".
540 541
				"('$node','$i','$osid','$imid','$impid',".
				" '$osvers','$imvers')");
542 543
	    } else {
		$dbresult =
544 545
		    DBQueryWarn("delete from `partitions` ".
				"where node_id='$node' and `partition`='$i'");
546 547 548 549 550
	    }
	    if (!$dbresult) {
		tberror "$node: Could not update partitions table";
		goto failednode;
	    }
551 552
	}

553 554 555 556 557
	#
	# Change the node's default command line as necessary.
	# XXX we only do this for delay nodes.
	#
	if ($defosid && $nodeobject->erole() eq "delaynode") {
558 559
	    my $osimage = OSImage->Lookup($defosid, $defvers);
	    if ($osimage) {
560 561 562 563
		my ($ocmdline,$ncmdline);
		$ocmdline = $nodeobject->def_boot_cmd_line();
		$ocmdline = ""
		    if (!defined($ocmdline));
564
		$osimage->OSBootCmd("delay", \$ncmdline);
565 566 567 568 569 570 571 572 573 574 575 576 577 578
		$ncmdline = ""
		    if (!defined($ncmdline));
		if ($ocmdline ne $ncmdline) {
		    print "osload ($node): Changing cmdline: ".
			  "'$ocmdline' -> '$ncmdline'\n";
		    if (!DBQueryWarn("update nodes set ".
				     "def_boot_cmd_line='$ncmdline' ".
				     "where node_id='$node'")) {
			tbwarn "$node: Could not update command line";
		    }
		}
	    }
	}

579 580 581 582 583
	#
	# Setup swapinfo now after partitions have initialized but before
	# we setup the one-shot frisbee load.
	#
	if ($swapinfo) {
584
	    print "osload ($node): Updating image signature.\n";
585 586 587
	    osload_setupswapinfo(undef, undef, $node);
	}

588 589 590 591 592 593
	#
	# For each image to be loaded, we check and see if it is a delta
	# image. If so, we must follow its parent link backward til we
	# find the latest full version of the image, then load those in
	# reverse order.
	#
594
	my @allimages = ();
595
	if ($WITHPROVENANCE && $WITHDELTAS) {
596
	    my $founddelta = 0;
597
	    foreach my $image (@images) {
598
		if (!$image->HaveFullImage()) {
599 600 601 602 603 604 605 606 607 608
		    my $pimage = $image;
		    my @ilist = ();
		    do {
			# if it is a delta image, there had better be a parent!
			$pimage = $pimage->Parent();
			if (!$pimage) {
			    tberror "$node: delta image $image has no parent!";
			    goto failednode;
			}
			push(@ilist, $pimage);
609
		    } while (!$pimage->HaveFullImage());
610 611 612 613 614 615 616 617 618 619 620 621 622
		    push @allimages, reverse(@ilist);
		    $founddelta = 1;
		}
		push(@allimages, $image);
	    }
	    #
	    # If we added any images to the list, we need to recompute
	    # the access keys.
	    #
	    if ($founddelta) {
		@access_keys = ();
		foreach my $image (@allimages) {
		    push(@access_keys, $image->access_key());
623 624
		}
	    }
625 626
	} else {
	    @allimages = @images;
627
	}
628
	my @allimageidxs = (0 .. $#allimages);
629

630 631 632 633 634
	#
	# Determine which mode to use for reloading this node (note: this may
	# become an entry in node_capabilities or something like that in the
	# future - that would be cleaner)
	#
635 636
	my $type  = $nodeobject->type();
	my $class = $nodeobject->class();
637
	my $isremote = $nodeobject->isremotenode();
638
	my $isvirtnode = $nodeobject->isvirtnode();
639 640 641
	my $reload_mode;
	my $reload_func;
	my $reboot_required;
642
	my $wait_required = 1;
643 644 645 646
	if ($class eq "mote") {
	    $reload_mode = "UISP";
	    $reload_func = \&SetupReloadUISP;
	    $reboot_required = 0; # We don't reboot motes to reload them
647
	    $zeronode = 0; # and we don't zero "the disk"
648 649 650 651 652 653
	}
	elsif ($class eq "ue") {
	    $reload_mode = "UE";
	    $reload_func = \&SetupReloadUE;
	    $reboot_required = 0; # We don't reboot UEs to reload them
	    $zeronode = 0; # and we don't zero "the disk"
654 655 656 657
	} else {
	    $reload_mode = "Frisbee";
	    $reload_func = \&SetupReloadFrisbee;
	    $reboot_required = !$noreboot; # Reboot unless $noreboot flag set
658

659 660 661 662 663
	    if (defined($nodeflags{$node}) 
		&& defined($nodeflags{$node}{'noreboot'})) {
		$reboot_required = !$nodeflags{$node}{'noreboot'};
	    }

664 665 666 667 668
	    if (defined($nodeflags{$node}) 
		&& defined($nodeflags{$node}{'nowait'})) {
		$wait_required = !$nodeflags{$node}{'nowait'};
	    }

669
	    foreach my $i (@allimageidxs) {
670 671
		# This is passed along so that remote node can request the file.
		# Make sure the image object has an access key defined.
672 673
		if (($nodeobject->isremotenode() || $nodeobject->OnRemoteNode())
		    && !defined($access_keys[$i])) {
674 675
		    $access_keys[$i] = TBGenSecretKey();
		    
676
		    if ($allimages[$i]->Update({'access_key' => $access_keys[$i]}) != 0) {
677 678 679
			tberror "$node: Could not initialize image access key";
			goto failednode;
		    }
680 681
		}
	    }
682 683 684 685 686 687 688
	}

	#
	# Remember this stuff so that if we have to retry this node again
	# later, we'll know how to handle it
	#
	$reload_info{$node} = {
689
	    'nodeobj'  => $nodeobject,
690 691 692
	    'node'     => $node,
	    'mode'     => $reload_mode,
	    'func'     => $reload_func,
693
	    'images'   => \@allimages,
694
	    'osid'     => $defosid,
695
	    'osid_vers'=> $defvers,
696
	    'reboot'   => $reboot_required,
697
	    'wait'     => $wait_required,
698
	    'zerofree' => $zeronode,
699
	    'prepare'  => $prepare,
700
	    'maxwait'  => $maxwait,
701 702
	    'isremote' => $isremote,
	    'isvirtnode' => $isvirtnode
703 704 705 706
	};

	print "Setting up reload for $node (mode: $reload_mode)\n";

707
	if (!$TESTMODE) {
708
	    if (&$reload_func($reload_info{$node}) < 0) {
709
		tberror("$node: Could not set up reload. Skipping.");
710 711 712 713 714 715 716 717 718
		goto failednode;
	    }
	}
	next;
	
      failednode:
	$result->{$node} = -1;
	$failures++;
    }
719
    
720 721 722 723 724 725 726 727 728 729
    #
    # Remove any failed nodes from the list we are going to operate on.
    #
    my @temp = ();
    foreach my $node (@nodes) {
	push(@temp, $node)
	    if (! $result->{$node});
    }
    @nodes = @temp;

730 731
    TBDebugTimeStamp("osload: database setup done");

732 733 734 735 736 737 738
    # Exit if not doing an actual reload.
    if ($TESTMODE) {
	print "osload: Stopping in Testmode!\n";
	goto done;
    }

    if (! @nodes) {
739
	tbnotice "Stopping because of previous failures!";
740 741 742 743 744
	goto done;
    }

    # Fire off a mass reboot and quit if not in waitmode.
    if (! $waitmode) {
745
	my ($reboot_nodes, $noreboot_nodes)
746
	    = GetNodesRequiringReboot(\%reload_info, keys(%reload_info));
747
	if (@$reboot_nodes) {
748 749 750 751 752 753 754
	    print "osload: Rebooting nodes.\n";

	    my %reboot_args     = ();
	    my %reboot_failures = ();

	    $reboot_args{'debug'}    = $debug;
	    $reboot_args{'waitmode'} = 0;
755
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];
756 757

	    if (nodereboot(\%reboot_args, \%reboot_failures)) {
758
		foreach my $node (@$reboot_nodes) {
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$failures++;
		    }
		}
	    }
	}
	goto done;
    }

    #
    # The retry vector is initialized to the number of retries we allow per
    # node, afterwhich its a fatal error.
    #
    foreach my $node (@nodes) {
	$retries{$node} = $MAXRETRIES;
    }
776 777 778 779 780 781 782 783

    #
    # Callback for our event handler. We use a "closure" so it can
    # reference the list of nodes that we are currently waiting on.
    #
    my $eventnodes = undef;
    my $handler = sub {
	my ($handle, $notification, undef) = @_;
784
    
785 786 787 788 789 790
	my $node_id = event_notification_get_objname($handle,$notification);
	my $event   = event_notification_get_eventtype($handle,$notification);

	return
	    if (!defined($eventnodes));

791
	$eventnodes->{'GOTONE'} = 1;
792
	if (exists($eventnodes->{$node_id})) {
793
	    my $et = time();
794 795
	    print "osload: eventhandler: $node_id => $event @ $et\n"
		if ($debug);
796
	    $eventnodes->{$node_id} = $et;
797 798 799 800 801 802 803 804 805 806 807 808
	}
    };
    my $evhandle = SetupEventHandler($handler);
    if (!defined($evhandle)) {
	tbnotice "Stopping because event registration failed!";
	foreach my $node (@nodes) {
	    $result->{$node} = -1;
	    $failures++;
	}
	goto done;
    }

809
    while (@nodes) {
810 811 812
	my ($reboot_nodes, $noreboot_nodes)
	    = GetNodesRequiringReboot(\%reload_info, @nodes);
	if (@$reboot_nodes) {
813
	    # Reboot them all.
814 815 816 817 818 819 820 821
	    print "osload: ".
		"Issuing reboot for @$reboot_nodes and then waiting ...\n";

	    # Prime the event handler above.
	    $eventnodes = {} if (!defined($eventnodes));
	    foreach my $node (@$reboot_nodes) {
		$eventnodes->{$node} = 0;
	    }
822
	    TBDebugTimeStamp("osload: event handler enabled");
823 824 825 826 827 828
	    
	    my %reboot_args     = ();
	    my %reboot_failures = ();

	    $reboot_args{'debug'}    = $debug;
	    $reboot_args{'waitmode'} = 0;
829
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];
830 831 832 833 834 835 836 837

	    if (nodereboot(\%reboot_args, \%reboot_failures)) {
		#
		# If we get any failures in the reboot, we want to
		# alter the list of nodes accordingly for the next phase.
		# 
		my @temp = ();
		
838
		foreach my $node (@$reboot_nodes) {
839 840 841 842 843 844 845 846
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$failures++;
		    }
		    else {
			push(@temp, $node);
		    }
		}
847
		@nodes = (@temp,@$noreboot_nodes);
848 849 850 851 852
	    }
	}

	# Now wait for them.
	my $startwait   = time;
853 854 855
	my @failednodes = WaitTillReloadDone($startwait,
					     $waitmode,
					     \%reload_info, 
856 857
					     $eventnodes,
					     $evhandle,
858
					     @nodes);
859
				
860 861 862 863 864 865
	@nodes=();
    
	while (@failednodes) {
	    my $node = shift(@failednodes);

	    if ($retries{$node}) {
866
		tbnotice "$node: Trying again ...";
867

868 869
		my $reload_info = $reload_info{$node};

870
		# Possible race with reboot?
871
		if (&{$reload_info->{'func'}}($reload_info) < 0) {
872
		    tberror("$node: Could not set up reload. Skipping.");
873 874 875 876 877 878 879 880 881 882
		    $result->{$node} = -1;
		    $failures++;
		    next;
		}
		push(@nodes, $node);

		# Retry until count hits zero.
		$retries{$node} -= 1;
	    }
	    else {
883 884
		tberror ({sublevel => -1}, 
			 "$node failed to boot too many times. Skipping!");
885 886 887 888 889 890 891
		$result->{$node} = -1;
		$failures++;
	    }
	}
    }
  done:
    print "osload: Done! There were $failures failures.\n";
892 893 894 895 896 897 898 899
    
    #
    # Since we use this in long running daemons, be sure to release
    # the event system connection, or else we stack up lots of handles
    # and socket connections to the event server. 
    #
    event_unregister($evhandle)
	if (defined($evhandle));
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

    if ($asyncmode) {
	#
	# We are a child. Send back the results to the parent side
	# and *exit* with status instead of returning it.
	# 
	foreach my $node (keys(%{ $result })) {
	    my $status = $result->{$node};
	    
	    print CHILD_WRITER "$node,$status\n";
	}
	close(CHILD_WRITER);
	exit($failures);
    }
    return $failures;
}

917
sub DumpImageInfo($)
918
{
919 920
    my ($image) = @_;
    
921
    print STDERR
922 923 924 925 926 927
	"$image: loadpart=", $image->loadpart(),
	", loadlen=", $image->loadlength(),
	", imagepath=", $image->path(),
	", imagesize=", $image->size(),
	", defosid=", $image->default_osid(),
	", maxloadwait=", $image->_maxloadwait(), "\n"
928 929 930 931 932
	    if ($debug);

    return 1;
}

933
# Wait for a reload to finish by watching its state
934
sub WaitTillReloadDone($$$$$@)
935
{
936 937
    my ($startwait, $waitmode,
	$reload_info, $eventnodes, $evhandle, @nodes) = @_;
938 939 940 941
    my %done	= ();
    my $count   = @nodes;
    my @failed  = ();

942 943 944 945 946 947 948 949 950 951
    foreach my $node ( @nodes ) {
	if ($reload_info->{$node}{'wait'} == 1) {
	    $done{$node} = 0;
	}
	else {
	    $done{$node} = 1;
	    --$count;
	    print "osload ($node): not waiting for reload of $node.\n";
	}
    }
952

Mike Hibler's avatar
Mike Hibler committed
953 954
    print STDERR "Waiting for @nodes to finish reloading\n".`date`
	if ($count && $debug);
955 956 957

    # Start a counter going, relative to the time we rebooted the first
    # node.
958
    TBDebugTimeStamp("osload: starting reload-done wait");
959 960 961
    my $waittime  = 0;
    my $minutes   = 0;

962 963 964 965 966 967 968 969 970
    #
    # Should-be-parameters:
    #
    # REBOOTWAIT: time in minutes to make a transition after reboot
    # MAXEVENTS: max events to grab in any event_poll loop
    #
    my $REBOOTWAIT = 5;
    my $MAXEVENTS = 500;

971
    my $ecount = 1;
Mike Hibler's avatar
Mike Hibler committed
972
    while ($count > 0) {
973 974
	# Wait first to make sure reboot is done, and so that we don't
	# wait one more time after everyone is up.
975 976 977
	if ($ecount > 0) {
	    sleep(5)
	}
978
	my $ecount = $MAXEVENTS;
979 980 981 982
	do {
	    $eventnodes->{'GOTONE'} = 0;
	    event_poll($evhandle);
	} while ($eventnodes->{'GOTONE'} && --$ecount > 0);
983 984 985 986
	if ($ecount < $MAXEVENTS) {
	    print STDERR "got ", $MAXEVENTS-$ecount, " events\n"
		if ($debug);
	}
987 988
	foreach my $node (@nodes) {
	    if (! $done{$node}) {
989
		my $nodeobject = Node->Lookup($node);
990 991 992 993 994 995 996 997 998 999 1000
		my $maxwait;

		#
		# If we have to zero fill free space, then the
		# wait time has to be proportional to the disk
		# size.  In other words, a really, really, really
		# long time.  Lets assume 20MB/sec to blast zeros,
		# so 50 seconds/GB.  What the heck, lets call it
		# 1GB/minute.  Did I mention how this would take
		# a really long time?
		#
1001 1002
		# Else, if we have a remote node, we wait another multiplier.
		#
1003
		if ($reload_info->{$node}{'zerofree'}) {
1004
		    my $disksize = $nodeobject->disksize();
1005

1006 1007 1008
		    $disksize = 20
			if (!$disksize);
		    $maxwait = ($disksize * 60);
1009 1010
		} elsif ($reload_info->{$node}{'isremote'}) {
		    $maxwait = $reload_info->{$node}{'maxwait'} * $remote_mult;
1011
		} else {
1012
		    $maxwait = $reload_info->{$node}{'maxwait'};
1013
		}
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

		#
		# If it's a virtnode, we need to add a bunch of time based
		# on how long the parent might take.  This is a fool's errand,
		# given how synchronous our scripts are, so give it 8 mins 
		# for now.
		#
		if ($reload_info->{$node}{'isvirtnode'}) {
		    $maxwait += 8 * 60;
		}
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
		
		my $query_result =
		    DBQueryWarn("select * from current_reloads ".
				"where node_id='$node'");

		#
		# There is no point in quitting if this query fails. Just
		# try again in a little bit.
		# 
		if (!$query_result) {
1034
		    tbwarn "$node: Query failed; waiting a bit.";
1035 1036 1037 1038 1039 1040 1041 1042 1043
		    next;
		}

		#
		# We simply wait for stated to clear the current_reloads entry.
		#
		if (!$query_result->numrows) {
		    print STDERR "osload ($node): left reloading mode at ".`date`
			if ($debug);
1044

1045 1046 1047 1048
		    $count--;
		    $done{$node} = 1;
		    next;
		}
1049 1050 1051 1052 1053 1054 1055 1056

		#
		# All of the eventstate stuff belongs in stated. Sheesh.
		#
		my $eventstate;
		if ($nodeobject->GetEventState(\$eventstate)) {
		    print STDERR "osload ($node): Could not get event state\n";
		}
1057 1058 1059 1060 1061
	
		# Soon we will have stated's timeouts take care of
		# rebooting once or twice if we get stuck during
		# reloading.
		$waittime = time - $startwait;
1062
		
1063 1064 1065
		# If the node doesn't made a transition within $REBOOTWAIT
		# minutes of booting, we declare it stuck.
		my $isstuck = ($minutes > $REBOOTWAIT &&
1066 1067
			       exists($eventnodes->{$node}) &&
			       $eventnodes->{$node} == 0);
1068

1069
		if ($waittime > $maxwait ||
1070 1071
		    $eventstate eq TBDB_NODESTATE_TBFAILED() ||
		    $eventstate eq TBDB_NODESTATE_PXEFAILED() ||
1072
		    $eventstate eq TBDB_NODESTATE_RELOADFAILED() ||
1073
		    $isstuck) {
1074 1075 1076 1077 1078 1079

		    #
		    # If we are in reloading, then we obviously missed
		    # a state transition in our handler. Probably just
		    # need to increase $MAXEVENTS above.
		    #
1080 1081
		    if ($isstuck &&
			$eventstate eq TBDB_NODESTATE_RELOADING()) {
1082 1083 1084 1085 1086 1087
			tbnotice("missed state transition to RELOADING".
				 " for $node; faking it.");
			$eventnodes->{$node} = time();
			goto okay;
		    }

1088
		    my $t = (int ($waittime / 60));
1089 1090
		    tbnotice "$node appears wedged; ".
			"it has been $t minutes since it was rebooted.";
1091

1092
		    if ($eventstate eq TBDB_NODESTATE_TBFAILED() ||
1093
			$eventstate eq TBDB_NODESTATE_RELOADFAILED() ||
1094
			$eventstate eq TBDB_NODESTATE_PXEFAILED()) {
1095 1096 1097 1098
			tbnotice("  $node is stuck in $eventstate.");
		    }
		    elsif ($eventstate eq TBDB_NODESTATE_RELOADING()) {
			tbnotice("  $node did not finish reloading.");
1099
		    }
1100
		    elsif ($isstuck) {
1101 1102 1103
			tbnotice("  $node failed to make a state ".
				 "transition after $REBOOTWAIT minutes; ".
				 "stuck in $eventstate.");
1104
		    }
1105
		    TBNodeConsoleTail($node, *STDERR);
1106 1107

		    $count--;
1108
		    $done{$node} = $waitmode;
1109 1110 1111
		    push(@failed, $node);
		    next;
		}
1112
	      okay:
1113 1114 1115 1116 1117 1118 1119 1120
		if (int($waittime / 60) > $minutes) {
		    $minutes = int($waittime / 60);
		    print STDERR "osload ($node): still waiting; ".
			"it has been $minutes minute(s)\n";
		}
	    }
	}
    }
1121 1122 1123

    if ($waitmode > 1) {
	$startwait = time;
Mike Hibler's avatar
Mike Hibler committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
	foreach my $node (@nodes) {
	    print STDERR
		"osload ($node): waiting for node to finish booting\n";
	    if ($done{$node} < $waitmode) {
		my $actual_state;

		if (!TBNodeStateWait($node,
				     $startwait,
				     (60*6),
				     \$actual_state,
				     (TBDB_NODESTATE_TBFAILED,
1135
				      TBDB_NODESTATE_RELOADFAILED,
Mike Hibler's avatar
Mike Hibler committed
1136 1137 1138 1139 1140
				      TBDB_NODESTATE_PXEFAILED,
				      TBDB_NODESTATE_ISUP))) {
		    $done{$node} = $waitmode;
		} else {
		    push(@failed, $node);
1141 1142 1143 1144 1145
		}
	    }
	}
    }

1146 1147 1148 1149
    return @failed;
}

# Setup a reload. 
1150
sub SetupReloadFrisbee($)
1151
{
1152
    my $reload_info   = $_[0];
1153
    my $nodeobject    = $reload_info->{'nodeobj'};
1154
    my $node          = $reload_info->{'node'};
1155
    my $images        = $reload_info->{'images'};
1156
    my $zerofree      = $reload_info->{'zerofree'};
1157
    my $prepare       = $reload_info->{'prepare'};
1158
    my $isvirtnode    = $reload_info->{'isvirtnode'};
1159
    my $osid          = TBNodeDiskloadOSID($node);
1160

1161 1162 1163 1164
    #
    # Put it in the current_reloads table so that nodes can find out which
    # OS to load. See tmcd. 
    #
1165
    $nodeobject->ClearCurrentReload();
1166

1167
    my $idx = 1;
1168 1169 1170
    foreach my $image (@$images) {
	my $imageid = $image->imageid();
	my $version = $image->version();
1171 1172

	# only prepare on first image
1173
	my $prepare0 = $idx == 1 && $prepare ? 1 : 0;
1174
	# only zero on full images
1175
	my $zerofree0 = $image->HaveFullImage() ? $zerofree : 0;
1176

1177 1178
	my $query_result = 
	    DBQueryWarn("insert into current_reloads ".
1179
			"(node_id, idx, image_id, imageid_version,".
1180
			" mustwipe, prepare) values ".
1181 1182
			"('$node', $idx, '$imageid', '$version',".
			" $zerofree0, $prepare0)");
1183 1184 1185 1186 1187
	return -1
	    if (!$query_result);
	++$idx;
    }

1188 1189 1190 1191 1192
    #
    # We used to invoke os_select here and it checks for MODIFYINFO permission
    # on the node. Since we have already checked for LOADIMAGE permission,
    # which requires the same user privilege, we do not need to check further.
    #
1193 1194 1195
    my $osimage = OSImage->Lookup($osid);
    if (!defined($osimage) ||
	$nodeobject->OSSelect($osimage, "next_boot_osid", 0)) {
1196
	tberror "os_select $osid failed!";
1197 1198
	return -1;
    }
1199 1200 1201

    # Need to kick virtnodes so stated picks up the next_op_mode from os_select
    if ($isvirtnode) {
1202
	$nodeobject->SetEventState(TBDB_NODESTATE_SHUTDOWN);
1203 1204
    }

1205 1206 1207
    return 0;
}

1208 1209 1210 1211 1212
#
# Setup a reload, using USIP (for motes), rather than Frisbee. Note that
# this differs from a Frisbee reload in one key way - it does the reload
# right here in this code, rather than setting up a reload for later.
#
1213
sub SetupReloadUISP($)
1214
{
1215 1216 1217 1218
    my $reload_info   = $_[0];
    my $node          = $reload_info->{'node'};
    my $imageid       = $reload_info->{'imageid'};
    my $osid          = $reload_info->{'osid'};
1219 1220 1221 1222 1223 1224 1225

    #
    # Get the path to the image
    #
    my $query_result = DBQueryFatal("select path from images " .
	"where imageid='$imageid'");
    if ($query_result->num_rows() != 1) {
1226
	tberror "Failed to get path for $imageid!";
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	return -1;
    }
    my ($path) = $query_result->fetchrow();

    #
    # Tell stated that we're about to start reloading
    #
    TBSetNodeNextOpMode($node,TBDB_NODEOPMODE_RELOADMOTE);

    #
    # The mote goes 'down', then starts to reload
    #
    TBSetNodeEventState($node,TBDB_NODESTATE_SHUTDOWN);
    TBSetNodeEventState($node,TBDB_NODESTATE_RELOADING);

    #
    # Okay, just run tbuisp with that path
    #
    my $rv = system("$TBUISP upload $path $node");
    if ($rv) {
1247
	tberror "$node: tbuisp failed";
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
	return -1;
    }

    #
    # Tell stated that we've finished reloading the node
    #
    TBSetNodeEventState($node,TBDB_NODESTATE_RELOADDONE);

    system("$osselect $osid $node");
    if ($?) {
1258
	tberror "os_select $osid failed!";
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
	goto failednode;
    }

    #
    # 'Reboot' the node (from stated's perspective, anyway)
    # has been shutdown, so that the os_select will take effect
    #
    TBSetNodeEventState($node,TBDB_NODESTATE_SHUTDOWN);

    return 0;
}

1271 1272 1273 1274 1275 1276 1277 1278
#
# Setup a UE (mobile handset) reload via ADB rather than Frisbee. This
# calls a script on the UE's "console" server that then pulls across
# the image (if necessary) and loads it on the specified device.
#
sub SetupReloadUE($)
{
    my $reload_info   = $_[0];
1279
    my $nodeobject    = $reload_info->{'nodeobj'};
1280
    my $node          = $reload_info->{'node'};
1281
    my $image         = (@{$reload_info->{'images'}})[0];
1282 1283

    #
1284 1285 1286 1287 1288 1289
    # Clear any pending reload entries.
    #
    $nodeobject->ClearCurrentReload();

    #
    # Get some image details for setting up the reload.
1290
    #
1291 1292
    my $imgpid  = $image->pid();
    my $imgname = $image->imagename();
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
    my $imageid = $image->imageid();
    my $version = $image->version();

    my $query_result = 
	DBQueryWarn("insert into current_reloads ".
		    "(node_id, idx, image_id, imageid_version,".
		    " mustwipe, prepare) values ".
		    "('$node', 1, '$imageid', '$version',".
		    " 0, 0)");
    return -1
	if (!$query_result);
1304 1305 1306 1307

    #
    # Tell stated that we're about to start reloading
    #
1308
    TBSetNodeNextOpMode($node,TBDB_NODEOPMODE_RELOADUE);
1309 1310

    #
1311
    # The device goes 'down', then starts to reload
1312
    #
1313 1314
    TBSetNodeEventState($node,TBDB_NODESTATE_SHUTDOWN);
    TBSetNodeEventState($node,TBDB_NODESTATE_RELOADING);
1315 1316 1317

    #
    # Invoke local script that calls the remote end that
1318
    # actually does the work.  This will go into the background.
1319
    #
1320
    my $rv = system("$TBADB -n $node loadimage $imgpid $imgname nowait");
1321
    if ($rv) {
1322
	tberror "$node: tbadb failed!";
1323 1324 1325 1326 1327 1328
	return -1;
    }

    return 0;
}

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
#
# Grab the size and update the database.
#
sub GetImageSize($$)
{
    my ($image, $node) = @_;
    my $imagesize = 0;
    my $imagepath = $image->FullImageFile();

    #
    # Perform a few validity checks: imageid should have a file name
    # and that file should exist.
    #
    if (!defined($imagepath)) {
	tberror "No filename associated with $image!";
	return -1;
    }

    if (! -R $imagepath) {
	#
	# There are two reasons why a legit image might not be readable.
	# One is that we are in an elabinelab and the image has just not
	# been downloaded yet. The other is that we are attempting to
	# access a shared (via the grantimage mechanism) image which the
	# caller cannot directly access.
	#
	# For either case, making a proxy query request via frisbee will
	# tell us whether the image is accessible and, if so, its size.
	# "imageinfo" makes that call for us.
	#
	my $frisimageid = $image->pid() . "/" . $image->imagename();
	my $sizestr = `$IMAGEINFO -qs -N $node $frisimageid`;
	if ($sizestr =~ /^(\d+)$/) {
	    $imagesize = $1;
	} else {
	    tberror "$image: access not allowed or image does not exist.";
	    return -1;
	}
    } else {
	$imagesize = stat($imagepath)->size;
    }

    #
    # A zero-length image cannot be right and will result in much confusion
    # if allowed to pass: the image load will succeed, but the disk will be
    # unchanged, making it appear that os_load loaded the default image.
    #
    if ($imagesize == 0) {
	tberror "$imagepath is empty!";
	return -1;
    }
    $image->SetFullSize($imagesize);
    return 0;
}

1384 1385 1386 1387
#
# Return two array references (possbily empty) of:
# [all nodes requiring reboot, all nodes not requiring reboot]
#
1388 1389
sub GetNodesRequiringReboot($@) {
    my ($reload_info, @nodes) = @_;
1390
    my (@reboot, @noreboot);
1391
    foreach my $node (@nodes) {
1392 1393 1394 1395 1396 1397 1398 1399 1400
	if ($reload_info->{$node}{'reboot'}) {
	    push @reboot, $node;
	} else {
	    push @noreboot, $node;
	}
    }
    return (\@reboot, \@noreboot);
}

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
#
# This gets called in the parent, to wait for an async osload that was
# launched earlier (asyncmode). The child will print the results back
# on the the pipe that was opened between the parent and child. They
# are stuffed into the original results array.
# 
sub osload_wait($)
{
    my ($childpid) = @_;

    if (!exists($children{$childpid})) {
1412
	tberror "No such child pid $childpid!"; # INTERNAL
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
	return -1;
    }
    my ($PARENT_READER, $result) = @{ $children{$childpid}};

    #
    # Read back the results.
    # 
    while (<$PARENT_READER>) {
	chomp($_);

	if ($_ =~ /^([-\w]+),([-\d])+$/) {
	    $result->{$1} = $2;
	    print STDERR "reload ($1): child returned $2 status.\n";
	}
	else {
1428
	    tberror "Improper response from child: $_"; # INTERNAL
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	}
    }
    
    #
    # And get the actual exit status.
    # 
    waitpid($childpid, 0);
    return $? >> 8;
}

Leigh Stoller's avatar
Leigh Stoller committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
sub osload_kill($)
{
    my ($childpid) = @_;

    print STDERR "osload_kill($childpid): starting\n";
    kill('TERM', $childpid);
    waitpid($childpid, 0);
    return 0;
}

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
#
# Save signature files and boot partition info for all nodes in an experiment
# (or just the listed nodes).  We call this when swapping in an experiment or
# when reloading nodes in an experiment.
#
# Note that this is not strictly an os loading function, we do it on swapins
# of nodes which already have the correct OS as well.  But we stick it here
# because it is about os loading in principle.
#
sub osload_setupswapinfo($$;@)
{
    my ($pid, $eid, @nodelist) = @_;
    my %nodeinfo = ();
    my $allnodes;
    my $clause = "";

1465
    if (!@nodelist) {
1466
	@nodelist = ExpNodes($pid, $eid, 1, 0);
1467 1468 1469 1470 1471 1472 1473 1474 1475
	$clause .= "r.pid='$pid' and r.eid='$eid'";
	$allnodes = 1;
    } else {
	$clause .= "r.node_id in (" . join(",", map("'$_'", @nodelist)) . ")";
	$allnodes = 0;
    }
    map { $nodeinfo{$_} = 0 } @nodelist;

    # XXX only know how to do this for local PCs right now
1476
    $clause .= " and nt.class='pc' and nt.isremotenode=0";
1477 1478 1479 1480 1481 1482 1483 1484

    #
    # Note that we are using the def_boot_osid from the nodes table to identify
    # the image of interest.  This is because the osid field is set by stated
    # after a node has reached the BOOTING state the first time, and may be
    # set to an MFS at other times.
    #
    my $query_result = DBQueryWarn(
1485
	"select r.node_id,r.vname,r.pid,r.eid,r.erole,n.osid,p.`partition`,".
1486 1487
	"       p.imageid,p.imageid_version,p.imagepid,i.imagename,".
	"       iv.loadpart,e.savedisk ".
1488 1489 1490
	"from reserved as r ".
	"left join nodes as n on n.node_id=r.node_id ".
	"left join node_types as nt on nt.type=n.type ".
Mike Hibler's avatar