libosload_new.pm.in 63.9 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2011 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
# All rights reserved.
#
# Osload library. Basically the backend to the osload script, but also used
# where we need finer control of loading of nodes.
#
package libosload_new;

use strict;
use Exporter;
use vars qw(@EXPORT $AUTOLOAD $MAXRETRIES);
use base qw( Exporter );

@EXPORT = qw( $MAXRETRIES );

# Must come after package declaration!
use libtestbed; # for TBGenSecretKey();
use libdb;
use libreboot;
use libtblog;
use Node;
use NodeType;
use Image;
use User;
use OSinfo;
use English;
use event;
use Data::Dumper;
use IO::Handle;
use overload ('""' => 'Stringify');

# Configure variables
my $TB		= "@prefix@";
my $TESTMODE    = @TESTMODE@;
my $TBOPS       = "@TBOPSEMAIL@";
my $ELABINELAB  = @ELABINELAB@;
my $PROJROOT    = "@PROJROOT_DIR@";
41
my $OUTERBOSS	= "@OUTERBOSS_NODENAME@";
42

43
# Paths to binaries
44
my $TBUISP	    = "$TB/bin/tbuisp";
45 46
my $FRISBEE         = "$TB/sbin/frisbee";

47 48 49 50 51
# XXX windows load
my $MAKECONF	    = "$TB/sbin/dhcpd_makeconf";
my $IMAGEX_OSNAME   = "IMAGEX-MFS";
my $IMAGEX_PXEPATH  = "/tftpboot/pxelinux/winpe";

52 53 54 55 56 57
#
# Max number of retries (per node) before its deemed fatal. This allows
# for the occasional pxeboot failure.
#
$MAXRETRIES  = 1;

58 59 60 61 62 63 64
#
# 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!)
# XXX should this be exported like MAXRETRIES?
#
my $TBLOADWAIT  = (10 * 60);

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
# Locals
my $remote_mult     = 5;        # Wait lots longer for remote nodes!

#
# The point of this is to create a data structure that we can
# pass around. 
#
sub New($$$;@)
{
    my ($class,@nodelist) = @_;

    my $self              = {};
    $self->{'HASH'}       = {};
    $self->{'CHILDREN'}   = {};
    $self->{'NODES'}      = {};
    $self->{'FLAGS'}      = {};
    $self->{'NODEFLAGS'}  = {};
    $self->{'NODEINFO'}   = {};
    $self->{'IMAGEINFO'}  = {};
    $self->{'OSMAP'}      = {};
    $self->{'FAILED'}     = {};
    $self->{'FAILCOUNT'}  = 0;
    $self->{'TYPECACHE'}  = {};
    $self->{'TYPEOBJECTS'} = {};

    foreach my $node (@nodelist) {
	$self->{'NODES'}->{$node->node_id()} = $node;

	# Init some per-node stuff.
    }

    bless($self, $class);

    # We need this guy right away!
    $self->debug(0);

    return $self;
}
# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    foreach my $key (keys(%{ $self })) {
	$self->{$key} = undef;
    }
}
sub nodelist($)		{ return $_[0]->{'NODES'}; }
sub failedlist($)	{ return $_[0]->{'FAILED'}; }
sub user($)		{ return $_[0]->{'USER'}; }
sub experiment($)	{ return $_[0]->{'EXPT'}; }
sub incrfailcount($)    { $_[0]->{'FAILCOUNT'}++ }
sub failed($)           { return $_[0]->{'FAILCOUNT'}; }

118 119
sub dprint($$;@) {
    my ($self,$level,@args) = @_;
120
    print STDERR "$self " . join('',@args) . "\n"
121
	if ($self->debug() > $level);
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
}
sub dprintts($@) {
    my ($self,@args) = @_;
    TBDebugTimeStamp("$self " . join('',@args))
	if ($self->debug());
}

# Grab a node by node_id.
sub node($$)
{
    my ($self, $node_id) = @_;

    if (exists($self->{'NODES'}->{$node_id})) {
	return $self->{'NODES'}->{$node_id};
    }

    tbwarn "$self nodeobject lookup failed for $node_id!\n";
    return undef;
}

# Get/set a type object by node.
sub typeobject($$;$)
{
    my ($self, $nodeobject, $typeobject) = @_;
    my $node_id = $nodeobject->node_id();

    if (defined($typeobject)) {
	$self->{TYPEOBJECTS}->{$node_id} = $typeobject;
	return $typeobject;
    }

    if (exists($self->{TYPEOBJECTS}->{$node_id})) {
	return $self->{TYPEOBJECTS}->{$node_id};
    }
    return undef;
}

# Store/retrieve misc reload info for this node
sub nodeinfo($$$;$)
{
    my ($self,$nodeobject,$key,$data) = @_;
    if (!defined($nodeobject)) {
	tbwarn "$self nodeinfo called with $key and no node!\n";
    }
    my $node_id = $nodeobject->node_id();

    if (defined($data)) {
	$self->{NODEINFO}->{$node_id}->{$key} = $data;
170
	$self->dprint(3,"nodeinfo($node_id,$key) <- $data)");
171 172 173 174 175
	return $data;
    }
    if (exists($self->{NODEINFO}->{$node_id}->{$key})) {
	my $retval = $self->{NODEINFO}->{$node_id}->{$key};
	my $pretval = defined($retval) ? $retval : "undef";
176
	$self->dprint(3,"nodeinfo($node_id,$key) -> $pretval");
177 178 179 180 181 182
	return $retval;
    }
    return undef;
}
sub nodeinfo_unset($$$)
{
183
    my ($self,$nodeobject,$key) = @_;
184
    if (!defined($nodeobject)) {
185
	tbwarn "$self nodeinfo_unset called with $key and no node!\n";
186 187 188
    }
    my $node_id = $nodeobject->node_id();
    
189
    $self->dprint(3,"nodeinfo_unset($nodeobject,$key)");
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    if (exists($self->{NODEINFO}->{$node_id}->{$key})) {
	delete $self->{NODEINFO}->{$node_id}->{$key};
    }
    
    return 0;
}

# Store/retrieve osload flags.  Check the per-node flags first, then
# the global flags.
sub nodeflag($$$;$)
{
    my ($self,$nodeobject,$flagname,$flagval) = @_;

    my $retval;

    my $node_id = $nodeobject->node_id();
    if (defined($flagval)) {
	$self->{NODEFLAGS}->{$node_id}->{$flagname} = $flagval;
	$retval = $flagval;
    }
    elsif (exists($self->{NODEFLAGS}->{$node_id}->{$flagname})) {
	$retval = $self->{NODEFLAGS}->{$node_id}->{$flagname};
    }
    elsif (exists($self->{FLAGS}->{$flagname})) {
	$retval = $self->{FLAGS}->{$flagname};
    }

    my $pretval = defined($retval) ? $retval : "undef";
218
    $self->dprint(2,"nodeflag($node_id,$flagname) -> $pretval");
219 220 221 222

    return $retval;
}
    
223
# Get/Set the imageid->images mapping. Nice to keep this to avoid lookups.
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
sub imageinfo($$;$)
{
    my ($self,$imageid,$imageinfo) = @_;
    if (defined($imageinfo)) {
	# set it
	$self->{'IMAGEINFO'}->{$imageid} = $imageinfo;
	return $imageinfo;
    }

    return $self->{'IMAGEINFO'}->{$imageid}
        if (exists($self->{'IMAGEINFO'}->{$imageid}));

    return undef;
}

# Get/Set the osid->osinfo mapping. Nice to keep this to avoid lookups.
sub osmap($$;$)
{
    my ($self, $osid, $osinfo) = @_;

    if (defined($osinfo)) {
	return $self->{'OSMAP'}->{$osid} = $osinfo;
    }
    elsif (exists($self->{'OSMAP'}->{$osid})) {
	return $self->{'OSMAP'}->{$osid};
    }
    return undef;
}

