libosload.pm.in 43.8 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
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/>.
# 
# }}}
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;
41 42
use Node;
use NodeType;
43
use Image;
44
use User;
45
use OSinfo;
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 59 60 61 62

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

63 64 65 66
# 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);

67
my $osselect	    = "$TB/bin/os_select";
68
my $TBUISP	    = "$TB/bin/tbuisp";
69
my $IMAGEINFO	    = "$TB/sbin/imageinfo";
70 71 72 73 74

# Locals
my %imageinfo       = ();	# Per imageid DB info.
my $debug           = 0;
my %children        = ();	# Child pids in when asyncmode=1
75
my $remote_mult     = 5;        # Wait lots longer for remote nodes!
76 77 78 79 80

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

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

    # Locals
    my %retries	    = ();
    my $failures    = 0;
    my $usedefault  = 1;
    my $mereuser    = 0;
    my $rowref;
98
    my @images;
99
    my $this_user;
100 101

    if (!defined($args->{'nodelist'})) {
102
	tberror "Must supply a node list!"; # INTERNAL
103 104 105 106 107 108 109 110 111 112 113 114 115 116
	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'};
    }
    if (defined($args->{'imageid'})) {
117
	@imageids = split(/,/, $args->{'imageid'});
118 119 120 121
	$usedefault = 0;
    }
    if (defined($args->{'imageids'})) {
	@imageids = @{$args->{'imageids'}};
122 123
	$usedefault = 0;
    }
124 125 126 127
    if (defined($args->{'usecurrent'}) && $args->{'usecurrent'}) {
	$usecurrent = 1;
	$usedefault = 0;
    }
128 129 130
    if (defined($args->{'asyncmode'})) {
	$asyncmode = $args->{'asyncmode'};
    }
131 132 133
    if (defined($args->{'zerofree'})) {
	$zerofree = $args->{'zerofree'};
    }
134 135 136
    if (defined($args->{'prepare'})) {
	$prepare = $args->{'prepare'};
    }
137 138 139
    if (defined($args->{'swapinfo'})) {
	$swapinfo = $args->{'swapinfo'};
    }
140 141 142
    if (defined($args->{'nodeflags'})) {
	%nodeflags = %{$args->{'nodeflags'}};
    }
143 144 145 146 147 148 149 150 151

    #
    # Start a new logging sub-process
    #
    my $old_env = \%ENV;
    local %ENV;
    copy_hash %ENV, $old_env;
    tblog_sub_process("osload", @nodes);

152 153 154 155 156
    #
    # 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.
    #
157 158 159 160 161 162 163 164 165 166 167 168 169
    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;
	    }
170 171 172
	}
    }

173 174 175 176
    foreach my $i (0 .. $#imageids) {
	my $imageid = $imageids[$i];
	$images[$i] = Image->Lookup($imageid);
	my $image = $images[$i];
177 178 179 180 181
	if (!defined($image)) {
	    tberror("Could not map $imageid to its object!");
	    return -1;
	}

182 183 184 185 186 187 188 189 190
	#
	# 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;
	}
191

192 193 194 195 196 197 198 199 200
	#
	# 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 
201
	    "Would exceed maxiumum concurrent instances ".
202
		"limitation for $image";
203 204
	    return -1;
	}
205 206
    }

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    #
    # 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.
	#
222 223
	my $PARENT_READER = new IO::Handle; # Need a new handle for each child
	if (! pipe($PARENT_READER, CHILD_WRITER)) {
224
	    tberror "creating pipe: $!";
225 226 227 228 229 230
	    return -1;
	}
	CHILD_WRITER->autoflush(1);

	if (my $childpid = fork()) {
	    close(CHILD_WRITER);
231
	    $children{$childpid} = [ $PARENT_READER, $result ];
232 233 234 235 236
	    return $childpid;
	}
	#
	# Child keeps going. 
	#
237
	close($PARENT_READER);
238 239 240
	TBdbfork();
    }

241 242 243 244
    # This will store information about each node, so that if we have to try
    # again later, we'll have it all.
    my %reload_info;

245 246 247 248
    # Loop for each node.
    foreach my $node (@nodes) {
	# All nodes start out as being successful; altered later as needed.
	$result->{$node} = 0;
249 250 251 252 253 254

	my $nodeobject = Node->Lookup($node);
	if (!defined($nodeobject)) {
	    tberror "$node: Could not map to object!";
	    goto failednode;
	}
255 256 257 258 259 260

	# 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()) {
261
	    $zeronode = 2;
262 263 264 265
	}
	elsif ($zerofree) {
	    $zeronode = $zerofree;
	}
266 267
	
	# Get default imageid for this node.
268 269 270
	# 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.
