libossetup.pm.in 62 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2019 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
#
package libossetup;

use strict;
use Exporter;
28 29 30
use vars qw(@EXPORT $AUTOLOAD
	    $NOSTATE $RELOAD $RECONFIG $REBOOT
	    $RELOAD_FAILED $RECONFIG_FAILED $REBOOT_FAILED $SETUP_FAILED
31
	    $SETUP_OKAY $SETUP_CANCELED);
32
use base qw( Exporter );
33

34 35 36
@EXPORT = qw(&die_noretry
	     $NOSTATE $RELOAD $RECONFIG $REBOOT
	     $RELOAD_FAILED $RECONFIG_FAILED $REBOOT_FAILED $SETUP_FAILED
37
	     $SETUP_OKAY $SETUP_CANCELED);
38 39 40 41 42

use libdb;
use libtestbed;
use libreboot;
use libosload;
43
use OSImage;
44
use Node;
45
use NodeType;
46
use libtblog_simple;
47
use Logfile;
48 49
use English;
use Data::Dumper;
50
use EmulabFeatures;
51 52 53 54 55

# Configure variables
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $NODEREBOOT  = "$TB/bin/node_reboot";
56
my $POWER       = "$TB/bin/power";
Leigh Stoller's avatar
Leigh Stoller committed
57
my $VNODESETUP  = "$TB/sbin/vnode_setup";
58
my $ELABINELAB  = "$TB/sbin/elabinelab";
59
my $TBADB       = "$TB/bin/tbadb";
60

61
# Setup Operation Flags
Leigh Stoller's avatar
Leigh Stoller committed
62
$NOSTATE    = 0x00;
63
$RELOAD     = 0x01;
64 65 66
$RECONFIG   = 0x02;
$REBOOT     = 0x04;

67 68 69 70 71 72
# Setup Result Flags
$SETUP_OKAY      = 0x00;
$RELOAD_FAILED   = 0x01;
$RECONFIG_FAILED = 0x02;
$REBOOT_FAILED   = 0x04;
$SETUP_FAILED    = 0x08;
73
$SETUP_CANCELED  = 0x10;
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
#
# Used to die with a -1 return code, to indicate to caller (tbswap)
# that the failure is not likely to be fixed with another attempt.
#
sub die_noretry($;$)
{
    my $parms = {};
    $parms = shift if ref $_[0] eq 'HASH';
    my ($mesg) = shift;
    tberror($parms, $mesg);
    exit(-1);
}

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

    my $self              = {};
    $self->{'USER'}       = $user;
    $self->{'EXPT'}       = $experiment;
Leigh Stoller's avatar
Leigh Stoller committed
99 100
    $self->{'GROUP'}      = (defined($experiment) ?
			     $experiment->GetGroup() : undef);
101 102
    $self->{'HASH'}       = {};
    $self->{'NODES'}      = {};
Leigh Stoller's avatar
Leigh Stoller committed
103
    $self->{'PHYSNODES'}  = {};
104
    $self->{'FAILED'}     = {};
105
    $self->{'FAILCOUNT'}  = 0;
106 107
    $self->{'OSMAP'}      = {};
    $self->{'TYPECACHE'}  = {};
Leigh Stoller's avatar
Leigh Stoller committed
108
    $self->{'OPLIST'}     = {};
109 110 111 112 113 114 115 116

    # For informing users of failed nodes.
    $self->{'INFORM_USER'}       = {};
    $self->{'INFORM_TBOPSWARN'}  = {};
    $self->{'INFORM_TBOPSFATAL'} = {};

    foreach my $node (@nodelist) {
	$self->{'NODES'}->{$node->node_id()} = $node;
Leigh Stoller's avatar
Leigh Stoller committed
117 118 119

	# Init some per-node stuff.
	$node->_rebooted(0);
120
	$node->_vnodecount(0);
121
	$node->_reloaded(0);
Leigh Stoller's avatar
Leigh Stoller committed
122
	$node->_bootlog(undef);
123 124 125 126 127
    }

    bless($self, $class);
    # XXX
    $self->noretry(0);
Leigh Stoller's avatar
Leigh Stoller committed
128
    $self->canceled(0);
129
    $self->aborted(0);
130
    $self->realreboot(0);
131 132 133 134 135 136 137 138

    if (EmulabFeatures->FeatureEnabled("NewOsload",$user,
				       $self->{'GROUP'},$experiment)) {
	require libosload_new;
	# XXX -- @nodelist
	$self->loadobj(libosload_new->New());
    }

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    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 virtnodes($)        { return $_[0]->{'VIRTNODES'}; }
sub physnodes($)        { return $_[0]->{'PHYSNODES'}; }
sub geninodes($)        { return $_[0]->{'GENINODES'}; }
sub sharednodes($)      { return $_[0]->{'SHAREDNODES'}; }
Leigh Stoller's avatar
Leigh Stoller committed
155
sub oplist($)		{ return $_[0]->{'OPLIST'}; }
156 157
sub user($)		{ return $_[0]->{'USER'}; }
sub experiment($)	{ return $_[0]->{'EXPT'}; }
158
sub group($)		{ return $_[0]->{'GROUP'}; }
Leigh Stoller's avatar
Leigh Stoller committed
159
sub IncrFailCount($)    { $_[0]->{'FAILCOUNT'}++ }
160
sub failed($)           { return $_[0]->{'FAILCOUNT'}; }
161 162 163 164 165 166

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

Leigh Stoller's avatar
Leigh Stoller committed
167 168 169 170 171 172 173
    if (exists($self->{'NODES'}->{$node_id})) {
	return $self->{'NODES'}->{$node_id};
    }
    # Phys nodes are nodes we do not actually own; they are shared
    if (exists($self->{'PHYSNODES'}->{$node_id})) {
	return $self->{'PHYSNODES'}->{$node_id};
    }
174 175 176 177 178 179
    return undef
}

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

182 183
    if (defined($osimage)) {
	return $self->{'OSMAP'}->{$osid} = $osimage;
184 185 186 187 188 189 190
    }
    elsif (exists($self->{'OSMAP'}->{$osid})) {
	return $self->{'OSMAP'}->{$osid};
    }
    return undef;
}

191
# To avoid writing out all the methods.
192 193
sub AUTOLOAD {
    my $self = shift;
194
    my $type = ref($self) or die("$self is not an object");
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    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 "$self: tried to access unknown slot $name\n";
    return undef;
}

#
#
Leigh Stoller's avatar
Leigh Stoller committed
211
sub OperationList($)
212 213 214 215 216 217 218 219 220 221
{
    my ($self) = @_;
    
    return [ values(%{ $self->{'TYPECACHE'} }) ];
}

#
# Setup a reload of a node if we can find an image.
# This goo constructs a hashed array of lists.
#
222
sub SetupReload($$$$)
223
{
224
    my ($self, $node, $osimage, $auxload) = @_;
225 226 227 228 229 230 231 232 233 234 235 236 237 238
    my $type = $node->type();

    #
    # We use a special type, "pcvm", for *any* subOS that can boot on a vnode.
    # For now, we're not going to mess with vnode types -- type checking is 
    # pretty pointless for this, since what we really want to check for a subOS
    # is whether it can boot on a specific parentOS.
    # So, users who make subOSes have to select that they can boot on type
    # pcvm and that's all that's necessary.
    #
    if ($node->isvirtnode()) {
	$type = "pcvm";
    }

239
    if ((my $image = $osimage->MapToImage($type))) {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	#
	# We support aux image loading, but have to distingush between a boot
	# load and an aux load, since an aux load should not change what is
	# actually booted.
	#
	if ($auxload) {
	    if (!defined($node->_loadimages())) {
		$node->_loadimages([]);
	    }
	    my @list = @{ $node->_loadimages() };
	    push(@list, $image);
	    $node->_loadimages(\@list);
	}
	else {
	    $node->_loadimages(undef);
	    $node->_loadimage($image);
	}
Leigh Stoller's avatar
Leigh Stoller committed
257
	$node->_setupoperation($RELOAD);
258
	$node->_reloaded(1);
259 260 261
	if ($self->debug()) {
	    print STDERR "SetupReload: $node:$image auxload:$auxload\n";
	}
262 263 264
    }
    else {
	die_noretry({type => 'primary', severity => SEV_ERROR,
265 266
		     error => ['file_not_found', 'image', $osimage, $node]},
		    "No image can be found for $osimage on $node ($type)!");
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    }
}