# To avoid writing out all the methods.
sub AUTOLOAD {
    my $self = shift;
    my $type = ref($self) or die("$self is not an object\n");

    my $name = $AUTOLOAD;
    $name =~ s/.*://;   # strip fully-qualified portion

    if (@_) {
	return $self->{'HASH'}->{$name} = shift;
    }
    elsif (exists($self->{'HASH'}->{$name})) {
	return $self->{'HASH'}->{$name};
    }
    print STDERR "libosload_new: tried to access unknown slot $name\n";
    return undef;
}

#
# Create a type (or class) specific object to handle those nodes.
#
sub NewType($$)
{
    my ($self, $type) = @_;

278
    $self->dprint(2,"NewType($type): trying to create type object");
279 280 281 282 283

    my $packname = "libosload_${type}";
    my $newtype  = eval { $packname->New($self); };
    # Not loaded?
    if ($@) {
284
	$self->dprint(2,"NewType($type): simple module load failed: " . $@);
285 286 287
	eval "require libosload_$type";
	$newtype  = eval { $packname->New($self); };
	if ($@) {
288
	    $self->dprint(1,"$self NewType($type): module load failed: " . $@);
289 290 291 292 293
	    return undef;
	}
    }
    $self->{'TYPECACHE'}->{$type} = $newtype;
    
294
    $self->dprint(3,"NewType($type): created type object $newtype");
295 296 297 298 299 300 301 302 303 304 305 306 307
    
    return $newtype;
}

#
# Return the cached type object.
#
sub TypeLookup($$;$)
{
    my ($self, $nodeobject, $forcedtype) = @_;

    my $type  = $nodeobject->type();
    my $class = $nodeobject->class();
308
    my $node_id = $nodeobject->node_id();
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

    if (defined($forcedtype)) {
	return $self->{'TYPECACHE'}->{$forcedtype}
            if (exists($self->{'TYPECACHE'}->{$forcedtype}));
    }
    else {
	return $self->{'TYPECACHE'}->{$type}
            if (exists($self->{'TYPECACHE'}->{$type}));

	return $self->{'TYPECACHE'}->{$class}
            if (exists($self->{'TYPECACHE'}->{$class}));
    }

    return undef;
}

sub ChildCreate($$;$)
{
    my ($self,$data,$child_writer_ptr) = @_;

    #
    # Create a pipe to read back results from the child we will create.
    #
    my $PARENT_READER = new IO::Handle; # Need a new handle for each child
    my $CHILD_WRITER = new IO::Handle; # Need a new handle for each child
    if (! pipe($PARENT_READER, $CHILD_WRITER)) {
	tberror "creating pipe: $!";
	return -1;
    }
    if (defined($child_writer_ptr)) {
	$$child_writer_ptr = $CHILD_WRITER;
    }
    $CHILD_WRITER->autoflush(1);

    if (my $childpid = fork()) {
	close($CHILD_WRITER);

	$self->{CHILDREN}->{$childpid} = [ $PARENT_READER, $data ];

348
	$self->dprint(4,"ChildCreate: created $childpid");
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

	return $childpid;
    }

    #
    # Child keeps going. 
    #
    close($PARENT_READER);
    TBdbfork();

    return 0;
}

sub ChildReap($)
{
    my ($self,$childpid) = @_;

    my $childdataptr;
    if (exists($self->{CHILDREN}->{$childpid})) {
	$childdataptr = $self->{CHILDREN}->{$childpid};
    }
    else {
	tberror "$self ChildReap: no such child pid $childpid!"; # INTERNAL
	return -1;
    }
    my ($PARENT_READER, $data) = @$childdataptr;

    #
    # Read back the results.
    # 
    my @output = ();
    while (<$PARENT_READER>) {
	push @output, $_;
    }
    
    #
    # And get the actual exit status.
    # 
    waitpid($childpid, 0);
    return ($data,$? >> 8,@output);
}

#
# XXX -- shoudl teh API change to use the object more?
#
sub osload($$$) {
    my ($self, $args, $result) = @_;
    my $CHILD_WRITER;

    $self->dprintts("osload starting on nodes " . join(' ',@{$args->{'nodelist'}}));

400
    # set some default flags
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    my %flags = ();
    $flags{waitmode}    = 1;
    $flags{usecurrent}  = 0;
    $flags{noreboot}    = 0;
    $flags{asyncmode}   = 0;
    $flags{zerofree}    = 0;
    $flags{prepare}     = 0;
    $flags{swapinfo}    = 0;

    # These come in from the caller.
    my @imageids;
    my @nodes       = ();
    my %nodeflags   = ();

    # Locals
    my $mereuser    = 0;
    my $rowref;
    my @images;
    my $this_user;

    if (!defined($args->{'nodelist'})) {
	tberror "Must supply a node list!"; # INTERNAL
	return -1;
    }
    @nodes = sort(@{ $args->{'nodelist'} });

    #
    # Although the object can support multiple osloads in flight at once,
    # don't allow multiple reloads per node in different osload invocations!
    #
    foreach my $node (@nodes) {
	if (exists($self->{NODES}->{$node})) {
	    tberror "$self is already loading $node!\n";
	    return -1;
	}
    }
437 438 439 440

    # override our defaults
    foreach my $flag (keys(%$args)) {
	$flags{$flag} = $args->{$flag};
441
    }
442
    # handle some of the flags specially
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    if (defined($args->{'imageid'})) {
	@imageids = split(/,/, $args->{'imageid'});
    }
    if (defined($args->{'imageids'})) {
	@imageids = @{$args->{'imageids'}};
    }
    if (defined($args->{'nodeflags'})) {
	%nodeflags = %{$args->{'nodeflags'}};
    }

    $self->{FLAGS} = \%flags;

    if (!$self->debug() || $flags{asyncmode}) {
	#
	# Start a new logging sub-process
	#
	my $old_env = \%ENV;
	local %ENV;
	copy_hash %ENV, $old_env;
	tblog_sub_process("osload", @nodes);
    }

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

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

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

	#
	# 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 
	    "Would exceed maxiumum concurrent instances ".
		"limitation for $image";
	    return -1;
	}

	# 
	# XXX should we do this?
	# Load up the imageinfo before we fork to minimize queries and maximize
	# mem sharing.
	#
	#$self->GetImageInfo($image);
    }

    #
    # 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 ($flags{asyncmode}) {
	my $retval = $self->ChildCreate([ $result,$args ],\$CHILD_WRITER);
	if ($retval < 0) {
	    tberror "$self: create child: $!";
	    return -1;
	}
	elsif ($retval) {
	    foreach my $node (@nodes) {
		# All nodes start out as being failed from the parent's perspective; altered later as needed.
		$result->{$node} = -1;
	    }
	    return $retval;
	}
	#
	# Child continues
	#
    }