271 272 273 274 275 276
	if ($usedefault) {
	    if ($nodeobject->isvirtnode()) {
		tberror("Virtnodes do not have default images!");
		goto failednode;
	    }
	    else {
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
		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) {
		    my $default_image = Image->Lookup($default_imageid);
		    if (!defined($default_image)) {
			tberror("Could not find $default_imageid in the DB!");
			goto failednode;
		    }
		    push @default_images, $default_image;
		}
292 293 294 295
		$prepare = 1;
		@imageids = @default_imageids;
		@images   = @default_images;
	    }
296 297 298 299
	}
	elsif ($usecurrent) {
	    my $def_boot_osid  = $nodeobject->def_boot_osid();
	    my $osinfo = OSinfo->Lookup($def_boot_osid);
300

301 302 303 304 305 306 307 308
	    if (! defined($osinfo)) {
		tberror("Could not find OS $def_boot_osid in the DB!");
		goto failednode;
	    }
	    my $best_image = $osinfo->MapToImage($nodeobject->type());
	    if (!defined($best_image)) {
		tberror("Could not map $osinfo to an image for $node!");
		goto failednode;
309
	    }
310 311
	    @imageids = $best_image->imageid();
	    @images   = ($best_image);
312
	}
313 314 315 316 317
	
	my @imageidxs = (0 .. $#imageids);
	my $defosid;
	my $maxwait = 0;
	my @access_keys;
318

319
	#
320 321 322 323 324
	# 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.
325
	#
326 327
	my %partitions = ();
	my $curmbrvers = 0;
328

329
	#
330 331
	# XXX assumes a DOS MBR, but this is ingrained in the DB schema
	# as well (i.e., the images.part[1234]_osid fields).
332
	#
333 334 335 336 337 338 339
	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.
340
	#
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
	if (!$prepare) {
	    my $dbresult =
		DBQueryWarn("select p.*,i.mbr_version ".
			    " from partitions as p,images as i ".
			    " where p.imageid=i.imageid ".
			    "  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;
	    }
	}
364

365 366 367
	#
	# For each image, update the necessary node state.
	#
368 369 370
	foreach my $i (@imageidxs) {
	    my $imageid = $imageids[$i];
	    my $image = $images[$i];
371
	
372 373 374 375
	    print STDERR "osload: Using $image for $node\n"
		if $debug;

	    #
376 377 378 379
	    # We try to avoid repeated queries to DB for info that
	    # does not change by caching the image info on the first
	    # use.  GetImageInfo() will perform various one-time
	    # checks as well.
380
	    # 
381
	    if (!exists($imageinfo{$imageid}) && !GetImageInfo($image,$node)) {
382 383 384 385 386 387
		goto failednode;
	    }
	    $rowref = $imageinfo{$imageid};
	    if ($rowref eq 'BADIMAGE') {
		goto failednode;
	    }
388
	    
389 390 391 392 393 394 395
	    my $loadpart   = $rowref->{'loadpart'};
	    my $loadlen    = $rowref->{'loadlength'};
	    my $imagepath  = $rowref->{'path'};
	    my $imagepid   = $rowref->{'pid'};
	    $maxwait += $rowref->{'maxloadwait'};
	    $access_keys[$i] = $rowref->{'access_key'};

396
	    #
397 398 399
	    # Set the default boot OSID.
	    # Note: when loading multiple images, use the osinfo from the
	    # last image.
400
	    #
401 402 403 404 405 406 407 408 409 410 411 412
	    if ($i == $imageidxs[-1]) {
		$defosid = $rowref->{'default_osid'};

		my $osinfo = OSinfo->Lookup($defosid);
		if (!defined($osinfo)) {
		    tberror("Could map map OSID $defosid to its object!");
		    goto failednode;
		}
		
		print "osload ($node): Loading $image\n" if $i > 0;
		print "osload ($node): Changing default OS to $osinfo\n";
		if (!$TESTMODE) {
413
		    if ($nodeobject->OSSelect($osinfo, "def_boot_osid", 0)) {
414 415
			tberror "$node: os_select $defosid failed!";
			goto failednode;
416 417
		    }
		}
418 419
	    } else {
		print "osload ($node): Loading $image\n";
420
	    }
421
	    
422
	    #
423 424
	    # Assign partition table entries for each partition in the image
	    # that has an OSID associated with it.
425
	    #
426 427 428 429 430
	    # 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
431 432
	    # in which case we must invalidate all existing partitions since
	    # the partition boundaries may have changed...
433 434 435 436 437
	    #
	    # ...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
438 439 440 441
	    # 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.
442 443 444 445
	    #
	    my $startpart = $loadpart == 0 ? $MINPART : $loadpart;
	    my $endpart   = $startpart + $loadlen;
	    
446 447 448 449 450 451 452 453
	    #
	    # If image MBR is incompatible with what is on the disk right
	    # now, invalidate all the existing partitions ("...UNLESS" above).
	    #
	    if (defined($rowref->{'mbr_version'})) {
		if ($rowref->{'mbr_version'} && $curmbrvers &&
		    $rowref->{'mbr_version'} != $curmbrvers) {
		    %partitions = ();
454
		}
455 456 457 458 459 460 461 462 463 464 465 466
		$curmbrvers = $rowref->{'mbr_version'};
	    }

	    #
	    # Now we loop through the image partitions and set/clear
	    # the existing partition info as appropriate.
	    #
	    for (my $i = $startpart; $i < $endpart; $i++) {
		my $partname = "part${i}_osid";

		my $osid = $rowref->{$partname};
		if (defined($osid)) {
467 468 469 470 471 472 473 474 475 476
		    # Have the node inherit taint states from each OS
		    # to be loaded on it (or that is already loaded on
		    # it).  This action is additive, i.e. the node
		    # will end up with the union of taint states
		    # across all partition OSes.  We also retain any
		    # taint states the node had previously; it's
		    # important not to clear these existing states
		    # until OS loading and disk zeroing have been
		    # performed.
		    my $osinfo = OSinfo->Lookup($osid);
477 478 479 480
		    if (defined($osinfo) && $osinfo->IsTainted()) {
			$nodeobject->InheritTaintStates($osinfo) == 0 or
			    warn "Node $node could not inherit taint ".
			    "states from osid $osid\n";
481 482
		    }

483 484 485 486 487 488 489 490 491
		    my %part = (
			'node_id' => $node,
			'partition' => $i,
			'osid' => $osid,
			'imageid' => $imageid,
			'imagepid' => $imagepid,
			'mbr_version' => $curmbrvers
		    );
		    $partitions{$i} = \%part;
492 493
		}
		else {
494
		    delete $partitions{$i};
495
		}
496
	    }
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
	}

	#
	# 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'};
		my $imid = $href->{'imageid'};
		my $impid = $href->{'imagepid'};
		$dbresult =
		    DBQueryWarn("replace into partitions ".
				"(node_id,partition,osid,imageid,imagepid) ".
				"values ".
				"('$node','$i','$osid','$imid','$impid')");
	    } else {
		$dbresult =
		    DBQueryWarn("delete from partitions ".
				"where node_id='$node' and partition='$i'");
	    }
	    if (!$dbresult) {
		tberror "$node: Could not update partitions table";
		goto failednode;
	    }