#
# keep track of the failed nodes of all types.
#   values = ['boot'|'osload', 'fatal'|'nonfatal']
#
sub add_failed_node_fatal($$) {
    $_[0]->{'FAILED'}->{$_[1]} = ['boot', 'fatal'];
}
sub add_failed_node_nonfatal($$) {
    $_[0]->{'FAILED'}->{$_[1]} = ['boot', 'nonfatal'];
}
sub add_failed_node_reload($$) {
    $_[0]->{'FAILED'}->{$_[1]} = ['reload', 'fatal'];
}
#
# Add node to lists for email messages.
#
sub add_failed_node_inform_user($$) {
    $_[0]->{'INFORM_USER'}->{$_[1]} = $_[1];
}
sub add_failed_node_inform_tbopswarn($$) {
    $_[0]->{'INFORM_TBOPSWARN'}->{$_[1]} = $_[1];
}
sub add_failed_node_inform_tbopsfatal($$) {
    $_[0]->{'INFORM_TBOPSFATAL'}->{$_[1]} = $_[1];
}
sub ClearInformLists($)
{
    $_[0]->{'INFORM_USER'}       = {};
    $_[0]->{'INFORM_TBOPSWARN'}  = {};
    $_[0]->{'INFORM_TBOPSFATAL'} = {};
}

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
#
# Collect up log files and create a list of urls.
#
sub CollectBootLogFiles($@)
{
    my ($self, @node_ids) = @_;
    my $logmsg = "";

    foreach my $node_id (@node_ids) {
	my $node = $self->node($node_id);
	next
	    if (!defined($node) || !defined($node->_bootlog()));

	$logmsg .= sprintf("%-15s : %s\n",
			   $node->node_id(), $node->_bootlog()->URL());
    }
    return $logmsg;
}

321 322 323 324 325 326 327 328 329 330 331 332
#
# Spam time! Send mail to the user and testbed-ops about failures.
#
sub InformUser($)
{
    my ($self) = @_;
    my $pid    = $self->experiment()->pid();
    my $eid    = $self->experiment()->eid();
    my $name   = $self->user()->name();
    my $email  = $self->user()->email();

    my @nodelist = keys(%{ $self->{'INFORM_USER'} });
333
    my $logmsg   = $self->CollectBootLogFiles(@nodelist);
334 335 336 337 338 339 340 341 342 343 344 345
    my $count    = scalar(@nodelist);
    if ($count > 0) {
	SENDMAIL("$name <$email>", "$count nodes are down",
		 "Nodes:\n".
		 "  " . join(" ", @nodelist) . "\n".
		 "in pid/eid $pid/$eid appear to be dead.\n\n".
		 "Your experiment will continue to run since these failures\n".
		 "are nonfatal, although you might encounter other problems\n".
		 "if your experiment depends explicitly on these nodes.\n".
		 "You should terminate this experiment if it cannot ".
		 "tolerate these failures.\n\n".
		 "Testbed Operations has also been notified.\n\n".
346 347
		 "$logmsg\n",
		 undef,
348 349 350 351 352 353 354 355 356 357 358 359 360
		 "Cc: $TBOPS");
    }
}

sub InformTBopsFatal($)
{
    my ($self) = @_;
    my $pid    = $self->experiment()->pid();
    my $eid    = $self->experiment()->eid();
    my $name   = $self->user()->name();
    my $email  = $self->user()->email();

    my @nodelist = keys(%{ $self->{'INFORM_TBOPSFATAL'} });
361
    my $logmsg   = $self->CollectBootLogFiles(@nodelist);
362 363 364 365 366 367
    my $count    = scalar(@nodelist);
    if ($count > 0) {
	SENDMAIL($TBOPS, "$count nodes are down",
		 "Nodes:\n".
		 "  " . join(" ", @nodelist) . "\n".
		 "in pid/eid $pid/$eid appear to be dead.\n\n".
368
		 "The nodes have been moved into hardware checkup.\n\n$logmsg",
369 370 371 372 373 374 375 376 377 378 379 380 381
		 "$name <$email>");
    }
}

sub InformTBopsWarn($)
{
    my ($self) = @_;
    my $pid    = $self->experiment()->pid();
    my $eid    = $self->experiment()->eid();
    my $name   = $self->user()->name();
    my $email  = $self->user()->email();

    my @nodelist = keys(%{ $self->{'INFORM_TBOPSWARN'} });
382
    my $logmsg   = $self->CollectBootLogFiles(@nodelist);
383 384 385 386 387 388
    my $count    = scalar(@nodelist);
    if ($count > 0) {
	SENDMAIL($TBOPS, "$count nodes are down",
		 "Nodes:\n".
		 "  " . join(" ", @nodelist) . "\n".
		 "in pid/eid $pid/$eid failed to boot after loading OS.\n\n".
389
		 "The nodes have been freed.\n\n$logmsg",
390 391 392 393 394 395 396 397 398 399 400 401 402
		 "$name <$email>");
    }
}

#
# Set the OS that needs to boot on a node, and mark it.
#
sub SetOS($$)
{
    my ($self, $node) = @_;
    my $node_id       = $node->node_id();
    my $imageable     = $node->imageable();
    my $osid          = $node->def_boot_osid();
403
    my $osid_vers     = $node->def_boot_osid_vers();
404
    my $osimage       = OSImage->Lookup($osid, $osid_vers);
405
    my $loadlist      = $node->loadlist();
406 407 408 409
    my $experiment    = $self->experiment();
    my $pid           = $experiment->pid();

    die_noretry("Could not map $osid to its object!")
410
	if (!defined($osimage));
411

412 413
    # Lets remember the osimage for later.
    $self->osmap($osid, $osimage);
414 415 416 417 418 419 420 421 422

    # Set the canfail bit.
    $node->_canfail($node->failureaction() eq NODEFAILMODE_FATAL() ? 0 : 1);

    #
    # If a virtnode is running a subOS, we set $imageable because it
    # really is going to be reloaded... even though virtnode types are
    # not typically imageable.
    #
423
    if ($node->isvirtnode() && $osimage->def_parentosid()) {
424 425
	#
	# But, if the subos is static (like OPENVZ-STD), there is
426 427 428 429 430 431
	# no reload, cause it is already on the parent image. But this
	# is currently difficult to determine, which is something that
	# needs to be fixed.
	#
	# So instead, just watch for an image we can map to, and if
	# nothing is returned, just move on. 
432 433
	#
	$imageable = 1
434
	    if (defined($osimage->MapToImage($node->type())));
435 436
    }

437
    if ($imageable) {
438 439 440 441
	#
	# These checks are not necessary if the front end and web page
	# are doing the right thing, but lets be careful anyway.
	#
442
	if (! $osimage) {
443 444
	    die_noretry("$node has no bootpath and no def_boot_osid set!");
	}
445
	$self->SetOSAux($node, $osimage, 0, $loadlist);
446

447
	#
448
	# Now look for additional loads. 
449
	#
450 451 452 453
	if ($loadlist) {
	    my @osnamelist = split(",", $loadlist);

	    foreach my $osname (@osnamelist) {
454 455
		my $osimage = OSImage->Lookup($pid, $osname) ||
		    OSImage->LookupByName($osname);
456 457

		die_noretry("Could not map $osname to its object!")
458
		    if (!defined($osimage));
459

460
		$self->SetOSAux($node, $osimage, 1, 1);
461 462 463 464
	    }
	}
    }
    # Remember this for later. 
465
    $node->_bootosinfo($osimage);
466
    
467
    print STDERR "$node_id - $osimage\n"
468 469 470 471 472 473
	if ($self->debug());
}