555
    my %access_keys = ();
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
    # Loop for each node.
    foreach my $node (@nodes) {
	# All nodes start out as being successful; altered later as needed.
	$result->{$node} = 0;

	# Try to find the node before doing anything else.
	my $nodeobject = Node->Lookup($node);
	if (!defined($nodeobject)) {
	    tberror "$node: Could not map to object!";
	    goto failednode;
	}

	#
	# Look for type specific module first.
	#
	my $forcedtype;
	$nodeobject->NodeAttribute('osload_objtype',\$forcedtype);
	if (!defined($forcedtype)) {
	    $nodeobject->NodeTypeAttribute('osload_objtype',\$forcedtype);
	}
	my $object = $self->TypeLookup($nodeobject,$forcedtype);
	if (!defined($object)) {
	    $object = $self->NewType(defined($forcedtype) ? $forcedtype 
				                          : $nodeobject->type());
	    if (defined($forcedtype) && !defined($object)) {
		#
		# If they shoot themselves in the foot, their fault!
		# Don't fall back to real type or class!
		#
		die_noretry("$self: could not find type object for forced type $forcedtype -- check your attributes!");
	    }
	    elsif (!defined($object)) {
		#
		# Otherwise use the class.
		#
		$object = $self->NewType($nodeobject->class());
		if ($@) {
David Johnson's avatar
David Johnson committed
593
		    die_noretry("$self: no type/class specific osload module for $node");
594 595 596
		}
	    }

597
	    $self->dprint(2,"osload($node): used typeobject $object");
598 599 600 601 602 603 604 605 606 607 608
	}

	# Save off this type object for this node
	$self->typeobject($nodeobject,$object);

	# Construct a local copy of per-image flags overridden by per-node
	# flags
	my %nargs = ();
	foreach my $k (keys(%flags)) {
	    $nargs{$k} = $flags{$k};
	}
609
	foreach my $k (keys(%{$nodeflags{$node}})) {
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
	    $nargs{$k} = $nodeflags{$node}{$k};
	}
	# Wait, don't do this -- waitmode is global; nowait is per-node!
	#
        # XXX hack to handle that we would see a 'nowait' flag per-node,
	# but a 'waitmode' flag globally.  Since we now just have per-node flags
	# available to the type-specific objects, we just override waitmode.
	#if (exists($nargs{nowait})) {
	#    $nargs{waitmode} = $nargs{nowait};
	#}

	#
	# Add the node with the given images and arguments
	#
	if ($object->AddNode($nodeobject,\@images,\%nargs)) {
	    goto failednode;
	}
	# We also need to add it to ourself for non-type-specific metadata
	# storage
	if ($self->AddNode($nodeobject,\@images,\%nargs)) {
	    goto failednode;
	}
	$self->typeobject($nodeobject,$object);
	
	#
	# Setup a bunch of database state before setting up the actual reload:
	# setting the boot osid, adjusting the partitions table, setting up
	# swapinfo.
	#
	if ($object->PreSetupReload($nodeobject)) {
	    goto failednode;
	}
642

643 644 645 646 647
	#
	# This is a bad place for this, but it has to go somewhere, and handling
	# remote nodes is not really a type-specific thing!  It's more a 
	# feature mixin than a type-specific class!
	#
648 649 650 651 652 653
	foreach my $image (@images) {
	    # This is passed along so that remote node can request the file.
	    # Make sure the image object has an access key defined.
	    if (defined($image->access_key()) && $image->access_key() ne '') {
		$access_keys{$image} = $image->access_key();
	    }
David Johnson's avatar
David Johnson committed
654
	    elsif ($nodeobject->isremotenode() && !defined($access_keys{$image})) {
655 656 657
		$access_keys{$image} = TBGenSecretKey();
		
		$rowref->{'access_key'} = $access_keys{$image};
David Johnson's avatar
David Johnson committed
658 659
		if ($image->Update({'access_key' => $access_keys{$image}}) != 0) {
		    tberror "$self ($node): Could not initialize image access key";
660 661 662 663
		    goto failednode;
		}
	    }
	}
664 665 666 667

	#
	# Setup the reload, finally!
	#
668
	print "$object: setting up reload for $node\n";
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

	if (!$TESTMODE) {
	    if ($object->SetupReload($nodeobject)) {
		tberror("$self ($node): Could not set up reload. Skipping.");
		goto failednode;
	    }

	    if ($object->Reload($nodeobject)) {
		tberror("$self ($node): direct reload failed. Skipping.");
		goto failednode;
	    }
	}

	next;
	
      failednode:
	$object->RemoveNode($nodeobject);
	$self->RemoveNode($nodeobject);
	$result->{$node} = -1;
	$self->incrfailcount();
    }

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

    # Exit if not doing an actual reload.
    if ($TESTMODE) {
	print "$self: Stopping in Testmode!\n";
	goto done;
    }

    if (! @nodes) {
	tbnotice "$self: Stopping because of previous failures!";
	goto done;
    }

    # Fire off a mass reboot and quit if not in waitmode.
    if (!$flags{waitmode}) {
	my ($reboot_nodes, $noreboot_nodes)
	    = $self->GetNodesRequiringReboot(@nodes);
	if (@$reboot_nodes) {
	    print "$self: Rebooting nodes.\n";

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

	    $reboot_args{'debug'}    = $self->debug();
	    $reboot_args{'waitmode'} = 0;
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];

	    if (nodereboot(\%reboot_args, \%reboot_failures)) {
		foreach my $node (@$reboot_nodes) {
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$self->incrfailcount();
		    }
		}
	    }
	}
	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) {
	my $nodeobject = $self->node($node);
	my $typeobject = $self->typeobject($nodeobject);
	$self->nodeinfo($nodeobject,'retries',$typeobject->GetMaxRetries());
    }

    #
    # XXX not all type objects will need/want events to signal completion,
    # so we could eventually separate this out, but not for now.
    #
    # 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) = @_;
    
	my $node_id = event_notification_get_objname($handle,$notification);
	my $event   = event_notification_get_eventtype($handle,$notification);

	return
	    if (!defined($eventnodes));

	print "$self: eventhandler: $node_id, $event\n"
	    if ($self->debug());

	if (exists($eventnodes->{$node_id})) {
	    $eventnodes->{$node_id} = time();
	}
    };
    my $evhandle = $self->SetupEventHandler($handler);
    if (!defined($evhandle)) {
	tbnotice "$self: Stopping because event registration failed!";
	foreach my $node (@nodes) {
	    $result->{$node} = -1;
	    $self->incrfailcount();
	}
	goto done;
    }

    while (@nodes) {
	my ($reboot_nodes, $noreboot_nodes)
	    = $self->GetNodesRequiringReboot(@nodes);
	if (@$reboot_nodes) {
	    # Reboot them all.
	    print "$self: ".
		"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;
	    }
	    
	    my %reboot_args     = ();
	    my %reboot_failures = ();

	    $reboot_args{'debug'}    = $self->debug();
	    $reboot_args{'waitmode'} = 0;
	    $reboot_args{'nodelist'} = [ @$reboot_nodes ];

	    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 = ();
		
		foreach my $node (@$reboot_nodes) {
		    if ($reboot_failures{$node}) {
			$result->{$node} = $reboot_failures{$node};
			$self->incrfailcount();
		    }
		    else {
			push(@temp, $node);
		    }
		}
		@nodes = (@temp,@$noreboot_nodes);
	    }
	}

	# Now wait for them.
	my $startwait   = time;
	my @failednodes = $self->WaitTillReloadDone($startwait,
						    $flags{waitmode},
						    $eventnodes,
						    $evhandle,
						    @nodes);
				
	@nodes = ();
    
	while (@failednodes) {
	    my $node = shift(@failednodes);
	    my $nodeobject = $self->node($node);
	    my $typeobject = $self->typeobject($nodeobject);

	    my $retries = $self->nodeinfo($nodeobject,'retries');
	    if ($retries) {
		tbnotice "$self ($node): Trying again ...";

		# Possible race with reboot?
		if ($typeobject->SetupReload($nodeobject) < 0) {
		    tberror("$self ($node): Could not set up reload. Skipping.");
		    $result->{$node} = -1;
		    $self->incrfailcount();
		    $typeobject->ReloadDone($nodeobject);
		    next;
		}

		if ($typeobject->Reload($nodeobject) < 0) {
		    tberror("$self ($node): direct reload failed. Skipping.");
		    $result->{$node} = -1;
		    $self->incrfailcount();
		    $typeobject->ReloadDone($nodeobject);
		    next;
		}

		push(@nodes, $node);

		# Retry until count hits zero.
		$self->nodeinfo($nodeobject,'retries',$retries - 1);
	    }
	    else {
		tberror ({sublevel => -1}, 
			 "$self: $node failed to boot too many times. Skipping!");
		$result->{$node} = -1;
		$typeobject->ReloadDone($nodeobject);
		$self->incrfailcount();
	    }
	}
    }
  done:
    my $failures = $self->failed();
    print "$self: Done! There were $failures failures.\n";

    if ($flags{asyncmode}) {
878
	$self->dprint(3,"osload: asyncmode osload writing results");
879 880 881 882 883 884
	#
	# 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};
885
	    $self->dprint(3,"osload: asyncmode osload writing result ($node,$status)");
886 887 888 889
	    print $CHILD_WRITER "$node,$status\n";
	}
	close($CHILD_WRITER);