525 526
	}

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	#
	# Change the node's default command line as necessary.
	# XXX we only do this for delay nodes.
	#
	if ($defosid && $nodeobject->erole() eq "delaynode") {
	    my $osinfo = OSinfo->Lookup($defosid);
	    if ($osinfo) {
		my ($ocmdline,$ncmdline);
		$ocmdline = $nodeobject->def_boot_cmd_line();
		$ocmdline = ""
		    if (!defined($ocmdline));
		$osinfo->OSBootCmd("delay", \$ncmdline);
		$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";
		    }
		}
	    }
	}

553 554 555 556 557
	#
	# Setup swapinfo now after partitions have initialized but before
	# we setup the one-shot frisbee load.
	#
	if ($swapinfo) {
558
	    print "osload ($node): Updating image signature.\n";
559 560 561
	    osload_setupswapinfo(undef, undef, $node);
	}

562 563 564 565 566
	#
	# 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)
	#
567 568
	my $type  = $nodeobject->type();
	my $class = $nodeobject->class();
569
	my $isremote = $nodeobject->isremotenode();
570
	my $isvirtnode = $nodeobject->isvirtnode();
571 572 573
	my $reload_mode;
	my $reload_func;
	my $reboot_required;
574
	my $wait_required = 1;
575 576 577 578
	if ($class eq "mote") {
	    $reload_mode = "UISP";
	    $reload_func = \&SetupReloadUISP;
	    $reboot_required = 0; # We don't reboot motes to reload them
579
	    $zeronode = 0; # and we don't zero "the disk"
580 581 582 583
	} else {
	    $reload_mode = "Frisbee";
	    $reload_func = \&SetupReloadFrisbee;
	    $reboot_required = !$noreboot; # Reboot unless $noreboot flag set
584

585 586 587 588 589
	    if (defined($nodeflags{$node}) 
		&& defined($nodeflags{$node}{'noreboot'})) {
		$reboot_required = !$nodeflags{$node}{'noreboot'};
	    }

590 591 592 593 594
	    if (defined($nodeflags{$node}) 
		&& defined($nodeflags{$node}{'nowait'})) {
		$wait_required = !$nodeflags{$node}{'nowait'};
	    }

595 596 597
	    foreach my $i (@imageidxs) {
		# This is passed along so that remote node can request the file.
		# Make sure the image object has an access key defined.
598 599
		if (($nodeobject->isremotenode() || $nodeobject->OnRemoteNode())
		    && !defined($access_keys[$i])) {
600 601 602 603 604 605 606
		    $access_keys[$i] = TBGenSecretKey();
		    
		    $rowref->{'access_key'} = $access_keys[$i];
		    if ($images[$i]->Update({'access_key' => $access_keys[$i]}) != 0) {
			tberror "$node: Could not initialize image access key";
			goto failednode;
		    }
607 608
		}
	    }
609 610 611 612 613 614 615
	}

	#
	# Remember this stuff so that if we have to retry this node again
	# later, we'll know how to handle it
	#
	$reload_info{$node} = {
616
	    'nodeobj'  => $nodeobject,
617 618 619 620 621 622
	    'node'     => $node,
	    'mode'     => $reload_mode,
	    'func'     => $reload_func,
	    'imageids' => \@imageids,
	    'osid'     => $defosid,
	    'reboot'   => $reboot_required,
623
	    'wait'     => $wait_required,
624
	    'zerofree' => $zeronode,
625
	    'prepare'  => $prepare,
626
	    'maxwait'  => $maxwait,
627 628
	    'isremote' => $isremote,
	    'isvirtnode' => $isvirtnode
629 630 631 632
	};

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