#
# Helper for above.
#
474
sub SetOSAux($$$$$)
475
{
476
    my ($self, $node, $osinfo, $auxload, $multiple) = @_;
477 478 479 480 481
    my $node_id       = $node->node_id();
    my $experiment    = $self->experiment();
    my $pid           = $experiment->pid();
    
    #
482
    # No more oskit kernels, just MFSs.
483
    #
484
    if (! $osinfo->mfs()) {
485
	my $nextosinfo;
486
	    
487 488 489 490
	#
	# Not an OSKit kernel.
	#
	if ($osinfo->IsGeneric()) {
491
	    #
492
	    # Map generic OSID to the specific one.
493
	    #
494 495 496
	    $nextosinfo = $osinfo->ResolveNextOSID($experiment);
	    if (!defined($nextosinfo)) {
		die_noretry("No next mapping for $osinfo on $node!\n");
497
	    }
498 499 500 501
	    print "Mapping $osinfo on $node_id to $nextosinfo\n";
	    $osinfo = $nextosinfo;
	}
	#
502 503 504 505 506 507
	# Have the node inherit any taint states set for the OS. This
	# call retains any taint states the node had set previously.
	#
	$node->InheritTaintStates($osinfo) == 0
	    or die_noretry("$node could not inherit taint states from $osinfo");
	#
508 509 510 511 512 513
	# Make sure this OSID is actually loaded on the machine.
	#
	my $isloaded = $node->IsOSLoaded($osinfo);
	if ($isloaded < 0) {
	    die_noretry("Error determining if $osinfo is loaded on $node\n");
	}
514 515 516
	if ($self->debug()) {
	    print STDERR "$node:$osinfo: isloaded:$isloaded\n";
	}
517
	if ($isloaded) {
518 519 520 521 522 523 524 525 526
	    #
	    # XXX the primary (boot) OSID is already loaded, but we are loading
	    # multiple images. In this case we reload the primary OS anyway so that
	    # the logic in osload continues to work (it assumes that it is responsible
	    # for setting the def_boot_osid based on the last image specified).
	    #
	    if (!$auxload && $multiple) {
		$self->SetupReload($node, $osinfo, $auxload);
	    }
527
	    #
528
	    # OSID is loaded, but might need to be cleaned.
529
	    #
530
	    elsif ($self->dolastload() &&
531 532 533
		defined($node->last_reservation()) &&
		$node->last_reservation() ne $pid) {
		$self->SetupReload($node, $osinfo, $auxload);
534
	    }
535
	    elsif ($nextosinfo && !$auxload) {
536
		#
537 538 539
		# Seems like a bad place for this; if the OS was
		# mapped to something else that is already on the
		# disk, need to reset def_boot_osid.
540
		#
541 542 543
		if ($self->impotent()) {
		    print STDERR "$node_id:def_boot_osid --> $osinfo\n"
			if ($self->debug());
544
		}
545 546
		elsif ($node->OSSelect($osinfo, "def_boot_osid", 0)) {
		    die_noretry("Could not set boot OS to $osinfo for $node");
547 548
		}
	    }
549 550 551 552 553 554
	}
	else {
	    #
	    # OS not loaded.
	    #
	    $self->SetupReload($node, $osinfo, $auxload);
555 556 557 558 559 560 561 562
	}
    }
}