890
	$self->dprintts("osload: asyncmode finished");
891 892 893 894

	exit($failures);
    }

895
    $self->dprintts("osload: finished");
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    return $failures;
}

sub GetMaxRetries($)
{
    return $MAXRETRIES;
}

#
# Add a node to the list.  This should of course be overridden -- this is just
# a basic version for the libosload_new main package!  And of course, 
# libosload_common does override it.
#
sub AddNode($$$$)
{
    my ($self, $nodeobject, $imagelist, $args) = @_;
    my $node_id = $nodeobject->node_id();

914
    $self->dprint(0,"AddNode($node_id): starting");
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

    $self->{'NODES'}->{$node_id}    = $nodeobject;
    $self->{'NODEFLAGS'}->{$node_id}    = $args;
    $self->{'IMAGES'}->{$node_id}   = $imagelist;

    return 0;
}

#
# Fetch information for a specified image the first time it is used.
# This info is cached for use by all other 
# nodes that require the image.  Returns 1 on success, 0 on failure.
#
sub GetImageInfo($$$)
{
    my ($self, $image, $rowrefptr) = @_;
931
    my $imagesize = 0;
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954

    my $imageid = $image->imageid();
    my $rowref  = $image->DBData();
    if (!defined($rowref)) {
	tberror("No DBData for $image!");
	$$rowrefptr = 'BADIMAGE';
	return -1;
    }
    $$rowrefptr = $rowref;

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

    #
    # 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!";
	$$rowrefptr = 'BADIMAGE';
	return -1;
    }

    if (! -R $imagepath) {
955 956 957 958 959 960 961
	#
	# If the image doesn't exist and we are in an inner elab,
	# make sure real boss has it and see how big it is.
	#
	# Note that we don't actually pre-fetch the image here,
	# that will be done automatically when the image is first requested.
	#
962
	if ($ELABINELAB) {
963 964 965 966 967 968 969 970 971 972 973
	    my $frisimageid = $rowref->{'pid'} . "/" . $rowref->{'imagename'};

	    my $attr = `$FRISBEE -S $OUTERBOSS -Q $frisimageid`;
	    if ($attr =~ /error=0/) {
		if ($attr =~ /size=(\d+)/) {
		    $imagesize = $1;
		} else {
		    $imagesize = 1 * 1024 * 1024 * 1024;
		}
	    } else {
		tberror "Query to $OUTERBOSS for info on $image failed!";
974 975 976 977 978 979 980 981 982 983
		$$rowrefptr = 'BADIMAGE';
		return -1;
	    }
	}
	else {
	    tberror "$imagepath does not exist or cannot be read!";
	    $$rowrefptr = 'BADIMAGE';
	    return -1;
	}
    }
984
    else {
985 986
	(undef,undef,undef,undef,undef,undef,undef,$imagesize,
	 undef,undef,undef,undef,undef) = stat($imagepath);
987

988 989 990 991 992 993 994
	#
	# 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!";
995 996
	    $$rowrefptr = 'BADIMAGE';
	    return -1;
997 998
	}
    }
999 1000

    # cache as long as we just looked!
1001
    $rowref->{size} = $imagesize;
1002 1003 1004 1005 1006 1007

    #
    # 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.
    #
1008
    if ($imagesize == 0) {
1009 1010 1011 1012 1013
	tberror "$imagepath is empty!";
	$$rowrefptr = 'BADIMAGE';
	return -1;
    }

1014
    $self->dprint(3,"GetImageInfo($image): loadpart=", $rowref->{'loadpart'},
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
		  ", loadlen=", $rowref->{'loadlength'},
		  ", imagepath=", $rowref->{'path'},
		  ", defosid=", $rowref->{'default_osid'});

    return 0;
}

# Wait for a reload to finish by watching its state
sub WaitTillReloadDone($$$$$@)
{
    my ($self, $startwait, $waitmode,
	$eventnodes, $evhandle, @nodes) = @_;
    my %done	= ();
    my $count   = @nodes;
    my @failed  = ();

1031
    $self->dprintts("WaitTillReloadDone(" . join(',',@nodes) . ") starting");
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

    foreach my $node ( @nodes ) {
	my $nodeobject = $self->node($node);
	if (1 && !$self->nodeflag($nodeobject,'nowait')) {
	    $done{$node} = 0;
	}
	else {
	    $done{$node} = 1;
	    --$count;
	    print "$self: not waiting for reload of $node.\n";
	}
    }

1045
    $self->dprint(1,"WaitTillReloadDone(" . join(',',@nodes) . "): waiting for nodes to finish reloading (".`date`.")")
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
	if ($count && $self->debug());

    # figure out our per-node max wait times
    foreach my $node (@nodes) {
	my $nodeobject = $self->node($node);
	my $typeobject = $self->typeobject($nodeobject);
	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?
	#
	# Else, if we have a remote node, we wait another multiplier.
	#
	if ($self->nodeflag($nodeobject,'zerofree')) {
	    my $disksize = $nodeobject->disksize();

	    $disksize = 20
		if (!$disksize);
	    $maxwait = ($disksize * 60);
	} elsif ($nodeobject->isremotenode()) {
	    $maxwait = $typeobject->ComputeMaxLoadWaitTime($nodeobject) * $remote_mult ;
	} else {
	    $maxwait = $typeobject->ComputeMaxLoadWaitTime($nodeobject);
	}

	$self->nodeinfo($nodeobject,'maxwait',$maxwait);
    }

    # Start a counter going, relative to the time we rebooted the first
    # node.
    my $waittime  = 0;
    my $minutes   = 0;

    while ($count > 0) {
	# Wait first to make sure reboot is done, and so that we don't
	# wait one more time after everyone is up.
	sleep(5);
	event_poll($evhandle);
	foreach my $node (@nodes) {
	    if (! $done{$node}) {
		my $nodeobject = $self->node($node);
		my $typeobject = $self->typeobject($nodeobject);
		my $maxwait = $self->nodeinfo($nodeobject,'maxwait');

		#
		# If we did a direct reload via typeobject->Reload(), we 
		# need to ask teh typeobject when the reload finishes (or
		# at least try, so it can 1) garbage collect the childpid
		# state, and 2) potentially tell us what happened!).
		#
		# Of course, if the typeobject tells us not to expect anything,
		# we don't worry about it, and instead query via the methods
		# below.
		#
		my ($typewaitstatus,$typeretval,@typeoutput) = 
		    $typeobject->WaitForNode($nodeobject);
1108
		$self->dprint(2,"$typeobject->WaitForNode($node) -> $typewaitstatus");
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
		if ($typewaitstatus > 0) {
		    --$count;
		    if ($typeretval) {
			$done{$node} = $waitmode;
			push @failed, $node;
		    }
		    else {
			# success!
			$count--;
			$done{$node} = 1;
			$typeobject->ReloadDone($nodeobject);
		    }
		    next;
		}
		elsif ($typewaitstatus == 0) {
		    # we need to keep waiting for this node, so don't check
		    # the db
		    ;
		}
		else {
		    # we haven't done a direct reload, so poll the db
		    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) {
			tbwarn "$self ($node): Query failed; waiting a bit.";
			next;
		    }

		    #
		    # We simply wait for stated to clear the current_reloads entry.
		    #
		    if (!$query_result->numrows) {
1147
			$self->dprint(1,"$self: WaitTillReloadDone($node): left reloading mode at ".`date`)
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
			    if ($self->debug());
		    
			$count--;
			$done{$node} = 1;
			$typeobject->ReloadDone($nodeobject);
			next;
		    }
		}

		#
		# All of the eventstate stuff belongs in stated. Sheesh.
		#
		my $eventstate;
		if ($nodeobject->GetEventState(\$eventstate)) {
1162
		    $self->dprint(2,"$self ($node): Could not get event state");
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
		}
	
		# Soon we will have stated's timeouts take care of
		# rebooting once or twice if we get stuck during
		# reloading.
		$waittime = time - $startwait;
		
		if ($waittime > $maxwait ||
		    (defined($eventstate) &&
		     ($eventstate eq TBDB_NODESTATE_TBFAILED() ||
		      $eventstate eq TBDB_NODESTATE_PXEFAILED())) ||
		    ($minutes > 5 &&
		     exists($eventnodes->{$node}) &&
		     $eventnodes->{$node} == 0)) {
		    my $t = (int ($waittime / 60));
		    tbnotice "$self: $node appears wedged; ".
			"it has been $t minutes since it was rebooted.";

		    if (defined($eventstate) &&
			($eventstate eq TBDB_NODESTATE_TBFAILED() ||
			 $eventstate eq TBDB_NODESTATE_PXEFAILED())) {
			tbnotice("$self: $node looks stuck in $eventstate.");
		    }
		    elsif ($minutes > 5 &&
			   exists($eventnodes->{$node}) &&
			   $eventnodes->{$node} == 0) {
			tbnotice("$self: $node failed to enter reloading state.");
		    }
		    TBNodeConsoleTail($node, *STDERR);

		    $count--;
		    $done{$node} = $waitmode;
		    push(@failed, $node);
		    next;
		}
		if (int($waittime / 60) > $minutes) {
		    $minutes = int($waittime / 60);
		    print STDERR "$self ($node): still waiting; ".
			"it has been $minutes minute(s)\n";
		}
	    }
	}
    }

    if ($waitmode > 1) {
	$startwait = time;
	foreach my $node (@nodes) {
	    print STDERR
		"$self ($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);
		}
	    }
	}
    }