633
	if (!$TESTMODE) {
634
	    if (&$reload_func($reload_info{$node}) < 0) {
635
		tberror("$node: Could not set up reload. Skipping.");
636 637 638 639 640 641 642 643 644
		goto failednode;
	    }
	}
	next;
	
      failednode:
	$result->{$node} = -1;
	$failures++;
    }
645
    
646 647 648 649 650 651 652 653 654 655
    #
    # 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;

656 657
    TBDebugTimeStamp("osload: database setup done");

658 659 660 661 662 663 664
    # Exit if not doing an actual reload.
    if ($TESTMODE) {
	print "osload: Stopping in Testmode!\n";
	goto done;
    }

    if (! @nodes) {
665
	tbnotice "Stopping because of previous failures!";
666 667 668 669 670
	goto done;
    }

    # Fire off a mass reboot and quit if not in waitmode.
    if (! $waitmode) {
671
	my ($reboot_nodes, $noreboot_nodes)
672
	    = GetNodesRequiringReboot(\%reload_info, keys(%reload_info));
673
	if (@$reboot_nodes) {
674 675 676 677 678 679 680
	    print "osload: Rebooting nodes.\n";

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

	    $reboot_args{'debug'}    = $debug;
	    $reboot_args{'waitmode'} = 0;
681
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];
682 683

	    if (nodereboot(\%reboot_args, \%reboot_failures)) {
684
		foreach my $node (@$reboot_nodes) {
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
		    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;
    }
702 703 704 705 706 707 708 709

    #
    # 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) = @_;
710
    
711 712 713 714 715 716
	my $node_id = event_notification_get_objname($handle,$notification);
	my $event   = event_notification_get_eventtype($handle,$notification);

	return
	    if (!defined($eventnodes));

717
	$eventnodes->{'GOTONE'} = 1;
718
	if (exists($eventnodes->{$node_id})) {
719
	    my $et = time();
720 721
	    print "osload: eventhandler: $node_id => $event @ $et\n"
		if ($debug);
722
	    $eventnodes->{$node_id} = $et;
723 724 725 726 727 728 729 730 731 732 733 734
	}
    };
    my $evhandle = SetupEventHandler($handler);
    if (!defined($evhandle)) {
	tbnotice "Stopping because event registration failed!";
	foreach my $node (@nodes) {
	    $result->{$node} = -1;
	    $failures++;
	}
	goto done;
    }

735
    while (@nodes) {
736 737 738
	my ($reboot_nodes, $noreboot_nodes)
	    = GetNodesRequiringReboot(\%reload_info, @nodes);
	if (@$reboot_nodes) {
739
	    # Reboot them all.
740 741 742 743 744 745 746 747
	    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;
	    }
748
	    TBDebugTimeStamp("osload: event handler enabled");
749 750 751 752 753 754
	    
	    my %reboot_args     = ();
	    my %reboot_failures = ();

	    $reboot_args{'debug'}    = $debug;
	    $reboot_args{'waitmode'} = 0;
755
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];
756 757 758 759 760 761 762 763

	    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 = ();
		
764
		foreach my $node (@$reboot_nodes) {
765 766 767 768 769 770 771 772
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$failures++;
		    }
		    else {
			push(@temp, $node);
		    }
		}