#
# Take a list of nodes and fire off the required reloads/reboots/reconfigs
# in parallel, then wait for finish.
#
563 564 565
# This is called in a child (fork) so all state has to be communicated via
# the DB, back to the parent. See the WaitForNodes() function. 
#
566 567 568 569
sub LightUpNodes($@)
{
    my ($self, @nodelist) = @_;
    my @children = ();
Leigh Stoller's avatar
Leigh Stoller committed
570
    my @failed   = ();
571 572 573 574 575 576 577 578 579 580 581 582 583 584

    #
    # Set up lists of what we are going to do.
    #
    my %reloads   = ();
    my %reboots   = ();
    my %reconfigs = ();
    my %rebooted  = ();

    foreach my $node (@nodelist) {
	my $node_id = $node->node_id();
	my $op      = $node->_setupoperation();
	my $action;

585 586 587 588
	# Nothing to do.
	next
	    if ($op == $NOSTATE);

Leigh Stoller's avatar
Leigh Stoller committed
589
	if ($op == $RELOAD) {
590 591
	    my $image    = $node->_loadimage();
	    my @images   = ($image);
592
	    my $imageids = $image->versid();
593 594 595 596 597 598 599 600
	    my $auxloads = $node->_loadimages();

	    #
	    # Watch for multiple loads, but remember that the boot image
	    # has to be last since libosload assumes that is the one to boot.
	    #
	    if (defined($auxloads)) {
		foreach my $aux (@{ $auxloads }) {
601
		    my $auxid = $aux->versid();
602 603 604 605 606 607 608
		    unshift(@images, $aux);
		    $imageids = "${auxid},${imageids}";
		}
	    }
	    
	    if (!exists($reloads{"$imageids"})) {
		$reloads{"$imageids"} = [];
609
	    }
610 611
	    push(@{ $reloads{"$imageids"} }, $node);
	    $action = "reloaded with @images";
612 613 614 615 616 617 618 619 620
	}
	elsif ($op == $REBOOT) {
	    $reboots{$node_id} = $node;
	    $action = "rebooted";
	}
	elsif ($op == $RECONFIG) {
	    $reconfigs{$node_id} = $node;
	    $action = "reconfiged";
	}
621
	print STDERR "$node_id will be $action\n";
622 623 624
    }

    # XXX Caller wants a list. 
625
    return 0
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
	if ($self->impotent());
    
    #
    # Now fire them off.
    #
    foreach my $imageid ( keys(%reloads) ) {
	my @nlist = @{ $reloads{$imageid} };
	my @list  = ();
	my %nodeflags = ();

	foreach my $node (@nlist) {
	    my $node_id = $node->node_id();
	    # The osload library gets ids.
	    push(@list, $node_id);
	    
	    #
	    # vnodes only get rebooted if this is a modify and we need
	    # to reload them (otherwise they will get rebooted because
	    # of presence in %reboots).
	    #
	    if ($node->isvirtnode()) {
		if (defined($node->allocstate()) &&
		    $node->allocstate() eq TBDB_ALLOCSTATE_RES_INIT_CLEAN()) {
		    $nodeflags{$node_id}{'noreboot'} = 1;
		}
	    }

	    #
	    # osload should not wait for shared vnodes.  We need
	    # vnode_setup to boot/reboot them since the underlying pnode
Leigh Stoller's avatar
Leigh Stoller committed
656
	    # will not be booting.  So for them, osload just sets up the
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
	    # reload and finishes.
	    #
	    if ($node->isvirtnode() && $node->_onsharednode()) {
		$nodeflags{$node_id}{'noreboot'} = 1;
		$nodeflags{$node_id}{'nowait'} = 1;
	    }

	    $node->SetAllocState(TBDB_ALLOCSTATE_RES_RELOAD());
	    # No point in reboot/reconfig obviously, since node will reboot!
	    delete $reboots{$node_id};
	    delete $reconfigs{$node_id};
	    $rebooted{$node_id} = 1;
	}

	my %reload_args     = ();
	my $reload_failures = {};

	$reload_args{'debug'}     = $self->debug();
	$reload_args{'asyncmode'} = 1;
	$reload_args{'imageid'}   = $imageid;
	$reload_args{'nodelist'}  = [ @list ];
	$reload_args{'nodeflags'} = \%nodeflags;

680 681 682 683 684 685
	my $pid;
	my $coderef;
	if (EmulabFeatures->FeatureEnabled("NewOsload",$self->user(),
					   $self->group(),
					   $self->experiment())) {
	    ($self->loadobj())->debug($self->debug());
686 687

	    # add a few more things for feature checks down the line:
688 689 690
	    $reload_args{'user'} = $self->user();
	    $reload_args{'group'} = $self->group();
	    $reload_args{'experiment'} = $self->experiment();
691

692 693 694 695 696 697 698 699
	    $pid = ($self->loadobj())->osload(\%reload_args, $reload_failures);
	    $coderef = sub {
		my $childpid = shift;
		return ($self->loadobj())->osload_wait($childpid);
	    };
	}
	else {
	    $pid = osload(\%reload_args, $reload_failures);
700
	    $coderef = \&libosload::osload_wait;
701
	}
702
	push(@children, [ $pid, $coderef,
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
			  [ @list ], $reload_failures ]);
	sleep(5);
    }

    #
    # Fire off the reboots.
    # 
    if (keys(%reboots)) {
	foreach my $node_id (keys(%reboots)) {
	    my $node = $self->node($node_id);

	    if (defined($node->allocstate()) &&
		$node->allocstate() eq TBDB_ALLOCSTATE_RES_INIT_CLEAN()) {
		$node->SetAllocState(TBDB_ALLOCSTATE_RES_REBOOT_CLEAN());
	    }
	    else {
		$node->SetAllocState(TBDB_ALLOCSTATE_RES_REBOOT_DIRTY());
	    }
	    # Needed for vnode_setup.
	    $rebooted{$node_id} = 1;
	}

	my @list            = keys(%reboots);
	my %reboot_args     = ();
	my $reboot_failures = {};

	$reboot_args{'debug'}     = $self->debug();
	$reboot_args{'waitmode'}  = 0;
	$reboot_args{'asyncmode'} = 1;
732
	$reboot_args{'rebootmode'} = $self->realreboot();
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
	$reboot_args{'nodelist'}  = [ @list ];

	my $pid = nodereboot(\%reboot_args, $reboot_failures);
	push(@children, [ $pid, \&nodereboot_wait,
			  [ @list ], $reboot_failures ]);
	sleep(2);
    }

    #
    # Fire off the reconfigs.
    #
    if (keys(%reconfigs)) {
	my @list            = keys(%reconfigs);
	my %reboot_args     = ();
	my $reboot_failures = {};

	$reboot_args{'debug'}     = $self->debug();
	$reboot_args{'waitmode'}  = 0;
	$reboot_args{'asyncmode'} = 1;
752
	$reboot_args{'rebootmode'} = $self->realreboot();
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
	$reboot_args{'reconfig'}  = 1;
	$reboot_args{'nodelist'}  = [ @list ];

	my $pid = nodereboot(\%reboot_args, $reboot_failures);
	push(@children, [ $pid, \&nodereboot_wait,
			  [ @list ], $reboot_failures ]);
    }

    #
    # Wait for all of the children to exit. We look at the $pid to know if
    # command failed/ended immediately; otherwise we need to wait on it.
    # For any failures, record the node failures for later so that we do
    # not wait for them needlessly.
    #
    while (@children) {
	my ($pid, $waitfunc, $listref, $hashref) = @{ pop(@children) };

	# This is not likely to happen.
	next
	    if ($pid == 0);

	if ($pid > 0) {
	    next
		if (! &$waitfunc($pid));
	}
	
	#
	# Failure. Record the failures for later. If the $pid<0 then the
	# entire list failed. Otherwise, have to scan the return hash to
	# find the failures.
	#
	my @nlist = ();
	
	if ($pid < 0) {
	    @nlist = @{ $listref };
	}
	else {
	    foreach my $node_id (keys(%{ $hashref })) {
		push(@nlist, $node_id)
		    if ($hashref->{$node_id});
	    }
	}

	#
Leigh Stoller's avatar
Leigh Stoller committed
797 798 799
	# Mark all of the failed nodes so that the caller knows there
	# was a failure. 
	# 
800 801
	foreach my $node_id (@nlist) {
	    my $node = $self->node($node_id);
Leigh Stoller's avatar
Leigh Stoller committed
802

803 804 805
	    $node->SetAllocState(TBDB_ALLOCSTATE_DOWN());
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
806 807 808 809 810 811 812 813 814 815 816

    return scalar(@failed);
}

#
# Generic waiting function for a list of nodes.
#
sub WaitForNodes($@)
{
    my ($self, @nodelist) = @_;
    my %nodes = ();
817 818 819
    my @waitstates = (TBDB_NODESTATE_TBFAILED,
		      TBDB_NODESTATE_RELOADFAILED,
		      TBDB_NODESTATE_ISUP);
Leigh Stoller's avatar
Leigh Stoller committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

    # Maybe all nodes failed to light up?
    return 0
	if (! @nodelist);

    # Copy of the array. 
    foreach my $node (@nodelist) {
	$nodes{$node->node_id()} = $node;
	$node->_waitstart(time());
	$node->Refresh();
    }

    #
    # See if the previous phase (lighting up the nodes) failed.
    # We use the bogus allocstate for this.
    #
    foreach my $node (@nodelist) {
	my $node_id = $node->node_id();
838 839
	my $typehandler = $node->_typehandler();
	
Leigh Stoller's avatar
Leigh Stoller committed
840 841 842 843 844 845 846 847 848 849 850
	next
	    if (! ($node->allocstate() eq TBDB_ALLOCSTATE_DOWN() ||
		   $node->allocstate() eq TBDB_ALLOCSTATE_DEAD()));

	#
	# These are unusual errors. Lets turn off retry.
	#
	$self->noretry(1);

	tbnotice("Not waiting for $node_id since reload/reboot failed!\n");
	delete($nodes{$node_id});
851 852
	$node->_setupstatus($RELOAD_FAILED);
	$typehandler->WaitDone($node);
Leigh Stoller's avatar
Leigh Stoller committed
853 854 855 856 857 858 859 860
    }

    #
    # Start a counter going, relative to the time we rebooted the first
    # node.
    #
    my $waittime  = 0;
    my $minutes   = 0;
861
    my $canceled  = $self->canceled();
Leigh Stoller's avatar
Leigh Stoller committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884

    #
    # Wait for the nodes to finish booting, as recorded in database
    #
    while (keys(%nodes)) {
	#
	# Check for cancelation. Do not want to retry if swap was canceled.
	#
	if (!$canceled) {
	    $canceled = $self->experiment()->canceled();
	    if ($canceled) {
		# So everyone knows.
		$self->canceled($canceled);
		tbnotice({cause => 'canceled', severity => SEV_IMMEDIATE,
			  error => ['cancel_flag']},
			 "Swap canceled; will terminate os_setup early!");
	    }
	}
	
	foreach my $node (values(%nodes)) {
	    my $node_id = $node->node_id();
	    my $typehandler = $node->_typehandler();
	    my $state;
885
	    my $state_timestamp;
Leigh Stoller's avatar
Leigh Stoller committed
886

887 888 889 890 891 892 893 894 895 896 897
	    #
	    # Terminate the remaining nodes early ...
	    #
	    if ($canceled) {
		print STDERR "$node_id: not waiting cause of cancellation.\n";
		$node->_setupstatus($SETUP_CANCELED);
		delete($nodes{$node_id});
		$typehandler->WaitDone($node);
		next;
	    }

Leigh Stoller's avatar
Leigh Stoller committed
898 899 900 901 902 903 904 905 906
	    #
	    # Call typehandler specific wait function; 
	    #
	    my $retval = $typehandler->WaitForNode($node);
	    #
	    # Zero means the handler had nothing to say.
	    #
	    if ($retval) {
		# The handler has to set the node state to something useful.
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
		if ($retval < 0) {
		    delete($nodes{$node_id});
		    $typehandler->WaitDone($node);
		    next;
		}
		#
		# The handler has decided to stop waiting for now and
		# send the node back through later. 
		#
		if ($retval == 1) {
		    delete($nodes{$node_id});
		    next;
		}
		#
		# We are going to kick the node and wait again. This will
		# make sure it stays on the node list and get called up
		# the time we ask for volunteers.
		#
		if ($retval > 0) {
		    delete($nodes{$node_id});
		    $typehandler->WaitDone($node);
		    next;
		}
Leigh Stoller's avatar
Leigh Stoller committed
930
	    }
931
	    if ($node->GetEventState(\$state, undef, \$state_timestamp)) {
Leigh Stoller's avatar
Leigh Stoller committed
932
		print STDERR "*** Error getting event state for $node_id.\n";
933
		$node->_setupstatus($SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
934 935 936 937 938 939
		delete($nodes{$node_id});
		$typehandler->WaitDone($node);
		next;
	    }
	    if (grep {$_ eq $state} @waitstates) {
		print "$node_id has reported state $state\n";
940 941 942 943 944 945
		if ($state eq TBDB_NODESTATE_ISUP()) {
		    $node->_setupstatus($SETUP_OKAY);
		}
		else {
		    $node->_setupstatus($SETUP_FAILED);
		}
Leigh Stoller's avatar
Leigh Stoller committed
946 947 948 949 950 951 952 953 954 955 956 957
		delete($nodes{$node_id});
		$typehandler->WaitDone($node);
		next;
	    }
	    $waittime = time() - $node->_waitstart();
	    if ($waittime > $node->_maxwait()) {
		$minutes = int($waittime / 60);
		if ($canceled ||
		    $self->noretry() || !$node->_retrycount()) {
		    tbnotice("*** Giving up on $node_id ($state) - ".
			     "it's been $minutes minute(s).\n");

958
		    $node->_setupstatus($SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
959 960 961 962 963
		    delete($nodes{$node_id});
		    $typehandler->WaitDone($node);
		}
		else {
		    if ($typehandler->Retry($node) != 0) {
964
			$node->_setupstatus($SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
965 966 967 968 969 970 971 972 973 974 975
			delete($nodes{$node_id});
			$typehandler->WaitDone($node);
		    }
		    else {
			$node->_retrycount($node->_retrycount() - 1);
			$node->_waitstart(time());
		    }
		}
		next;
	    }
	    if (int($waittime / 60) > $minutes) {
976 977
		# Changing minutes is why we get this print for just
		# a single node each time. 
Leigh Stoller's avatar
Leigh Stoller committed
978
		$minutes = int($waittime / 60);
979
		my $state_minutes = int((time() - $state_timestamp) / 60);
Leigh Stoller's avatar
Leigh Stoller committed
980
		tbnotice("Still waiting for $node_id ($state) - ".
981
			 "it's been $minutes/$state_minutes minute(s).\n");
Leigh Stoller's avatar
Leigh Stoller committed
982 983 984 985 986
	    }
	}
	sleep(5);
    }
    return 0;
987 988 989 990 991 992 993 994
}

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

    #
    # These special cases will eventually be encoded in the DB.
998
    # Note that type might be a class, and so Lookup() returns nothing.
999
    #
1000
    my $typeinfo = NodeType->Lookup($type);
1001
    my $packname = "libossetup_${type}";
1002

1003 1004 1005 1006 1007 1008 1009
    # Switches are special.
    if (defined($typeinfo) && $typeinfo->isswitch()) {
	eval "require libossetup_switch";
	if ($@) {
	    print STDERR "$self libossetup_switch load failed: " . $@;
	    return undef;
	}
1010 1011 1012
	$packname = "libossetup_${type}";
	# Dashes in package names are bad.
	$packname =~ s/\-/\_/g;
1013 1014 1015
    }
    elsif (defined($typeinfo) && $typeinfo->issubnode()) {
	$type = "subnode";
1016
	$packname = "libossetup_subnode";
1017
    }
1018

1019 1020 1021
    my $newtype  = eval { $packname->New($self); };
    # Not loaded?
    if ($@) {
1022
	#print STDERR "module load failed: " . $@ . "\n";
1023
	eval "require $packname";
1024 1025 1026 1027 1028 1029
	if ($@) {
	    if ($@ !~ /Can't locate libossetup_/) {
		print STDERR "$self NewType($type): module load failed: " . $@;
	    }
	    return undef;
	}
1030 1031
	$newtype  = eval { $packname->New($self); };
	if ($@) {
1032
#	    print STDERR "$self NewType($type): New() failed: " . $@ . "\n"
1033
#		if ($self->debug());
1034 1035
	    return undef;
	}
1036 1037 1038
    }
    $self->{'TYPECACHE'}->{$type} = $newtype;
    
1039 1040
#    print STDERR "Created type object $type with parent $self\n"
#	if ($self->debug());
1041 1042 1043 1044 1045 1046
    
    return $newtype;
}
#
# Return the cached type object.
#
1047
sub TypeLookup($$)
1048 1049 1050
{
    my ($self, $node) = @_;

1051 1052 1053 1054 1055 1056
    my $type  = $node->type();
    my $class = $node->class();

    #
    # These special cases will eventually be encoded in the DB.
    #
1057 1058 1059 1060 1061 1062
    if ($type eq "pcfedphys" || $type eq "pcfed") {
	$type = "protogeni";
    }
    elsif ($node->issubnode()) {
	$type = "subnode";
    }
1063

1064 1065 1066 1067 1068
    return $self->{'TYPECACHE'}->{$type}
        if (exists($self->{'TYPECACHE'}->{$type}));

    return $self->{'TYPECACHE'}->{$class}
        if (exists($self->{'TYPECACHE'}->{$class}));
1069 1070 1071 1072 1073 1074 1075 1076

    return undef;
}

#
# Wrapper class for the type/class specific packages below.
#
package libossetup_handler;
1077
use base qw(libossetup);
1078 1079 1080 1081

use libdb;
use libtestbed;
use libossetup;
1082
use libtblog_simple;
1083 1084 1085
use Node;
use English;
use Data::Dumper;
1086
use overload ('""' => 'Stringify');
1087

1088 1089
use vars qw($AUTOLOAD);

1090 1091 1092 1093
sub New($$$)
{
    my ($class, $type, $parent) = @_;

Leigh Stoller's avatar
Leigh Stoller committed
1094 1095 1096 1097 1098 1099
    my $self             = {};
    $self->{'TYPE'}      = $type;
    $self->{'NODES'}     = {};
    $self->{'PARENT'}    = $parent;
    $self->{'FAILCOUNT'} = 0;
    $self->{'TODOLIST'}  = {};
1100 1101 1102 1103 1104 1105 1106

    bless($self, $class);
    return $self;
}
# Access methods for the objects defined below, which are 
sub type($)		{ return $_[0]->{'TYPE'}; }
sub parent($)		{ return $_[0]->{'PARENT'}; }
Leigh Stoller's avatar
Leigh Stoller committed
1107
sub failcount($)	{ return $_[0]->{'FAILCOUNT'}; }
1108
sub nodelist($)         { return values(%{ $_[0]->{'NODES'} }); }
Leigh Stoller's avatar
Leigh Stoller committed
1109 1110 1111
sub todo($)		{ return $_[0]->{'TODOLIST'}; }
sub todolist($)		{ return values(%{ $_[0]->{'TODOLIST'} }); }
sub IncrFailCount($)    { $_[0]->{'FAILCOUNT'}++ }
1112

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
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 "$self: tried to access unknown slot $name\n";
    return undef;
}

1130
#
Leigh Stoller's avatar
Leigh Stoller committed
1131
# Add a node to the list.
1132
#
Leigh Stoller's avatar
Leigh Stoller committed
1133
sub AddNode($$)
1134
{
Leigh Stoller's avatar
Leigh Stoller committed
1135 1136 1137 1138 1139 1140 1141
    my ($self, $node) = @_;
    my $node_id = $node->node_id();

    $self->{'NODES'}->{$node_id}    = $node;
    $self->{'TODOLIST'}->{$node_id} = $node;
    $node->_typehandler($self);
    $node->_setupoperation($libossetup::NOSTATE);
1142 1143

    #
Leigh Stoller's avatar
Leigh Stoller committed
1144 1145
    # This sets the OS that should boot, as well as any reloads, reboots
    # and reconfigs that are needed.
1146
    #
Leigh Stoller's avatar
Leigh Stoller committed
1147 1148
    $self->parent()->SetOS($node);
    return 0;
1149 1150 1151
}

#
Leigh Stoller's avatar
Leigh Stoller committed
1152 1153
# Stub function to light up a set of nodes; calls the big version in the
# parent.
1154
#
Leigh Stoller's avatar
Leigh Stoller committed
1155
sub LightUpNodes($@)
1156
{
Leigh Stoller's avatar
Leigh Stoller committed
1157
    my ($self, @nodelist)  = @_;
1158 1159
    my $parent = $self->parent();

Leigh Stoller's avatar
Leigh Stoller committed
1160 1161
    return $parent->LightUpNodes(@nodelist);
}
1162

Leigh Stoller's avatar
Leigh Stoller committed
1163 1164 1165 1166 1167 1168
#
# Return the set of nodes ready to go.
#
sub Volunteers($)
{
    my ($self) = @_;
1169

Leigh Stoller's avatar
Leigh Stoller committed
1170 1171 1172 1173 1174 1175 1176 1177 1178
    return $self->todolist();
}

#
# Stub function to retry a node, called by the wait function. 
#
sub Retry($$)
{
    my ($self, $node) = @_;
1179 1180

    #
Leigh Stoller's avatar
Leigh Stoller committed
1181 1182
    # Return an error since this should not be called; it
    # should be overridden or the retry count always set to zero.
1183
    #
Leigh Stoller's avatar
Leigh Stoller committed
1184 1185
    return -1;
}
1186

Leigh Stoller's avatar
Leigh Stoller committed
1187 1188 1189 1190 1191 1192
#
# Generic wait for a single function.
#
sub WaitForNode($$)
{
    my ($self, $node) = @_;
1193

Leigh Stoller's avatar
Leigh Stoller committed
1194 1195 1196
    # Tell caller I have nothing to offer. 
    return 0;
}
1197

Leigh Stoller's avatar
Leigh Stoller committed
1198 1199 1200 1201 1202 1203
#
# Generic waitdone function.
#
sub WaitDone($@)
{
    my ($self, @nodelist) = @_;
1204 1205
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();
Leigh Stoller's avatar
Leigh Stoller committed
1206 1207 1208 1209 1210 1211 1212 1213 1214

    foreach my $node (@nodelist) {
	my $node_id = $node->node_id();
	
    	#
	# At this point, we are done with this node, so remove
	# it from the todo list. Might do something fancy later.
	#
	delete($self->todo()->{$node_id});
1215 1216 1217 1218
    }
    return 0;
}

1219 1220 1221 1222 1223 1224 1225 1226 1227
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $type = $self->type();

1228
    return "libossetup_$type";
1229 1230
}

1231 1232 1233 1234 1235 1236
#####################################################################
#
# Generic handler for local cluster nodes that do not require much
# special handling.
#
package libossetup_pc;
1237
use base qw(libossetup_handler);
1238 1239 1240 1241

use libdb;
use libtestbed;
use libossetup;
1242
use libtblog_simple;
1243 1244 1245
use Node;
use English;
use Data::Dumper;
1246
use overload ('""' => 'Stringify');
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270

#
# A constructor for an object to handle all nodes of this type.
#
sub New($$) {
    my ($class, $parent) = @_;

    my $self = $class->SUPER::New("pc", $parent);
    bless($self, $class);
    return $self;
}

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

    #
    # XXX Inner elab nodes should never report in to us.
    # If they do, make sure they wind up in PXEWAIT.
    #
    if ($node->_iseinenode()) {
	print "Will skip reload/reboot of inner elab node: $node_id.\n";
	$node->ClearOsids();
1271 1272
	# Need to initialize this for the stats code.
	$node->_bootosinfo(undef);
1273 1274 1275
	return 0;
    }

Leigh Stoller's avatar
Leigh Stoller committed
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    $self->SUPER::AddNode($node);

    #
    # Skip this if an OS needs to be reloaded.
    #
    if ($node->_setupoperation() != $libossetup::RELOAD) {
	if ($node->allocstate() eq TBDB_ALLOCSTATE_RES_RECONFIG()) {
	    $node->_setupoperation($libossetup::RECONFIG);
	}
	elsif ($node->allocstate() ne TBDB_ALLOCSTATE_RES_READY()) {
	    # only reboot node if assign_wrapper just pulled it into expt.
	    # (e.g. it isnt ALLOCSTATE_RES_READY)
	    $node->_setupoperation($libossetup::REBOOT);
	}
1290
    }
Leigh Stoller's avatar
Leigh Stoller committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

    #
    # Set up the retry count and the waittime.
    #
    my $waittime = (60 * 7);	# The default.
    my $osinfo   = $node->_bootosinfo();

    # Compute actual waittime.
    if (defined($node->bios_waittime()) &&
	defined($osinfo->reboot_waittime())) {
	$waittime = ($node->bios_waittime() +
		     $osinfo->reboot_waittime()) * 2;
1303
    }
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    # Adjust for image backed datasets which take more time to load.
    my @blockstores =
	$self->parent()->experiment()->LookupBlockstoresForNode($node->vname());
    if (@blockstores) {
	require Blockstore;

	foreach my $blockstore (@blockstores) {
	    next
		if ($blockstore->type() ne "imdataset");
	    my $bsname = $blockstore->vname();
	    my $extra  = Blockstore::LoadEstimate($blockstore);

	    if ($extra < 0) {
		print STDERR
		    "*** Could not compute load estimate for $bsname\n";
		next;
	    }
	    print "Adding $extra seconds for blockstore $bsname\n";
	    $waittime += $extra;
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
1325 1326
    $node->_retrycount(1);
    $node->_maxwait($waittime);
1327
    $node->_setupstatus($libossetup::SETUP_OKAY);
1328 1329 1330 1331

    return 0;
}

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
#
# Return the set of nodes ready to go.
#
sub Volunteers($)
{
    my ($self)     = @_;
    my @nodelist   = $self->todolist();
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();
    my $firewall;
    my $firewalled = $experiment->IsFirewalled(\$firewall);
    my $elabinelab = $experiment->elabinelab();

    #
    # Setup the firewall first.  Once it is up we can continue with the
    # remaining nodes.
    #
    # There is very little point in setting up the other nodes at the same time
    # as they will not be able to PXE boot until the firewall is up.  We
    # could fire them off a little early in hopes of overlapping any BIOS
    # boot time with the last stages of the firewall setup, but it probably
    # isn't worth the complexity (and would not work with nodes for which
    # "reboot" means "fall out of PXEWAIT and boot".
    #
    # Note that we formerly did just do them all at once and let the nodes
    # continually PXE-timeout and reboot until the firewall came up.  But
    # that can actually take longer than what we do now, if a node happened
    # to timeout and reboot just as the firewall came up (i.e., we would
    # have to wait an extra BIOS-reboot cycle, which can be 90 seconds or
    # more.
    #
    if ($firewalled) {
	my $fwnode = $self->node($firewall);
	#
	# If the firewall fails, we abort and never come back.
	#
	if ($fwnode->allocstate() ne TBDB_ALLOCSTATE_RES_READY()) {
	    tbnotice("Setting up the firewall node first ... \n");
	    return ($fwnode);
	}
	# Remove firewall from the node list.
	@nodelist = grep {$_->node_id() ne $firewall} @nodelist;
    }
    return @nodelist;
}

1378
#
Leigh Stoller's avatar
Leigh Stoller committed
1379
# Wait function signals some local cluster nodes are done waiting.
1380
#
Leigh Stoller's avatar
Leigh Stoller committed
1381
sub WaitDone($@)
1382
{
Leigh Stoller's avatar
Leigh Stoller committed
1383
    my ($self, @nodelist) = @_;
1384 1385 1386 1387
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();
    my $pid        = $experiment->pid();
    my $eid        = $experiment->eid();
1388 1389 1390
    my $firewall;
    my $firewalled = $experiment->IsFirewalled(\$firewall);
    my $elabinelab = $experiment->elabinelab();
Leigh Stoller's avatar
Leigh Stoller committed
1391

1392
    #
Leigh Stoller's avatar
Leigh Stoller committed
1393
    # Must call the generic WaitDone handler too.
1394
    #
Leigh Stoller's avatar
Leigh Stoller committed
1395
    $self->SUPER::WaitDone(@nodelist);
1396

1397 1398 1399 1400 1401 1402 1403 1404 1405
    #
    # See if we allow failed osloads to continue on failureaction==nonfatal.
    # Since this is at its finest per-experiment, we check outside the loop.
    #
    my $osloadfailok = EmulabFeatures->FeatureEnabled("OsloadFailNonfatal",
						      $parent->user(),
						      $parent->group(),
						      $experiment);

1406
    #
Leigh Stoller's avatar
Leigh Stoller committed
1407
    # Then per node processing.
1408 1409
    #
    foreach my $node (@nodelist) {
1410 1411 1412
	my $node_id     = $node->node_id();
	my $setupstatus = $node->_setupstatus();
	my $eventstate  = $node->eventstate();
1413

1414
	if ($eventstate eq TBDB_NODESTATE_ISUP()) {
1415 1416 1417
	    print "$node_id is alive and well\n";
	    $node->SetBootStatus(NODEBOOTSTATUS_OKAY);
	    $node->SetAllocState(TBDB_ALLOCSTATE_RES_READY());
1418 1419 1420 1421
	    # Set this so we know a successful reboot was done.
	    # Important for VMs that depend on this node.
	    $node->_rebooted(1)
		if ($node->_setupoperation() != $libossetup::NOSTATE);
1422

1423
	    if ($firewalled && $node_id eq $firewall) {
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
		#
		# Firewall has booted, perform any final actions.
		#
		# The only case that currently matters is if the experiment is
		# elabinelab. In this case we want to turn off the firewall
		# so the nodes can boot/reload normally. Later, after we
		# set up the inner elab, we turn the firewall back on.
		#
		if ($elabinelab) {
		    #
		    # We use the elabinelab program to do this, since it
		    # knows what it might want to do (and helpfully, is
		    # setuid so it can ssh over).
		    #
		    system("$ELABINELAB -f $pid $eid");
		    if ($?) {
			tbnotice("Firewall Boot Setup failed!\n");
			$parent->aborted(1);
		    }
		}
	    }
1445 1446 1447
	    next;
	}
	# Fall through on failure.	
1448
	if ($eventstate eq TBDB_NODESTATE_TBFAILED()) {
1449 1450 1451 1452 1453 1454 1455
	    tbwarn("$node_id reported a TBFAILED event\n");
	}
	else {
	    tbwarn("$node_id failed to boot\n");
	}
	$node->SetBootStatus(NODEBOOTSTATUS_FAILED);

1456 1457 1458
	#
	# If the firewall fails to boot, we are hosed. Quit right away.
	#
1459
	if ($firewalled && $node_id eq $firewall) {
1460 1461 1462 1463
	    tbnotice("Firewall failed to boot!\n");
	    $parent->aborted(1);
	}

1464
	#
1465
	# Handle non-fatal failures (if we have not been canceled or aborted).
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
	if ($node->_canfail() &&
	    !$experiment->canceled() && !$parent->aborted()) {
	    #
	    # Non-fatal reload failures require special handling.
	    # (Note: no check for noretry() since it will always be set.)
	    #
	    # XXX it is not clear what the right strategy is here since
	    # the node might not boot, might boot into the wrong OS, or
	    # it might just sit there trying to boot over and over again.
	    # We could just power the machine off and tell the user.
	    # We could boot the node into the admin MFS and tell the user.
	    # We could park the node at PXEWAIT whenever it boots.
	    # Or we could just let it go and tell the user.
	    #
	    # Right now we park it in PXEWAIT on reboot. If the node is
	    # hung, the user will surely notice. If the node does reboot
	    # it will stop in PXEWAIT and the user will surely notice.
	    #
	    if ($setupstatus == $libossetup::RELOAD_FAILED) {
		if ($osloadfailok) {
		    # clear all boot osids causing node to go into PXEWAIT
		    if ($node->OSSelect(undef, undef, 0)) {
			tbnotice("could not force into PXEWAIT; failing\n");
			goto bad;
		    }
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
		    # and partitions
		    $node->ClearPartitions();

		    # XXX this will force node to reboot
		    $node->SetEventState(TBDB_NODESTATE_TBFAILED());

		    $parent->add_failed_node_inform_user($node_id);
		    $parent->add_failed_node_nonfatal($node_id);
		    tbwarn("$node_id will stop in PXEWAIT state on reboot\n");
		    tbnotice("Continuing with experiment setup anyway ...\n");

		    # XXX otherwise, os_setup will still fail
		    $parent->noretry(0);
		    # XXX so subsequent swapmods don't free the node
		    $node->SetAllocState(TBDB_ALLOCSTATE_RES_READY());
		    next;
		}
	    }
	    elsif (!$parent->noretry()) {
		$parent->add_failed_node_inform_user($node_id);
		$parent->add_failed_node_nonfatal($node_id);
		tbnotice("Continuing with experiment setup anyway ...\n");
		next;
	    }
1517
	}
1518 1519 1520 1521
	elsif ($setupstatus == $libossetup::SETUP_CANCELED) {
	    # Skip the stuff below, not needed.
	    next;
	}
1522

1523
      bad:
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
	#
	# If the user has picked a standard image and it fails to boot,
	# something is wrong, so reserve it to checkup experiment. If the
	# image belongs to the user, then we assume its the image at fault,
	# and allow it to be returned to the pool (caller, tbswap will end
	# doing the nfree on nodes with a DOWN allocstate).
	#
	my $osinfo = $node->_bootosinfo();
	if (! defined($osinfo->pid()) || $osinfo->pid() eq TBOPSPID()) {
	    $node->MarkAsIll();
	    $node->InsertNodeLogEntry($parent->user(),
				      TB_DEFAULT_NODELOGTYPE(),
				      "'Moved to hwcheckup by os_setup; ".
				      "failed to boot image for $osinfo " .
				      "in $pid/$eid'");

	    $parent->add_failed_node_inform_tbopsfatal($node_id);
	}
	else {
	    $parent->add_failed_node_inform_tbopswarn($node_id);
	}
	$node->SetAllocState(TBDB_ALLOCSTATE_DOWN());
Leigh Stoller's avatar
Leigh Stoller committed
1546 1547
	$self->IncrFailCount();
	$parent->IncrFailCount();
1548 1549 1550 1551 1552 1553
	if ($setupstatus == $libossetup::RELOAD_FAILED) {
	    $parent->add_failed_node_reload($node_id);
	}
	else {
	    $parent->add_failed_node_fatal($node_id);
	}
1554
    }
Leigh Stoller's avatar
Leigh Stoller committed
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    return 0;
}

#
# Function to retry a node, called by the wait function. 
#
sub Retry($$)
{
    my ($self, $node) = @_;
    my $node_id = $node->node_id();

    tbnotice("Rebooting $node_id and waiting again ...\n");

    system("$NODEREBOOT $node_id");
    return $?;
1570 1571
}

1572 1573 1574 1575 1576 1577 1578
#####################################################################
package libossetup_pcRemote;
use base qw(libossetup_pc);

use libdb;
use libtestbed;
use libossetup;
1579
use libtblog_simple;
1580 1581 1582 1583 1584
use Node;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

1585 1586
#####################################################################
#
Leigh Stoller's avatar
Leigh Stoller committed
1587 1588
# This is a wrapper for virtnodes; hopefully most virtnodes can share
# stuff.
1589
#
Leigh Stoller's avatar
Leigh Stoller committed
1590
package libossetup_virtnode;
1591
use base qw(libossetup_handler);
1592 1593 1594 1595

use libdb;
use libtestbed;
use libossetup;
1596
use libosload;
1597
use libtblog_simple;
1598 1599 1600
use Node;
use English;
use Data::Dumper;
1601
use overload ('""' => 'Stringify');
1602

Leigh Stoller's avatar
Leigh Stoller committed
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
#
# A constructor for an object to handle all nodes of this type.
#
sub New($$$) {
    my ($class, $type, $parent) = @_;

    my $self = $class->SUPER::New($type, $parent);
    bless($self, $class);
    return $self;
}

sub AddNode($$)
{
    my ($self, $node) = @_;
    my $parent  = $self->parent();
    my $node_id = $node->node_id();

    #
    # The old code could deal with just jailed, plab, and remote nodes.
    # We are dropping plab support for now ...
    #
    return 0
1625
	if (! ($node->jailflag() || $node->isremotenode()));
Leigh Stoller's avatar
Leigh Stoller committed
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651

    $self->SUPER::AddNode($node);

    #
    # We need the physical node, although it if the physnode is shared,
    # it will not be allocated to this experiment.
    #
    my $pnode_id = $node->phys_nodeid();
    my $pnode    = $parent->node($pnode_id);
    if (!defined($pnode)) {
	$pnode    = Node->Lookup($pnode_id); 
	if (!defined($pnode)) {
	    die_noretry("Cannot lookup object for $pnode_id!");
	}
	# Put it in the parent node list cache to avoid lookup.
	$parent->{'PHYSNODES'}->{$pnode_id} = $pnode;
	$pnode->_vnodecount(0);
    }
    
    #
    # Count up the number of VMs on this pnode. We use this for
    # determining how long to wait for a particular vnode.
    #
    $pnode->_vnodecount($pnode->_vnodecount() + 1);
    # and stash the pnode in case we need it later.
    $node->_pnode($pnode);
1652 1653 1654 1655 1656
    # Taint the pnode if this vnode was tainted by its OS
    # and is not on a shared host.  No user access already on
    # the latter.
    if (($node->IsTainted(TB_TAINTSTATE_USERONLY) ||
	 $node->IsTainted(TB_TAINTSTATE_BLACKBOX))
Kirk Webb's avatar
Kirk Webb committed
1657
	&& $pnode->erole() ne "sharedhost") {
1658
	$pnode->AddTaintState(TB_TAINTSTATE_BLACKBOX) == 0 
Kirk Webb's avatar
Kirk Webb committed
1659
	    or die_noretry("Could not add blackbox taint state to vnode host!\n");
1660
    }
Leigh Stoller's avatar
Leigh Stoller committed
1661

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
    # No retry for VMs, 
    $node->_retrycount(0);

    #
    # A flag in case the node got stuck in a manner that we can try a
    # reboot.  This is different then _retrycount() which is a
    # more general retry that we do not do with VMs. For now, we are
    # going to retry only once when kickme is set. See below for more.
    #
    # Set to 1 to kick.
    #
    $node->_kickme(0);

Leigh Stoller's avatar
Leigh Stoller committed
1675 1676 1677 1678 1679
    #
    # See if a "reload" is required; some virtual nodes can get
    # custom guest OSs, which are loaded on the client side with
    # a sorta standard frisbee approach. We reach into the libosload
    # library to set up the necessary state, but otherwise the node
1680
    # is rebooted normally (or starts when its physical node starts).
Leigh Stoller's avatar
Leigh Stoller committed
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
    #
    if ($node->_setupoperation() eq $libossetup::RELOAD) {
	my $image = $node->_loadimage();

	my %reload_args     = ();
	my $reload_failures = {};

	$reload_args{'debug'}     = $parent->debug();
	$reload_args{'asyncmode'} = 0;
	$reload_args{'waitmode'}  = 0;
	$reload_args{'noreboot'}  = 1;
1692
	$reload_args{'imageid'}   = $image->versid();
Leigh Stoller's avatar
Leigh Stoller committed
1693 1694
	$reload_args{'nodelist'}  = [ $node_id ];

1695 1696 1697
	if (EmulabFeatures->FeatureEnabled("NewOsload",$self->user(),
					   $self->group(),
					   $self->experiment())) {
Leigh Stoller's avatar
Leigh Stoller committed
1698
	    ($parent->loadobj())->debug($parent->debug());	    
1699 1700 1701 1702 1703 1704

	    # add a few more things for feature checks down the line:
	    $reload_args{user} = $self->user();
	    $reload_args{group} = $self->group();
	    $reload_args{experiment} = $self->experiment();

1705 1706 1707 1708 1709
	    ($parent->loadobj())->osload(\%reload_args, $reload_failures);
	}
	else {
	    osload(\%reload_args, $reload_failures)
	}
Leigh Stoller's avatar
Leigh Stoller committed
1710

1711
	# Reset this. Updated in Volunteers() below. 
Leigh Stoller's avatar
Leigh Stoller committed
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
	$node->_setupoperation($libossetup::NOSTATE);
    }
    return 0;
}

#
# VMs are done with a different program. 
#
sub LightUpNodes($@)
{
    my ($self, @nodelist)  = @_;
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();
    my $pid        = $experiment->pid();
    my $eid        = $experiment->eid();
1727
    my @nodeids    = map { $_->node_id() } @nodelist;
Leigh Stoller's avatar
Leigh Stoller committed
1728 1729 1730

    tbnotice("Setting up virtual testbed nodes ...\n");
    TBDebugTimeStamp("vnode_setup starting");
1731
    system("$VNODESETUP -j $pid $eid @nodeids");
Leigh Stoller's avatar
Leigh Stoller committed
1732 1733 1734 1735
    my $exitval = $?;
    TBDebugTimeStamp("vnode_setup done");

    if ($exitval) {
1736 1737
	# This is very unusual.
	$parent->noretry(1);
Leigh Stoller's avatar
Leigh Stoller committed
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
	return -1;
    }
    return 0;
}

sub Volunteers($)
{
    my ($self)     = @_;
    my @nodelist   = ();
    my @failed     = ();
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();

    #
    # Look for nodes that we can do on this pass. Some nodes have
    # dependencies.
    #
1755
    foreach my $node ($self->todolist()) {
Leigh Stoller's avatar
Leigh Stoller committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
	my $node_id     = $node->node_id();
	my $pnode       = $node->_pnode();
	my $pnode_id    = $pnode->node_id();
	my $typehandler = $node->_typehandler();
	
	#
	# Make sure we get fresh state after vnode_setup ran.
	#
	$node->Refresh();
	$pnode->Refresh();

	#
	# If the physnode is not ours, the vnode always has to do the
	# setup, since the physnode does not reboot.
	#
        my $reservation = $pnode->Reservation();
	if (!defined($reservation)) {
	    die_noretry("Cannot lookup object for $pnode_id!");
	}

	#
	# If the physnode is not in this experiment, there is no
	# dependency, and we can do it now. Otherwise, we have to
	# wait to a later pass, after the physnode.
	#
1781
	if ($reservation->SameExperiment($parent->experiment())) {
1782 1783 1784 1785 1786 1787 1788 1789
	    #
	    # Watch for needing to ke kicked (just once).
	    #
	    if ($node->_kickme()) {
		$node->_setupoperation($libossetup::REBOOT);
		# Tell vnode_setup to really do it.
		$node->SetAllocState(TBDB_ALLOCSTATE_RES_REBOOT());
	    }
Leigh Stoller's avatar
Leigh Stoller committed
1790 1791 1792 1793
	    #
	    # If the node was rebooted, then we can determine if
	    # the vnode is dead, or worth waiting for.
	    #
1794
	    elsif ($pnode->_rebooted()) {
Leigh Stoller's avatar
Leigh Stoller committed
1795 1796 1797 1798 1799 1800