1230
    $self->dprintts("WaitTillReloadDone(" . join(',',@nodes) . "): finished");
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268

    return @failed;
}



#
# Return two array references (possbily empty) of:
# [all nodes requiring reboot, all nodes not requiring reboot]
#
sub GetNodesRequiringReboot($@) {
    my ($self,@nodes) = @_;
    my (@reboot, @noreboot);

    foreach my $node_id (@nodes) {
	my $nodeobject = $self->node($node_id);
	my $typeobject = $self->typeobject($nodeobject);
	if (!$typeobject->nodeflag($nodeobject,'noreboot')) {
	    push @reboot, $nodeobject->node_id();
	}
	else {
	    push @noreboot, $nodeobject->node_id();
	}
    }

    return (\@reboot, \@noreboot);
}

#
# 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 ($self,$childpid) = @_;

1269
    $self->dprintts("osload_wait($childpid): starting");
1270 1271 1272 1273 1274 1275 1276 1277 1278

    my ($data,$retval,@output) = $self->ChildReap($childpid);
    my ($result,$args) = @$data;

    foreach my $line (@output) {
	chomp($line);

	if ($line =~ /^([-\w]+),([-\d])+$/) {
	    $result->{$1} = $2;
1279
	    print STDERR "$self osload_wait($1): child returned $2 status.\n";
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 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 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
	}
	else {
	    tberror "$self osload_wait: improper response from child: $_"; # INTERNAL
	}
    }

    $self->dprintts("osload_wait($childpid) finished");

    return $retval;
}

#
# 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 ($self, $pid, $eid, @nodelist) = @_;
    my %nodeinfo = ();
    my $allnodes;
    my $clause = "";

    if (!@nodelist) {
	@nodelist = ExpNodes($pid, $eid, 1, 0);
	$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
    $clause .= " and nt.class='pc' and nt.isremotenode=0";

    #
    # 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(
	"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 ".
	"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;
    }

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

	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();

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

	#
	# Weed out otherwise ineligible nodes:
	#	- from experiments that are not saving disk state
	#	- non-'node' role machines (i.e., delaynodes, virthosts)
	# 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.
	#
	if (!defined($savedisk) || $savedisk == 0 || $erole ne "node") {
	    delete $nodeinfo{$node};
	    next;
	}

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

	my $disk = "$dtype$dunit";
	$nodeinfo{$node} =
	    [$vname, $rpid, $reid, $disk, $part, $imagepid, $imagename, $lpart];
    }

    #
    # 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.
    #
    # Note that we actually copy the signature over as <imagename>.sig and
    # 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.
    #
    # 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).
    #
    my %gotsig = ();
    for my $node (keys(%nodeinfo)) {
	my $infop = $nodeinfo{$node};
	if ($infop == 0) {
	    print "*** swapinfo: WARNING: got no partition info for $node!\n";
	    next;
	}
	my ($vname, $rpid, $reid, $disk, $part, $imagepid, $imagename, $lpart) = @{$infop};

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

	# XXX backward compat
	my $infodir = "/$PROJROOT/$rpid/exp/$reid/swapinfo";
	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");

	#
	# 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;
	my ($sigdir, $signame);
	if ($imagepid eq TBOPSPID()) {
	    $sigdir = "$TB/images/sigs";
	} else {
	    $sigdir = "/$PROJROOT/$imagepid/images/sigs";
	}
	$signame = "$imagename.ndz.sig";
	$signame =~ s/^$imagepid-//;
	if (! -d $sigdir || ! -f "$sigdir/$signame") {
	    print "*** swapinfo: WARNING: ".
		"no image signature for $rimagename, ".
		"cannot save swapout state!\n";
	    next;
	}
	my $basesig = "$infodir/$rimagename.sig";
	if (! -r $basesig) {
	    $mustcopy = 1;
	} elsif (!defined($gotsig{$basesig})) {
David Johnson's avatar
David Johnson committed
1462 1463 1464 1465
	    my (undef,undef,undef,undef,undef,undef,undef,undef,
		undef,$fromtime,undef,undef,undef) = stat("$sigdir/$signame");
	    my (undef,undef,undef,undef,undef,undef,undef,undef,
		undef,$totime,undef,undef,undef) = stat($basesig);
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 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 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
	    if ($fromtime > $totime) {
		print "*** swapinfo: WARNING: ".
		    "$rimagename.sig out of date, updating...\n";
		$mustcopy = 1;
	    } elsif ($fromtime < $totime) {
		print "*** swapinfo: WARNING: ".
		    "$rimagename.sig newer than source $sigdir/$signame!\n";
	    }
	}
	if ($mustcopy) {
	    unlink($basesig);
	    if (system("/bin/cp -p $sigdir/$signame $basesig")) {
		print "*** swapinfo: WARNING: ".
		      "could not create signature $basesig, ".
		      "cannot save swapout state!\n";
		next;
	    }
	}
	$gotsig{$basesig} = 1;

	if (system("/bin/ln -s $rimagename.sig $infodir/$vname.sig")) {
	    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);
    }

    #
    # 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) {
	my $infodir = "/$PROJROOT/$pid/exp/$eid/swapinfo";
	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);
		}
	    }
	}
    }
}