773
		@nodes = (@temp,@$noreboot_nodes);
774 775 776 777 778
	    }
	}

	# Now wait for them.
	my $startwait   = time;
779 780 781
	my @failednodes = WaitTillReloadDone($startwait,
					     $waitmode,
					     \%reload_info, 
782 783
					     $eventnodes,
					     $evhandle,
784
					     @nodes);
785
				
786 787 788 789 790 791
	@nodes=();
    
	while (@failednodes) {
	    my $node = shift(@failednodes);

	    if ($retries{$node}) {
792
		tbnotice "$node: Trying again ...";
793

794 795
		my $reload_info = $reload_info{$node};

796
		# Possible race with reboot?
797
		if (&{$reload_info->{'func'}}($reload_info) < 0) {
798
		    tberror("$node: Could not set up reload. Skipping.");
799 800 801 802 803 804 805 806 807 808
		    $result->{$node} = -1;
		    $failures++;
		    next;
		}
		push(@nodes, $node);

		# Retry until count hits zero.
		$retries{$node} -= 1;
	    }
	    else {
809 810
		tberror ({sublevel => -1}, 
			 "$node failed to boot too many times. Skipping!");
811 812 813 814 815 816 817
		$result->{$node} = -1;
		$failures++;
	    }
	}
    }
  done:
    print "osload: Done! There were $failures failures.\n";
818 819 820 821 822 823 824 825
    
    #
    # 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));
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842

    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;
}

843 844 845 846 847
#
# Fetch information for a specified image the first time it is used
# (for the indicated node).  This info is cached for use by all other
# nodes that require the image.  Returns 1 on success, 0 on failure.
#
848
sub GetImageInfo($$)
849
{
850
    my ($image, $node) = @_;
851
    my $imagesize = 0;
852

853 854 855 856
    my $imageid = $image->imageid();
    my $rowref  = $image->DBData();
    if (!defined($rowref)) {
	tberror("No DBData for $image!");
857
	$imageinfo{$imageid} = 'BADIMAGE';
858 859
	return 0;
    }
860
    $imageinfo{$imageid} = $rowref;
861 862 863 864 865 866 867 868

    my $imagepath = $rowref->{'path'};

    #
    # Perform a few validity checks: imageid should have a file name
    # and that file should exist.
    #
    if (!defined($imagepath)) {
869
	tberror "No filename associated with $image!";
870
	$imageinfo{$imageid} = 'BADIMAGE';
871 872 873 874
	return 0;
    }

    if (! -R $imagepath) {
875
	#
876 877 878 879 880
	# 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.
881
	#
882 883
	# For either case, making a proxy query request via frisbee will
	# tell us whether the image is accessible and, if so, its size.
884
	# "imageinfo" makes that call for us.
885
	#
886
	my $frisimageid = $rowref->{'pid'} . "/" . $rowref->{'imagename'};
887 888 889
	my $sizestr = `$IMAGEINFO -qs -N $node $frisimageid`;
	if ($sizestr =~ /^(\d+)$/) {
	    $imagesize = $1;
890
	} else {
891
	    tberror "$image: access not allowed or image does not exist.";
892
	    $imageinfo{$imageid} = 'BADIMAGE';
893 894
	    return 0;
	}
895 896
    } else {
	$imagesize = stat($imagepath)->size;
897
    }
898

899 900 901 902 903 904 905 906 907
    #
    # 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!";
	$imageinfo{$imageid} = 'BADIMAGE';
	return 0;
908 909
    }

910 911 912 913 914 915 916
    #
    # 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.
    #
    if (!defined($rowref->{'maxloadwait'})) {
917
	my $chunks = $imagesize >> 20; # size may be > 2^31, shift is unsigned
918

919
	$rowref->{'maxloadwait'} = int((($chunks / 100.0) * 65)) + $TBLOADWAIT;
920 921 922
    }

    print STDERR
923
	"$image: loadpart=", $rowref->{'loadpart'},
924 925
	", loadlen=", $rowref->{'loadlength'},
	", imagepath=", $rowref->{'path'},
926
	", imagesize=", $imagesize,
927 928 929 930 931 932 933
	", defosid=", $rowref->{'default_osid'},
	", maxloadwait=", $rowref->{'maxloadwait'}, "\n"
	    if ($debug);

    return 1;
}

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

943 944 945 946 947 948 949 950 951 952
    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";
	}
    }
953

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

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

963 964 965 966 967 968 969 970 971
    #
    # 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;

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

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

		#
		# 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;
		}
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		
		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) {
1035
		    tbwarn "$node: Query failed; waiting a bit.";
1036 1037 1038 1039 1040 1041 1042 1043 1044
		    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);
1045

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

		#
		# 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";
		}