sub SetupEventHandler($$)
{
    my ($self,$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;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;

    return 'libosload_new';
}


package libosload_common;
use base qw(libosload_new);

use libtestbed;
use libdb;
use libtblog;
use Node;
use Image;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

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

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

    $self->{'TYPE'}      = $type;
    $self->{'PARENT'}    = $parent;
    $self->{'IMAGES'}    = {};

    bless($self, $class);

    if (defined($parent)) {
	$self->debug($parent->debug());
    }

    return $self;
}

# Access methods for the objects defined below, which are 
sub type($)		{ return $_[0]->{'TYPE'}; }
sub parent($)		{ return $_[0]->{'PARENT'}; }
sub GetImages($$)       { return $_[0]->{'IMAGES'}{$_[1]->node_id()}; }

#
# If specific images were not specified, load the info for the default image
# setup the images list accordingly.
#
sub _LoadDefaultImages($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1620
    $self->dprint(3,"loading default images for $node_id");
1621 1622 1623

    my $default_imageid = $nodeobject->default_imageid();
    if (!defined($default_imageid)) {
1624
	tberror("$node_id: No default imageid defined!");
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
	return -1;
    }
    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!");
	    return -1;
	}
	push @default_images, $default_image;
    }
    # XXX -- should do elsewhere?  Seems wrong.
    $self->nodeflag($nodeobject,'prepare',1);

    $self->{'IMAGES'}->{$node_id} = \@default_images;

    return 0;
}

sub _LoadCurrentImages($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1650
    $self->dprint(3,"loading current images for $node_id");
1651 1652 1653 1654 1655 1656 1657 1658 1659

    my $def_boot_osid  = $nodeobject->def_boot_osid();
    my $osinfo = OSinfo->Lookup($def_boot_osid);
    if (! defined($osinfo)) {
	tberror("Could not find OS $def_boot_osid in the DB!");
	return undef;
    }
    my $best_image = $osinfo->MapToImage($nodeobject->type());
    if (!defined($best_image)) {
1660
	tberror("Could not map $osinfo to an image for $node_id!");
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
	return undef;
    }

    $self->{'IMAGES'}->{$node_id} = [ $best_image ];

    return 0;
}

#
# First load any node type attributes of form 'osload_*'.  Then, load any
# node attributes of form 'osload_*'.
#
sub _LoadAttributeArgs($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

    my $attrhashref = $nodeobject->GetNodeTypeAttributes();
    foreach my $k (keys(%{$attrhashref})) {
	if ($k =~ /^osload_.*$/) {
	    $self->nodeinfo($nodeobject,$k,$attrhashref->{$k}->{"value"});
	}
    }

    $attrhashref = $nodeobject->GetNodeAttributes();
    foreach my $k (keys(%{$attrhashref})) {
	if ($k =~ /^osload_.*$/) {
	    $self->nodeinfo($nodeobject,$k,$attrhashref->{$k});
	}
    }

    return 0;
}

#
# Add a node to the list.  This should almost never be overridden; it pretty
# much does generic testbed operations.
#
sub AddNode($$$$)
{
    my ($self, $nodeobject, $imagelist, $args) = @_;
    my $node_id = $nodeobject->node_id();

    if (!defined($args)) {
	$args = {};
    }

1708
    $self->dprint(0,"AddNode($node_id)");
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727

    $self->{'NODES'}->{$node_id}    = $nodeobject;
    $self->{'NODEFLAGS'}->{$node_id}    = $args;
    $self->{'IMAGES'}->{$node_id}   = $imagelist;

    if ($self->_LoadAttributeArgs($nodeobject)) {
	return -1;
    }

    my $imagelistref = $self->GetImages($nodeobject);

    if (!defined($imagelistref) || scalar(@$imagelistref) == 0) {
	if ($self->_LoadDefaultImages($nodeobject)) {
	    return -1;
	}
    }

    if ($self->nodeflag($nodeobject,'usecurrent')) {
	if (defined($imagelistref) && scalar(@$imagelistref)) {
1728
	    tbwarn("$self AddNode($node_id): we were given $imagelist, but are " . 
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
		   " going to use the current OS instead!");
	}

	if ($self->_LoadCurrentImages($nodeobject)) {
	    return -1;
	}
    }

    if ($self->_CheckImages($nodeobject)) {
	return -1;
    }

    return 0;
}