1058 1059 1060 1061 1062
	
		# Soon we will have stated's timeouts take care of
		# rebooting once or twice if we get stuck during
		# reloading.
		$waittime = time - $startwait;
1063
		
1064 1065 1066
		# If the node doesn't made a transition within $REBOOTWAIT
		# minutes of booting, we declare it stuck.
		my $isstuck = ($minutes > $REBOOTWAIT &&
1067 1068
			       exists($eventnodes->{$node}) &&
			       $eventnodes->{$node} == 0);
1069

1070
		if ($waittime > $maxwait ||
1071 1072 1073
		    $eventstate eq TBDB_NODESTATE_TBFAILED() ||
		    $eventstate eq TBDB_NODESTATE_PXEFAILED() ||
		    $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 1093
		    if ($eventstate eq TBDB_NODESTATE_TBFAILED() ||
			$eventstate eq TBDB_NODESTATE_PXEFAILED()) {
1094 1095 1096 1097
			tbnotice("  $node is stuck in $eventstate.");
		    }
		    elsif ($eventstate eq TBDB_NODESTATE_RELOADING()) {
			tbnotice("  $node did not finish reloading.");
1098
		    }
1099
		    elsif ($isstuck) {
1100 1101 1102
			tbnotice("  $node failed to make a state ".
				 "transition after $REBOOTWAIT minutes; ".
				 "stuck in $eventstate.");
1103
		    }
1104
		    TBNodeConsoleTail($node, *STDERR);
1105 1106

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

    if ($waitmode > 1) {
	$startwait = time;
Mike Hibler's avatar
Mike Hibler committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
	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,
				      TBDB_NODESTATE_PXEFAILED,
				      TBDB_NODESTATE_ISUP))) {
		    $done{$node} = $waitmode;
		} else {
		    push(@failed, $node);
1139 1140 1141 1142 1143
		}
	    }
	}
    }

1144 1145 1146 1147
    return @failed;
}

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

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

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    my $idx = 1;
    foreach my $imageid (@$imageids) {
	my $prepare0 = $idx == 1 && $prepare ? 1 : 0;
	my $query_result = 
	    DBQueryWarn("insert into current_reloads ".
			"(node_id, idx, image_id, mustwipe, prepare) values ".
			"('$node', $idx, '$imageid', $zerofree, $prepare0)");
	return -1
	    if (!$query_result);
	++$idx;
    }

1177 1178 1179 1180 1181 1182 1183 1184
    #
    # 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.
    #
    my $osinfo = OSinfo->Lookup($osid);
    if (!defined($osinfo) ||
	$nodeobject->OSSelect($osinfo, "next_boot_osid", 0)) {
1185
	tberror "os_select $osid failed!";
1186 1187
	return -1;
    }
1188 1189 1190

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

1194 1195 1196
    return 0;
}

1197 1198 1199 1200 1201
#
# 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.
#
1202
sub SetupReloadUISP($)
1203
{
1204 1205 1206 1207
    my $reload_info   = $_[0];
    my $node          = $reload_info->{'node'};
    my $imageid       = $reload_info->{'imageid'};
    my $osid          = $reload_info->{'osid'};
1208 1209 1210 1211 1212 1213 1214

    #
    # Get the path to the image
    #
    my $query_result = DBQueryFatal("select path from images " .
	"where imageid='$imageid'");
    if ($query_result->num_rows() != 1) {
1215
	tberror "Failed to get path for $imageid!";
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
	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) {
1236
	tberror "$node: tbuisp failed";
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	return -1;
    }

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

    system("$osselect $osid $node");
    if ($?) {
1247
	tberror "os_select $osid failed!";
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	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;
}

#
# Return two array references (possbily empty) of:
# [all nodes requiring reboot, all nodes not requiring reboot]
#
1264 1265
sub GetNodesRequiringReboot($@) {
    my ($reload_info, @nodes) = @_;
1266
    my (@reboot, @noreboot);
1267
    foreach my $node (@nodes) {
1268 1269 1270 1271 1272 1273 1274 1275 1276
	if ($reload_info->{$node}{'reboot'}) {
	    push @reboot, $node;
	} else {
	    push @noreboot, $node;
	}
    }
    return (\@reboot, \@noreboot);
}

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
#
# 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})) {
1288
	tberror "No such child pid $childpid!"; # INTERNAL
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
	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 {
1304
	    tberror "Improper response from child: $_"; # INTERNAL
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	}
    }
    
    #
    # And get the actual exit status.
    # 
    waitpid($childpid, 0);
    return $? >> 8;
}

1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
#
# 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 = "";

1331
    if (!@nodelist) {
1332
	@nodelist = ExpNodes($pid, $eid, 1, 0);
1333 1334 1335 1336 1337 1338 1339 1340 1341
	$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
1342
    $clause .= " and nt.class='pc' and nt.isremotenode=0";
1343 1344 1345 1346 1347 1348 1349 1350

    #
    # 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(
1351
	"select r.node_id,r.vname,r.pid,r.eid,r.erole,n.osid,p.partition,p.imageid,p.imagepid,i.imagename,i.loadpart,e.savedisk ".
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
	"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 ".
	"left join partitions as p on p.node_id=n.node_id and p.osid=n.def_boot_osid ".
        "left join images as i on i.imageid=p.imageid ".
        "left join experiments as e on e.pid=r.pid and e.eid=r.eid ".
	"where $clause");
    if (!$query_result) {
	return 1;
    }

1363
    while (my ($node, $vname, $rpid, $reid, $erole, $osid, $part, $imageid,
1364
	       $imagepid, $imagename, $lpart, $savedisk) =
1365 1366
	   $query_result->fetchrow_array()) {

1367 1368 1369 1370 1371 1372 1373 1374 1375
	my $nodeobject = Node->Lookup($node);

	# If the node is not imageable, skip it.
	next
	    if (! $nodeobject->imageable());
	
	my $dtype = $nodeobject->disktype();
	my $dunit = $nodeobject->bootdisk_unit();

1376 1377 1378 1379
	#
	# XXX not a disk-based OSID.  This can happen during frisbee loads
	#
	if (!defined($imageid)) {
1380
	    print "*** swapinfo: OS $osid is not disk-based!?\n";
1381 1382 1383 1384 1385
	    next
		if (!$allnodes);
	    return 1;
	}

1386 1387 1388
	#
	# Weed out otherwise ineligible nodes:
	#	- from experiments that are not saving disk state
1389
	#	- non-'node' role machines (i.e., delaynodes, virthosts)
1390 1391 1392 1393
	# They are removed from nodeinfo entirely so we do not complain about
	# them below.  This is the only reason we are doing this here rather
	# than as part of the above query.
	#
1394
	if (!defined($savedisk) || $savedisk == 0 || $erole ne "node") {
1395 1396 1397 1398
	    delete $nodeinfo{$node};
	    next;
	}

1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
	# Sanity checks
	if (!defined($nodeinfo{$node})) {
	    next
		if (!$allnodes);
	    print "*** swapinfo: Got partition info for invalid node $node!?\n";
	    return 1;
	}
	if ($nodeinfo{$node} != 0) {
	    print "*** swapinfo: Got redundant partition info for $node!?\n";
	    return 1;
	}
1410

1411 1412
	my $disk = "$dtype$dunit";
	$nodeinfo{$node} =
1413
	    [$vname, $rpid, $reid, $disk, $part, $imagepid, $imagename, $lpart];
1414 1415 1416 1417 1418 1419 1420
    }

    #
    # Copy over the signature file for the image used on every node under
    # the name <vname>.sig.  Likewise, we record the partition that the
    # image resides in under <vname>.part.
    #
1421
    # Note that we actually copy the signature over as <imagename>.sig and
1422 1423 1424
    # then symlink the <vname>.sig's to it.  This not only saves space,
    # but makes it easier to determine what is loaded on each node.
    #
1425 1426 1427 1428 1429
    # Finally note that we are using imagename rather than imageid (which
    # is a numeric UUID).  The latter is really closer to what we want, but
    # was added later and needs to be reconciled with our idea of 'unique'
    # (the signature).
    #
1430
    my %gotsig = ();