sub _CheckImages($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1749
    $self->dprint(0,"_CheckImages($node_id)");
1750 1751 1752 1753 1754 1755 1756 1757 1758

    my @images = @{$self->GetImages($nodeobject)};
    my @imageids = map { $_->imageid() } @images;
    my @imageidxs = (0 .. $#imageids);

    foreach my $i (@imageidxs) {
	my $imageid = $imageids[$i];
	my $image = $images[$i];

1759
	$self->dprint(1,"_CheckImages($node_id): using $image");
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779

	#
	# 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.
	# 
	my $rowref = $self->imageinfo($imageid);
	if (!defined($rowref)) {
	    my $retval = $self->GetImageInfo($image,\$rowref);
	    # save it off!
	    $self->imageinfo($imageid,$rowref);
	    if ($retval) {
		return -1;
	    }
	}
	if ($rowref eq 'BADIMAGE') {
	    return -1;
	}

1780
	$self->dprint(2,"_CheckImages($node_id): imageinfo for $imageid: " . Dumper($rowref));
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
    }

    return 0;
}

sub SetBootOS($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1791
    $self->dprint(0,"SetBootOS($node_id): setting boot os");
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804

    my @images = @{$self->GetImages($nodeobject)};
    #
    # When loading multiple images, use the osinfo from the
    # last image
    #
    my $image = $images[-1];
    my $imageid = $image->imageid();
    my $rowref = $self->imageinfo($imageid);

    my $defosid = $rowref->{'default_osid'};
    my $osinfo = OSinfo->Lookup($defosid);
    if (!defined($osinfo)) {
1805
	tberror("$self SetBootOS($node_id): could not map OSID $defosid to its object!");
1806 1807 1808
	return -1;
    }

1809
    print "$self SetBootOS($node_id): changing default OS to $osinfo\n";
1810
    if (!$TESTMODE) {
1811
	if ($nodeobject->OSSelect($osinfo,"def_boot_osid",$self->debug())) {
1812
	    tberror "$self SetBootOS($node_id): os_select $defosid failed!";
1813 1814 1815 1816 1817 1818 1819
	    return -1;
	}
    }

    return 0;
}

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
#
# Save the current osid, def_boot_osid, and partitions info for this node.
# This is not useful to most nodes, but for nodes where we *know* the reboot
# has failed (and for which we don't want to lie about which OS is actually
# on the node *because* we don't always force a reload if we think we know
# what OS is on "disk" -- like for switches!), we can do a reset if we save
# the old info.
#
# Note that none of this is called by default -- subclasses must manually
# invoke if they need it!
#
sub SaveNodeDiskInfo($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1836
    $self->dprint(0,"SaveNodeDiskInfo($node_id): saving partition and osid");
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870

    #
    # Save the old ones off first!
    #
    my $dbres;
    $dbres = DBQueryFatal("select node_id,partition,osid,imageid,imagepid" . 
			  " from partitions where node_id='$node_id'");
    if (defined($dbres) && $dbres->numrows()) {
	my @rows = ();
	while (my $rowref = $dbres->fetchrow_hashref()) {
	    push @rows,$rowref;
	}
	$self->nodeinfo($nodeobject,'old_partitions',\@rows);
    }

    $dbres = DBQueryFatal("select osid,def_boot_osid" . 
			  " from nodes where node_id='$node_id'");
    if (defined($dbres) && $dbres->numrows()) {
	my $rowref = $dbres->fetchrow_hashref();
	$self->nodeinfo($nodeobject,'old_osid',$rowref->{'osid'});
	$self->nodeinfo($nodeobject,'old_def_boot_osid',
			$rowref->{'def_boot_osid'});
    }
    return 0;
}

#
# Restore osid and partitions info if we saved it off!
#
sub RestoreNodeDiskInfo($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1871
    $self->dprint(0,"RestoreNodeDiskInfo($node_id): restoring partition and osid");
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898

    my $partref = $self->nodeinfo($nodeobject,'old_partitions');
    if (defined($partref) && @$partref) {
	DBQueryFatal("delete from partitions where node_id='$node_id'");

	foreach my $rowref (@$partref) {
	    my ($part,$osid,$imageid,$imagepid) = 
		( $rowref->{'partition'},$rowref->{'osid'},
		  $rowref->{'imageid'},$rowref->{'imagepid'} );
	    DBQueryFatal("insert into partitions " . 
			 " (node_id,partition,osid,imageid,imagepid)" . 
			 " values" . 
			 " ('$node_id','$part','$osid','$imageid','$imagepid')");
	}
    }

    my $osid = $self->nodeinfo($nodeobject,'old_osid');
    my $def_boot_osid = $self->nodeinfo($nodeobject,'old_def_boot_osid');
    if (defined($osid) && defined($def_boot_osid)) {
	DBQueryFatal("update nodes set osid='$osid'," . 
		     "                 def_boot_osid='$def_boot_osid'" . 
		     " where node_id='$node_id'");
    }

    return 0;
}

1899 1900 1901 1902 1903
sub UpdatePartitions($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

1904
    $self->dprint(0,"UpdatePartitions($node_id): starting");
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976

    my @images = @{$self->GetImages($nodeobject)};
    my @imageids = map { $_->imageid() } @images;
    my @imageidxs = (0 .. $#imageids);

    my $prepare = $self->nodeflag($nodeobject,'prepare');

    foreach my $i (@imageidxs) {
	my $imageid = $imageids[$i];
	my $image = $images[$i];

	my $rowref = $self->imageinfo($imageid);
	my $loadpart   = $rowref->{'loadpart'};
	my $loadlen    = $rowref->{'loadlength'};
	my $imagepath  = $rowref->{'path'};
	my $imagepid   = $rowref->{'pid'};

	#
	# XXX assumes a DOS MBR, but this is ingrained in the DB schema
	# as well (i.e., the images.part[1234]_osid fields).
	#
	my $MINPART = 1;
	my $MAXPART = 4;

	#
	# Assign partition table entries for each partition in the image
	# that has an OSID associated with it.
	#
	# 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
	# in which case we must invalidate all partitions except the ones
	# we are loading since the partition boundaries may have changed...
	#
	# ...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
	# experiments.  In this case we need to invalidate all but the
	# partition(s) we are loading 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.
	#
	my $startpart = $loadpart == 0 ? $MINPART : $loadpart;
	my $endpart   = $startpart + $loadlen;

	for (my $i = $MINPART; $i <= $MAXPART; $i++) {
	    my $partname = "part${i}_osid";
	    my $dbresult;
		
	    #
	    # Partition is outside the range affected by this image.
	    # Normally, we just leave it alone, except for the special
	    # cases above.
	    #
	    if ($i < $startpart || $i >= $endpart) {
		my $whackit = 0;

		if ($prepare) {
		    $whackit = 1;
		} elsif (defined($rowref->{'mbr_version'})) {
		    $dbresult =
			DBQueryWarn("select mbr_version ".
				    " from partitions as p,images as i ".
				    " where p.imageid=i.imageid ".
				    " and node_id='$node_id' and partition='$i'");
		    if ($dbresult && $dbresult->numrows) {
			my ($pmbr) = $dbresult->fetchrow_array();
			if ($pmbr != $rowref->{'mbr_version'}) {
			    # XXX: Is this right in the context of multiple images
1977
			    tbinfo("$node_id: Existing partition $i inconsistent".
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
				   " with new image partitioning,".
				   " invalidating existing partition");
			    $whackit = 1;
			}
		    }
		}
		if ($whackit) {
		    $dbresult =
			DBQueryWarn("delete from partitions ".
				    "where node_id='$node_id' and ".
				    "partition='$i'");
		    if (!$dbresult) {
1990
			tberror("$node_id: Could not update partition table");
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
			return -1;
		    }
		}
		next;
	    }
		
	    #
	    # This image has an OSID in the current partition,
	    # replace the partition table info.
	    #
	    if (defined($rowref->{$partname})) {
		my $osid = $rowref->{$partname};
		
		$dbresult =
		    DBQueryWarn("replace into partitions ".
				"(node_id,partition,osid,imageid,imagepid) ".
				"values ".
				"('$node_id','$i','$osid','$imageid','$imagepid')");
	    }
	    #
	    # Otherwise, if there is no OS for a particular image partition,
	    # clear any current partitions table info.
	    #
	    else {
		$dbresult =
		    DBQueryWarn("delete from partitions ".
				"where node_id='$node_id' and partition='$i'");
	    }
	    if (!$dbresult) {
2020
		tberror "$node_id: Could not update partition table";
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
		return -1;
	    }
	}
    }

    return 0;
}

sub RemoveNode($$)
{
    my ($self, $nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

2034
    $self->dprint(0,"RemoveNode($node_id)");
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069

    $self->{'NODES'}->{$node_id}    = undef;
    $self->{'ARGS'}->{$node_id}     = undef;
    $self->{'IMAGES'}->{$node_id}   = undef;

    return 0;
}

#
# Compute the time to load all images on this node.
#
sub ComputeMaxLoadWaitTime($$)
{
    my ($self,$nodeobject) = @_;

    my $maxwait = 0;

    my @images = @{$self->GetImages($nodeobject)};
    foreach my $image (@images) {
	my $imageid = $image->imageid();
	#
	# 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.
	#
	my $rowref = $self->imageinfo($imageid);

	my $chunks = $rowref->{size} >> 20; # size may be > 2^31, shift is unsigned

	# XXX aren't we multi-counting reboots??
	# ok, moved constant factor out.
	$maxwait += int(($chunks / 100.0) * 65);
    }

2070
    return $maxwait + $TBLOADWAIT;
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
}

sub PreSetupReload($$)
{
    my ($self,$nodeobject) = @_;

    if ($self->SetBootOS($nodeobject)) {
	return -1;
    }
    
    if ($self->UpdatePartitions($nodeobject)) {
	return -1;
    }

    #
    # Setup swapinfo now after partitions have initialized but before
    # we setup the one-shot frisbee load.
    #
    if ($self->nodeflag($nodeobject,'swapinfo')) {
	if ($self->SetupSwapInfo(undef,undef,$nodeobject)) {
	    return -1;
	}
    }

    return 0;
}

#
# These must be overridden by subclasses!
#
sub SetupReload($$) 
{
    return -1;
}

# This cannot block!
sub WaitForNode($$)
{
    my ($self,$nodeobject) = @_;
2110
    my $node_id = $nodeobject->node_id();
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128

    my $retval = 0;

    my $childpid = $self->nodeinfo($nodeobject,'reloadchildpid');
    if (defined($childpid)) {
	# if it's no longer there, reap it!
	#
	# we don't use waitpid with -WNOHANG because ChildReap already
	# does this for us... but XXX because this could cause a block
	# if we've coded a bug ;).
	$retval = kill(0,$childpid);

	if ($retval != 0) {
	    my ($data,$rc,@output) = $self->ChildReap($childpid);
	    # make room for another reload on this node!
	    $self->nodeinfo_unset($nodeobject,'reloadchildpid');
	    # caller should know that the node is done, with the following
	    # status
2129
	    $self->dprint(2,"WaitForNode($node_id): $childpid is done with $rc");
2130 2131 2132 2133
	    return (1,$rc,@output);
	}
	else {
	    # caller should still wait for it!
2134
	    $self->dprint(2,"WaitForNode($node_id): $childpid is stil working");
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
	    return (0,);
	}
    }

    # if this node doesn't have a child pid, tell callers not to wait
    # for it!
    return (-1,);
}

#
# These can be overridden by subclasses.
#
sub Reload()
{
    return 0;
}

sub ReloadDone($$)
{
    my ($self,$nodeobject) = @_;
    return $self->RemoveNode($nodeobject);
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $type = $self->type();

    return 'libosload_' . $type . '';
}

package libosload_pc;
use base qw(libosload_common);

use libtestbed;
use libdb;
use libtblog;
use Node;
use Image;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

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

    my $self = $class->SUPER::New($parent,defined($type)?$type:"pc");
    bless($self, $class);

    return $self;
}

sub SetupReload($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();
2196
    my $osinfo;
2197

2198
    $self->dprint(0,"SetupReload($node_id): setting up reload");
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216

    my @images = @{$self->GetImages($nodeobject)};
    my @imageids = map { $_->imageid() } @images;
    my @imageidxs = (0 .. $#imageids);

    my $prepare = $self->nodeflag($nodeobject,'prepare');
    my $zerofree = $self->nodeflag($nodeobject,'zerofree');
    my $osid = TBNodeDiskloadOSID($node_id);

    #
    # Put it in the current_reloads table so that nodes can find out which
    # OS to load. See tmcd. 
    #
    my $query_result = 
	DBQueryWarn("delete from current_reloads where node_id = '$node_id'");
    return -1
	if (!$query_result);

2217 2218 2219
    # XXX windows load
    my $needswinpe = 0;

2220 2221 2222
    my $idx = 1;
    foreach my $imageid (@imageids) {
	my $prepare0 = $idx == 1 && $prepare ? 1 : 0;
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234

	# XXX windows load
	my $rowref = $self->imageinfo($imageid);
	if (!defined($rowref)) {
	    tberror "$self: Mike make a bad assumption!";
	    return -1;
	}
	my $format = $rowref->{'format'};
	if (defined($format) && $format eq "wim") {
	    $needswinpe++;
	}

2235 2236 2237 2238 2239 2240 2241 2242 2243
	my $query_result = 
	    DBQueryWarn("insert into current_reloads ".
			"(node_id, idx, image_id, mustwipe, prepare) values ".
			"('$node_id', $idx, '$imageid', $zerofree, $prepare0)");
	return -1
	    if (!$query_result);
	++$idx;
    }

2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
    # XXX windows load
    if ($needswinpe) {
	if (@imageids > 1) {
	    tberror("$self: Cannot load more than one image with WinPE/ImageX");
	    return -1;
	}
	# Look up the magic osid for the imageX loader
	$osinfo = OSinfo->Lookup(TB_OPSPID, $IMAGEX_OSNAME);
    }
    else {
	$osinfo = OSinfo->Lookup($osid);
    }

2257
    if ($nodeobject->OSSelect($osinfo,"next_boot_osid",$self->debug())) {
2258 2259 2260 2261
	tberror "$self: os_select $osid failed!";
	return -1;
    }

2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
    # XXX windows load
    # whether windows or not, we always make sure this is set correctly
    my $changed = 0;
    my $path = $needswinpe ? $IMAGEX_PXEPATH : "";
    if ($nodeobject->PXESelect($path, "next_pxe_boot_path",
			       $self->debug(), \$changed)) {
	tberror "$self: pxe_select $path failed!";
	return -1;
    }
    if ($changed && system("$MAKECONF -i -r")) {
	tberror "$self: restart DHCPD failed!";
	return -1;
    }

2276 2277 2278
    return 0;
}

David Johnson's avatar
David Johnson committed
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
package libosload_pcRemote;
use base qw(libosload_pc);

use libdb;
use libtestbed;
use libossetup;
use libtblog;
use Node;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318

package libosload_virtnode;
use base qw(libosload_pc);

use libtestbed;
use libdb;
use libtblog;
use Node;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

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

    my $self = $class->SUPER::New($parent,defined($type)?$type:"pcvm");
    bless($self, $class);

    return $self;
}

# 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.
sub _LoadDefaultImages($$)
{
    return 0;
}
2319 2320 2321 2322 2323 2324 2325
#
# But we *do* want the user to be able to simply reload the current OS.
#
#sub _LoadCurrentImages($$) 
#{
#    return 0;
#}
2326 2327 2328 2329 2330 2331

sub SetupReload($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

2332
    $self->dprint(0,"SetupReload($node_id): setting up reload");
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441

    if ($self->SUPER::SetupReload($nodeobject)) {
	return -1;
    }

    # Need to kick virtnodes so stated picks up the next_op_mode from os_select
    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);

    return 0;
}

#
# Compute the time to load all images on this node.
#
sub ComputeMaxLoadWaitTime($$)
{
    my ($self,$nodeobject) = @_;

    my $maxwait = $self->SUPER::ComputeMaxLoadWaitTime($nodeobject);

    #
    # 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 (!$nodeobject->_onsharednode()) {
	$maxwait += 8 * 60;
    }

    return $maxwait;
}