1431 1432 1433 1434 1435 1436
    for my $node (keys(%nodeinfo)) {
	my $infop = $nodeinfo{$node};
	if ($infop == 0) {
	    print "*** swapinfo: WARNING: got no partition info for $node!\n";
	    next;
	}
1437
	my ($vname, $rpid, $reid, $disk, $part, $imagepid, $imagename, $lpart) = @{$infop};
1438 1439 1440 1441 1442

	#
	# If imageid is not "fully qualified" with the project name,
	# generate a name that is.
	#
1443 1444 1445
	my $rimagename = $imagename;
	if ($rimagename !~ /^$imagepid-/) {
	    $rimagename = "$imagepid-$imagename";
1446 1447 1448
	}

	# XXX backward compat
1449
	my $infodir = "/$PROJROOT/$rpid/exp/$reid/swapinfo";
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
	if (! -d "$infodir" && !mkdir($infodir, 0770)) {
	    print "*** swapinfo: no swap info directory $infodir!\n";
	    next
		if (!$allnodes);
	    return 1;
	}

	#
	# First make sure we get rid of any old signature for the node
	# in case any of the following steps fail.
	#
	unlink("$infodir/$vname.sig", "$infodir/$vname.part");

1463 1464 1465 1466 1467
	#
	# Now copy over the base signature if needed, either because
	# it doesn't exist in the swapinfo directory or is out of date.
	#
	my $mustcopy = 0;
1468 1469 1470 1471
	my ($sigdir, $signame);
	if ($imagepid eq TBOPSPID()) {
	    $sigdir = "$TB/images/sigs";
	} else {
1472
	    $sigdir = "/$PROJROOT/$imagepid/images/sigs";
1473
	}
1474
	$signame = "$imagename.ndz.sig";
1475 1476
	$signame =~ s/^$imagepid-//;
	if (! -d $sigdir || ! -f "$sigdir/$signame") {
1477
	    print "*** swapinfo: WARNING: ".
1478
		"no image signature for $rimagename, ".
1479 1480 1481
		"cannot save swapout state!\n";
	    next;
	}
1482
	my $basesig = "$infodir/$rimagename.sig";
1483
	if (! -r $basesig) {
1484 1485 1486 1487 1488 1489
	    $mustcopy = 1;
	} elsif (!defined($gotsig{$basesig})) {
	    my $fromtime = stat("$sigdir/$signame")->mtime;
	    my $totime = stat($basesig)->mtime;
	    if ($fromtime > $totime) {
		print "*** swapinfo: WARNING: ".
1490
		    "$rimagename.sig out of date, updating...\n";
1491 1492 1493
		$mustcopy = 1;
	    } elsif ($fromtime < $totime) {
		print "*** swapinfo: WARNING: ".
1494
		    "$rimagename.sig newer than source $sigdir/$signame!\n";
1495 1496 1497 1498
	    }
	}
	if ($mustcopy) {
	    unlink($basesig);
1499 1500 1501 1502 1503 1504 1505
	    if (system("/bin/cp -p $sigdir/$signame $basesig")) {
		print "*** swapinfo: WARNING: ".
		      "could not create signature $basesig, ".
		      "cannot save swapout state!\n";
		next;
	    }
	}
1506 1507
	$gotsig{$basesig} = 1;

1508
	if (system("/bin/ln -s $rimagename.sig $infodir/$vname.sig")) {
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
	    print "*** swapinfo: WARNING: ".
		"could not create signature $infodir/$vname.sig, ".
		    "cannot save swapout state!\n";
	    next;
	}

	if (!open(FD, "> $infodir/$vname.part")) {
		print "*** swapinfo: WARNING: ".
		      "could not create partition file $infodir/$vname.part, ".
		      "cannot save swapout state!\n";
		unlink("$infodir/$vname.sig");
		next;
	}
	print FD "DISK=$disk ";
	print FD "LOADPART=$lpart ";
	print FD "BOOTPART=$part\n";
	close(FD);
    }
1527 1528 1529 1530 1531 1532 1533

    #
    # Now get rid of usused signature files
    # Note that we can only use the gotsig hash if we are loading all nodes
    # in an experiment (else we don't know whether a sig is used or not).
    #
    if ($allnodes) {
1534
	my $infodir = "/$PROJROOT/$pid/exp/$eid/swapinfo";
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	my @allsigs = `ls $infodir/*.sig`;
	chomp(@allsigs);
	for my $sig (@allsigs) {
	    if (! -l $sig && !defined($gotsig{$sig})) {
		# untaint the file name
		if ($sig =~ /^($infodir\/[-\w\.\+]+\.sig)$/) {
		    $sig = $1;
		    print "removing unused signature file $sig ...\n";
		    unlink($sig);
		}
	    }
	}
    }
1548 1549
}

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
sub SetupEventHandler($)
{
    my ($handler) = @_;
    
    my $port = @BOSSEVENTPORT@;
    my $URL  = "elvin://localhost:$port";
    
    # Connect to the event system, and subscribe the the events we want
    my $EVhandle = event_register($URL, 0);
    
    if (!$EVhandle) {
	print STDERR "*** event: Unable to register with event system\n";
	return undef;
    }

    my $tuple = address_tuple_alloc();
    if (!$tuple) {
	print STDERR "*** event: Could not allocate an address tuple\n";
	return undef;
    }

    # These are the states that indicate things are happening.
    my @states = (TBDB_NODESTATE_RELOADSETUP(),
		  TBDB_NODESTATE_RELOADING());

    %$tuple = ( objtype   => TBDB_TBEVENT_NODESTATE(),
		eventtype => join(",", @states),
	      );
    
    if (!event_subscribe($EVhandle, $handler, $tuple)) {
	print STDERR "*** event: Could not subscribe to events\n";
	return undef;
    }
    return $EVhandle;
}

1586 1587
# _Always_ make sure that this 1 is at the end of the file...
1;