package libosload_mote;
use base qw(libosload_common);

use libtestbed;
use libdb;
use libtblog;
use Node;
use Image;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

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

    my $self = $class->SUPER::New($parent,defined($type)?$type:"mote");
    bless($self, $class);

    return $self;
}

sub AddNode($$$$) 
{
    my ($self, $nodeobject, $imagelist, $args) = @_;
    my $node_id = $nodeobject->node_id();

    # Motes don't support these flags, so clear them so libosload doesn't
    # try to do anything with them!
    if (defined($self->nodeflag($nodeobject,'reboot'))) {
	$self->nodeflag($nodeobject,'reboot',0);
    }

    return $self->SUPER::AddNode($nodeobject, $imagelist, $args);
}

#
# XXX: untested after port to new libosload!
#
sub SetupReload($$)
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

    my @images = @{$self->GetImages($nodeobject)};

    if (@images > 1) {
	tbwarn "$self ($node_id): motes can load only one image; using first!";
    }

    my $imageid = $images[0]->imageid();
    my $rowref = $self->imageinfo($imageid);
    my $osid = $rowref->{'default_osid'};

    #
    # Get the path to the image
    #
    my $path = $rowref->{'path'};

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

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

sub Reload($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

    if (defined($self->nodeinfo($nodeobject,'reloadchildpid'))) {
2442
	tberror "$self Reload($node_id): there is already a reload in progress?\n";
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
	return -1;
    }

    #
    # Reload can't block, so fork and make a note of ourself!
    #
    my $childpid = $self->ChildCreate([]);
    if ($childpid) {
	# parent:
	$self->nodeinfo($nodeobject,'reloadchildpid',$childpid);
	return 0;
    }

    # child continues:

    my @images = @{$self->GetImages($nodeobject)};
    my $imageid = $images[0]->imageid();
    my $rowref = $self->imageinfo($imageid);
    my $osid = $rowref->{'default_osid'};

    #
    # Get the path to the image
    #
    my $path = $rowref->{'path'};

    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);

    #
    # Okay, just run tbuisp with that path
    #
    my $rv = system("$TBUISP upload $path $node_id");
    if ($rv) {
2475
	tberror "$self Reload($node_id): tbuisp failed";
2476 2477 2478 2479 2480 2481 2482 2483
	return -1;
    }

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

2484 2485 2486

    my $osinfo = OSinfo->Lookup($osid);
    if ($nodeobject->OSSelect($osinfo,"def_boot_osid",$self->debug())) {
2487
	tberror "$self Reload($node_id): os_select $osid failed!";
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
	return -1;
    }

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

    return 0;
}

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