libossetup.pm.in 60 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27
#
package libossetup;

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

34 35 36 37
@EXPORT = qw(&die_noretry
	     $NOSTATE $RELOAD $RECONFIG $REBOOT
	     $RELOAD_FAILED $RECONFIG_FAILED $REBOOT_FAILED $SETUP_FAILED
	     $SETUP_OKAY);
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";
Leigh Stoller's avatar
Leigh Stoller committed
56
my $VNODESETUP  = "$TB/sbin/vnode_setup";
57
my $ELABINELAB  = "$TB/sbin/elabinelab";
58
my $TBADB       = "$TB/bin/tbadb";
59

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

66 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
#
# 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
97 98
    $self->{'GROUP'}      = (defined($experiment) ?
			     $experiment->GetGroup() : undef);
99 100
    $self->{'HASH'}       = {};
    $self->{'NODES'}      = {};
Leigh Stoller's avatar
Leigh Stoller committed
101
    $self->{'PHYSNODES'}  = {};
102
    $self->{'FAILED'}     = {};
103
    $self->{'FAILCOUNT'}  = 0;
104 105
    $self->{'OSMAP'}      = {};
    $self->{'TYPECACHE'}  = {};
Leigh Stoller's avatar
Leigh Stoller committed
106
    $self->{'OPLIST'}     = {};
107 108 109 110 111 112 113 114

    # 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
115 116 117

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

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

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

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

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

Leigh Stoller's avatar
Leigh Stoller committed
165 166 167 168 169 170 171
    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};
    }
172 173 174 175 176 177
    return undef
}

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

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

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

    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
209
sub OperationList($)
210 211 212 213 214 215 216 217 218 219
{
    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.
#
220
sub SetupReload($$$$)
221
{
222
    my ($self, $node, $osimage, $auxload) = @_;
223 224 225 226 227 228 229 230 231 232 233 234 235 236
    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";
    }

237
    if ((my $image = $osimage->MapToImage($type))) {
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
	#
	# 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
255
	$node->_setupoperation($RELOAD);
256
	$node->_reloaded(1);
257 258 259
	if ($self->debug()) {
	    print STDERR "SetupReload: $node:$image auxload:$auxload\n";
	}
260 261 262
    }
    else {
	die_noretry({type => 'primary', severity => SEV_ERROR,
263 264
		     error => ['file_not_found', 'image', $osimage, $node]},
		    "No image can be found for $osimage on $node ($type)!");
265 266 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
    }
}

#
# 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'} = {};
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
#
# 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;
}

319 320 321 322 323 324 325 326 327 328 329 330
#
# 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'} });
331
    my $logmsg   = $self->CollectBootLogFiles(@nodelist);
332 333 334 335 336 337 338 339 340 341 342 343
    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".
344 345
		 "$logmsg\n",
		 undef,
346 347 348 349 350 351 352 353 354 355 356 357 358
		 "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'} });
359
    my $logmsg   = $self->CollectBootLogFiles(@nodelist);
360 361 362 363 364 365
    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".
366
		 "The nodes have been moved into hardware checkup.\n\n$logmsg",
367 368 369 370 371 372 373 374 375 376 377 378 379
		 "$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'} });
380
    my $logmsg   = $self->CollectBootLogFiles(@nodelist);
381 382 383 384 385 386
    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".
387
		 "The nodes have been freed.\n\n$logmsg",
388 389 390 391 392 393 394 395 396 397 398 399 400
		 "$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();
401
    my $osid_vers     = $node->def_boot_osid_vers();
402
    my $osimage       = OSImage->Lookup($osid, $osid_vers);
403
    my $loadlist      = $node->loadlist();
404 405 406 407
    my $experiment    = $self->experiment();
    my $pid           = $experiment->pid();

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

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

    # 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.
    #
421
    if ($node->isvirtnode() && $osimage->def_parentosid()) {
422 423
	#
	# But, if the subos is static (like OPENVZ-STD), there is
424 425 426 427 428 429
	# 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. 
430 431
	#
	$imageable = 1
432
	    if (defined($osimage->MapToImage($node->type())));
433 434
    }

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

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

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

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

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

#
# Helper for above.
#
472
sub SetOSAux($$$$$)
473
{
474
    my ($self, $node, $osinfo, $auxload, $multiple) = @_;
475 476 477 478 479
    my $node_id       = $node->node_id();
    my $experiment    = $self->experiment();
    my $pid           = $experiment->pid();
    
    #
480
    # No more oskit kernels, just MFSs.
481
    #
482
    if (! $osinfo->mfs()) {
483
	my $nextosinfo;
484
	    
485 486 487 488
	#
	# Not an OSKit kernel.
	#
	if ($osinfo->IsGeneric()) {
489
	    #
490
	    # Map generic OSID to the specific one.
491
	    #
492 493 494
	    $nextosinfo = $osinfo->ResolveNextOSID($experiment);
	    if (!defined($nextosinfo)) {
		die_noretry("No next mapping for $osinfo on $node!\n");
495
	    }
496 497 498 499
	    print "Mapping $osinfo on $node_id to $nextosinfo\n";
	    $osinfo = $nextosinfo;
	}
	#
500 501 502 503 504 505
	# 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");
	#
506 507 508 509 510 511
	# 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");
	}
512 513 514
	if ($self->debug()) {
	    print STDERR "$node:$osinfo: isloaded:$isloaded\n";
	}
515
	if ($isloaded) {
516 517 518 519 520 521 522 523 524
	    #
	    # 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);
	    }
525
	    #
526
	    # OSID is loaded, but might need to be cleaned.
527
	    #
528
	    elsif ($self->dolastload() &&
529 530 531
		defined($node->last_reservation()) &&
		$node->last_reservation() ne $pid) {
		$self->SetupReload($node, $osinfo, $auxload);
532
	    }
533
	    elsif ($nextosinfo && !$auxload) {
534
		#
535 536 537
		# 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.
538
		#
539 540 541
		if ($self->impotent()) {
		    print STDERR "$node_id:def_boot_osid --> $osinfo\n"
			if ($self->debug());
542
		}
543 544
		elsif ($node->OSSelect($osinfo, "def_boot_osid", 0)) {
		    die_noretry("Could not set boot OS to $osinfo for $node");
545 546
		}
	    }
547 548 549 550 551 552
	}
	else {
	    #
	    # OS not loaded.
	    #
	    $self->SetupReload($node, $osinfo, $auxload);
553 554 555 556 557 558 559 560
	}
    }
}

#
# Take a list of nodes and fire off the required reloads/reboots/reconfigs
# in parallel, then wait for finish.
#
561 562 563
# 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. 
#
564 565 566 567
sub LightUpNodes($@)
{
    my ($self, @nodelist) = @_;
    my @children = ();
Leigh Stoller's avatar
Leigh Stoller committed
568
    my @failed   = ();
569 570 571 572 573 574 575 576 577 578 579 580 581 582

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

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

Leigh Stoller's avatar
Leigh Stoller committed
587
	if ($op == $RELOAD) {
588 589
	    my $image    = $node->_loadimage();
	    my @images   = ($image);
590
	    my $imageids = $image->versid();
591 592 593 594 595 596 597 598
	    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 }) {
599
		    my $auxid = $aux->versid();
600 601 602 603 604 605 606
		    unshift(@images, $aux);
		    $imageids = "${auxid},${imageids}";
		}
	    }
	    
	    if (!exists($reloads{"$imageids"})) {
		$reloads{"$imageids"} = [];
607
	    }
608 609
	    push(@{ $reloads{"$imageids"} }, $node);
	    $action = "reloaded with @images";
610 611 612 613 614 615 616 617 618
	}
	elsif ($op == $REBOOT) {
	    $reboots{$node_id} = $node;
	    $action = "rebooted";
	}
	elsif ($op == $RECONFIG) {
	    $reconfigs{$node_id} = $node;
	    $action = "reconfiged";
	}
619
	print STDERR "$node_id will be $action\n";
620 621 622
    }

    # XXX Caller wants a list. 
623
    return 0
624 625 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
	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
654
	    # will not be booting.  So for them, osload just sets up the
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
	    # 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;

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

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

690 691 692 693 694 695 696 697
	    $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);
698
	    $coderef = \&libosload::osload_wait;
699
	}
700
	push(@children, [ $pid, $coderef,
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
			  [ @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;
730
	$reboot_args{'rebootmode'} = $self->realreboot();
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
	$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;
750
	$reboot_args{'rebootmode'} = $self->realreboot();
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
	$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
795 796 797
	# Mark all of the failed nodes so that the caller knows there
	# was a failure. 
	# 
798 799
	foreach my $node_id (@nlist) {
	    my $node = $self->node($node_id);
Leigh Stoller's avatar
Leigh Stoller committed
800

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

    return scalar(@failed);
}

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

    # 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();
836 837
	my $typehandler = $node->_typehandler();
	
Leigh Stoller's avatar
Leigh Stoller committed
838 839 840 841 842 843 844 845 846 847 848
	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});
849 850
	$node->_setupstatus($RELOAD_FAILED);
	$typehandler->WaitDone($node);
Leigh Stoller's avatar
Leigh Stoller committed
851 852 853 854 855 856 857 858
    }

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

    #
    # 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;
883
	    my $state_timestamp;
Leigh Stoller's avatar
Leigh Stoller committed
884 885 886 887 888 889 890 891 892 893

	    #
	    # 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.
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
		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
917
	    }
918
	    if ($node->GetEventState(\$state, undef, \$state_timestamp)) {
Leigh Stoller's avatar
Leigh Stoller committed
919
		print STDERR "*** Error getting event state for $node_id.\n";
920
		$node->_setupstatus($SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
921 922 923 924 925 926
		delete($nodes{$node_id});
		$typehandler->WaitDone($node);
		next;
	    }
	    if (grep {$_ eq $state} @waitstates) {
		print "$node_id has reported state $state\n";
927 928 929 930 931 932
		if ($state eq TBDB_NODESTATE_ISUP()) {
		    $node->_setupstatus($SETUP_OKAY);
		}
		else {
		    $node->_setupstatus($SETUP_FAILED);
		}
Leigh Stoller's avatar
Leigh Stoller committed
933 934 935 936 937 938 939 940 941 942 943 944
		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");

945
		    $node->_setupstatus($SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
946 947 948 949 950
		    delete($nodes{$node_id});
		    $typehandler->WaitDone($node);
		}
		else {
		    if ($typehandler->Retry($node) != 0) {
951
			$node->_setupstatus($SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
952 953 954 955 956 957 958 959 960 961 962
			delete($nodes{$node_id});
			$typehandler->WaitDone($node);
		    }
		    else {
			$node->_retrycount($node->_retrycount() - 1);
			$node->_waitstart(time());
		    }
		}
		next;
	    }
	    if (int($waittime / 60) > $minutes) {
963 964
		# Changing minutes is why we get this print for just
		# a single node each time. 
Leigh Stoller's avatar
Leigh Stoller committed
965
		$minutes = int($waittime / 60);
966
		my $state_minutes = int((time() - $state_timestamp) / 60);
Leigh Stoller's avatar
Leigh Stoller committed
967
		tbnotice("Still waiting for $node_id ($state) - ".
968
			 "it's been $minutes/$state_minutes minute(s).\n");
Leigh Stoller's avatar
Leigh Stoller committed
969 970 971 972 973
	    }
	}
	sleep(5);
    }
    return 0;
974 975 976 977 978 979 980 981
}

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

    #
    # These special cases will eventually be encoded in the DB.
985
    # Note that type might be a class, and so Lookup() returns nothing.
986
    #
987
    my $typeinfo = NodeType->Lookup($type);
988
    my $packname = "libossetup_${type}";
989

990 991 992 993 994 995 996
    # Switches are special.
    if (defined($typeinfo) && $typeinfo->isswitch()) {
	eval "require libossetup_switch";
	if ($@) {
	    print STDERR "$self libossetup_switch load failed: " . $@;
	    return undef;
	}
997 998 999
	$packname = "libossetup_${type}";
	# Dashes in package names are bad.
	$packname =~ s/\-/\_/g;
1000 1001 1002
    }
    elsif (defined($typeinfo) && $typeinfo->issubnode()) {
	$type = "subnode";
1003
	$packname = "libossetup_subnode";
1004
    }
1005

1006 1007 1008
    my $newtype  = eval { $packname->New($self); };
    # Not loaded?
    if ($@) {
1009
	#print STDERR "module load failed: " . $@ . "\n";
1010
	eval "require $packname";
1011 1012 1013 1014 1015 1016
	if ($@) {
	    if ($@ !~ /Can't locate libossetup_/) {
		print STDERR "$self NewType($type): module load failed: " . $@;
	    }
	    return undef;
	}
1017 1018
	$newtype  = eval { $packname->New($self); };
	if ($@) {
1019
#	    print STDERR "$self NewType($type): New() failed: " . $@ . "\n"
1020
#		if ($self->debug());
1021 1022
	    return undef;
	}
1023 1024 1025
    }
    $self->{'TYPECACHE'}->{$type} = $newtype;
    
1026 1027
#    print STDERR "Created type object $type with parent $self\n"
#	if ($self->debug());
1028 1029 1030 1031 1032 1033
    
    return $newtype;
}
#
# Return the cached type object.
#
1034
sub TypeLookup($$)
1035 1036 1037
{
    my ($self, $node) = @_;

1038 1039 1040 1041 1042 1043
    my $type  = $node->type();
    my $class = $node->class();

    #
    # These special cases will eventually be encoded in the DB.
    #
1044 1045 1046 1047 1048 1049
    if ($type eq "pcfedphys" || $type eq "pcfed") {
	$type = "protogeni";
    }
    elsif ($node->issubnode()) {
	$type = "subnode";
    }
1050

1051 1052 1053 1054 1055
    return $self->{'TYPECACHE'}->{$type}
        if (exists($self->{'TYPECACHE'}->{$type}));

    return $self->{'TYPECACHE'}->{$class}
        if (exists($self->{'TYPECACHE'}->{$class}));
1056 1057 1058 1059 1060 1061 1062 1063

    return undef;
}

#
# Wrapper class for the type/class specific packages below.
#
package libossetup_handler;
1064
use base qw(libossetup);
1065 1066 1067 1068

use libdb;
use libtestbed;
use libossetup;
1069
use libtblog_simple;
1070 1071 1072
use Node;
use English;
use Data::Dumper;
1073
use overload ('""' => 'Stringify');
1074

1075 1076
use vars qw($AUTOLOAD);

1077 1078 1079 1080
sub New($$$)
{
    my ($class, $type, $parent) = @_;

Leigh Stoller's avatar
Leigh Stoller committed
1081 1082 1083 1084 1085 1086
    my $self             = {};
    $self->{'TYPE'}      = $type;
    $self->{'NODES'}     = {};
    $self->{'PARENT'}    = $parent;
    $self->{'FAILCOUNT'} = 0;
    $self->{'TODOLIST'}  = {};
1087 1088 1089 1090 1091 1092 1093

    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
1094
sub failcount($)	{ return $_[0]->{'FAILCOUNT'}; }
1095
sub nodelist($)         { return values(%{ $_[0]->{'NODES'} }); }
Leigh Stoller's avatar
Leigh Stoller committed
1096 1097 1098
sub todo($)		{ return $_[0]->{'TODOLIST'}; }
sub todolist($)		{ return values(%{ $_[0]->{'TODOLIST'} }); }
sub IncrFailCount($)    { $_[0]->{'FAILCOUNT'}++ }
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
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;
}

1117
#
Leigh Stoller's avatar
Leigh Stoller committed
1118
# Add a node to the list.
1119
#
Leigh Stoller's avatar
Leigh Stoller committed
1120
sub AddNode($$)
1121
{
Leigh Stoller's avatar
Leigh Stoller committed
1122 1123 1124 1125 1126 1127 1128
    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);
1129 1130

    #
Leigh Stoller's avatar
Leigh Stoller committed
1131 1132
    # This sets the OS that should boot, as well as any reloads, reboots
    # and reconfigs that are needed.
1133
    #
Leigh Stoller's avatar
Leigh Stoller committed
1134 1135
    $self->parent()->SetOS($node);
    return 0;
1136 1137 1138
}

#
Leigh Stoller's avatar
Leigh Stoller committed
1139 1140
# Stub function to light up a set of nodes; calls the big version in the
# parent.
1141
#
Leigh Stoller's avatar
Leigh Stoller committed
1142
sub LightUpNodes($@)
1143
{
Leigh Stoller's avatar
Leigh Stoller committed
1144
    my ($self, @nodelist)  = @_;
1145 1146
    my $parent = $self->parent();

Leigh Stoller's avatar
Leigh Stoller committed
1147 1148
    return $parent->LightUpNodes(@nodelist);
}
1149

Leigh Stoller's avatar
Leigh Stoller committed
1150 1151 1152 1153 1154 1155
#
# Return the set of nodes ready to go.
#
sub Volunteers($)
{
    my ($self) = @_;
1156

Leigh Stoller's avatar
Leigh Stoller committed
1157 1158 1159 1160 1161 1162 1163 1164 1165
    return $self->todolist();
}

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

    #
Leigh Stoller's avatar
Leigh Stoller committed
1168 1169
    # Return an error since this should not be called; it
    # should be overridden or the retry count always set to zero.
1170
    #
Leigh Stoller's avatar
Leigh Stoller committed
1171 1172
    return -1;
}
1173

Leigh Stoller's avatar
Leigh Stoller committed
1174 1175 1176 1177 1178 1179
#
# Generic wait for a single function.
#
sub WaitForNode($$)
{
    my ($self, $node) = @_;
1180

Leigh Stoller's avatar
Leigh Stoller committed
1181 1182 1183
    # Tell caller I have nothing to offer. 
    return 0;
}
1184

Leigh Stoller's avatar
Leigh Stoller committed
1185 1186 1187 1188 1189 1190
#
# Generic waitdone function.
#
sub WaitDone($@)
{
    my ($self, @nodelist) = @_;
1191 1192
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();
Leigh Stoller's avatar
Leigh Stoller committed
1193 1194 1195 1196 1197 1198 1199 1200 1201

    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});
1202 1203 1204 1205
    }
    return 0;
}

1206 1207 1208 1209 1210 1211 1212 1213 1214
#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $type = $self->type();

1215
    return "libossetup_$type";
1216 1217
}

1218 1219 1220 1221 1222 1223
#####################################################################
#
# Generic handler for local cluster nodes that do not require much
# special handling.
#
package libossetup_pc;
1224
use base qw(libossetup_handler);
1225 1226 1227 1228

use libdb;
use libtestbed;
use libossetup;
1229
use libtblog_simple;
1230 1231 1232
use Node;
use English;
use Data::Dumper;
1233
use overload ('""' => 'Stringify');
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257

#
# 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();
1258 1259
	# Need to initialize this for the stats code.
	$node->_bootosinfo(undef);
1260 1261 1262
	return 0;
    }

Leigh Stoller's avatar
Leigh Stoller committed
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    $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);
	}
1277
    }
Leigh Stoller's avatar
Leigh Stoller committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

    #
    # 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;
1290
    }
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    # 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
1312 1313
    $node->_retrycount(1);
    $node->_maxwait($waittime);
1314
    $node->_setupstatus($libossetup::SETUP_OKAY);
1315 1316 1317 1318

    return 0;
}

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

1365
#
Leigh Stoller's avatar
Leigh Stoller committed
1366
# Wait function signals some local cluster nodes are done waiting.
1367
#
Leigh Stoller's avatar
Leigh Stoller committed
1368
sub WaitDone($@)
1369
{
Leigh Stoller's avatar
Leigh Stoller committed
1370
    my ($self, @nodelist) = @_;
1371 1372 1373 1374
    my $parent     = $self->parent();
    my $experiment = $parent->experiment();
    my $pid        = $experiment->pid();
    my $eid        = $experiment->eid();
1375 1376 1377
    my $firewall;
    my $firewalled = $experiment->IsFirewalled(\$firewall);
    my $elabinelab = $experiment->elabinelab();
Leigh Stoller's avatar
Leigh Stoller committed
1378

1379
    #
Leigh Stoller's avatar
Leigh Stoller committed
1380
    # Must call the generic WaitDone handler too.
1381
    #
Leigh Stoller's avatar
Leigh Stoller committed
1382
    $self->SUPER::WaitDone(@nodelist);
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392
    #
    # 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);

1393
    #
Leigh Stoller's avatar
Leigh Stoller committed
1394
    # Then per node processing.
1395 1396
    #
    foreach my $node (@nodelist) {
1397 1398 1399
	my $node_id     = $node->node_id();
	my $setupstatus = $node->_setupstatus();
	my $eventstate  = $node->eventstate();
1400

1401
	if ($eventstate eq TBDB_NODESTATE_ISUP()) {
1402 1403 1404
	    print "$node_id is alive and well\n";
	    $node->SetBootStatus(NODEBOOTSTATUS_OKAY);
	    $node->SetAllocState(TBDB_ALLOCSTATE_RES_READY());
1405 1406 1407 1408
	    # 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);
1409

1410
	    if ($firewalled && $node_id eq $firewall) {
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
		#
		# 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);
		    }
		}
	    }
1432 1433 1434
	    next;
	}
	# Fall through on failure.	
1435
	if ($eventstate eq TBDB_NODESTATE_TBFAILED()) {
1436 1437 1438 1439 1440 1441 1442
	    tbwarn("$node_id reported a TBFAILED event\n");
	}
	else {
	    tbwarn("$node_id failed to boot\n");
	}
	$node->SetBootStatus(NODEBOOTSTATUS_FAILED);

1443 1444 1445
	#
	# If the firewall fails to boot, we are hosed. Quit right away.
	#
1446
	if ($firewalled && $node_id eq $firewall) {
1447 1448 1449 1450
	    tbnotice("Firewall failed to boot!\n");
	    $parent->aborted(1);
	}

1451
	#
1452
	# Handle non-fatal failures (if we have not been canceled or aborted).
1453
	#
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 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
	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;
		    }
		    # clear the reload info
		    $node->ClearCurrentReload();
		    # 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;
	    }
1505 1506
	}

1507
      bad:
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
	#
	# 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
1530 1531
	$self->IncrFailCount();
	$parent->IncrFailCount();
1532 1533 1534 1535 1536 1537
	if ($setupstatus == $libossetup::RELOAD_FAILED) {
	    $parent->add_failed_node_reload($node_id);
	}
	else {
	    $parent->add_failed_node_fatal($node_id);
	}
1538
    }
Leigh Stoller's avatar
Leigh Stoller committed
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
    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 $?;
1554 1555
}

1556 1557 1558 1559 1560 1561 1562
#####################################################################
package libossetup_pcRemote;
use base qw(libossetup_pc);

use libdb;
use libtestbed;
use libossetup;
1563
use libtblog_simple;
1564 1565 1566 1567 1568
use Node;
use English;
use Data::Dumper;
use overload ('""' => 'Stringify');

1569 1570
#####################################################################
#
Leigh Stoller's avatar
Leigh Stoller committed
1571 1572
# This is a wrapper for virtnodes; hopefully most virtnodes can share
# stuff.
1573
#
Leigh Stoller's avatar
Leigh Stoller committed
1574
package libossetup_virtnode;
1575
use base qw(libossetup_handler);
1576 1577 1578 1579

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

Leigh Stoller's avatar
Leigh Stoller committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
#
# 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
1609
	if (! ($node->jailflag() || $node->isremotenode()));
Leigh Stoller's avatar
Leigh Stoller committed
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

    $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);
1636 1637 1638 1639 1640
    # 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
1641
	&& $pnode->erole() ne "sharedhost") {
1642
	$pnode->AddTaintState(TB_TAINTSTATE_BLACKBOX) == 0 
Kirk Webb's avatar
Kirk Webb committed
1643
	    or die_noretry("Could not add blackbox taint state to vnode host!\n");
1644
    }
Leigh Stoller's avatar
Leigh Stoller committed
1645

1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    # 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
1659 1660 1661 1662 1663
    #
    # 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
1664
    # is rebooted normally (or starts when its physical node starts).
Leigh Stoller's avatar
Leigh Stoller committed
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    #
    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;
1676
	$reload_args{'imageid'}   = $image->versid();
Leigh Stoller's avatar
Leigh Stoller committed
1677 1678
	$reload_args{'nodelist'}  = [ $node_id ];

1679 1680 1681
	if (EmulabFeatures->FeatureEnabled("NewOsload",$self->user(),
					   $self->group(),
					   $self->experiment())) {
Leigh Stoller's avatar
Leigh Stoller committed
1682
	    ($parent->loadobj())->debug($parent->debug());	    
1683 1684 1685 1686 1687 1688

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

1689 1690 1691 1692 1693
	    ($parent->loadobj())->osload(\%reload_args, $reload_failures);
	}
	else {
	    osload(\%reload_args, $reload_failures)
	}
Leigh Stoller's avatar
Leigh Stoller committed
1694

1695
	# Reset this. Updated in Volunteers() below. 
Leigh Stoller's avatar
Leigh Stoller committed
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
	$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();
1711
    my @nodeids    = map { $_->node_id() } @nodelist;
Leigh Stoller's avatar
Leigh Stoller committed
1712 1713 1714

    tbnotice("Setting up virtual testbed nodes ...\n");
    TBDebugTimeStamp("vnode_setup starting");
1715
    system("$VNODESETUP -j $pid $eid @nodeids");
Leigh Stoller's avatar
Leigh Stoller committed
1716 1717 1718 1719
    my $exitval = $?;
    TBDebugTimeStamp("vnode_setup done");

    if ($exitval) {
1720 1721
	# This is very unusual.
	$parent->noretry(1);
Leigh Stoller's avatar
Leigh Stoller committed
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
	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.
    #
1739
    foreach my $node ($self->todolist()) {
Leigh Stoller's avatar
Leigh Stoller committed
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
	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.
	#
1765
	if ($reservation->SameExperiment($parent->experiment())) {
1766 1767 1768 1769 1770 1771 1772 1773
	    #
	    # 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
1774 1775 1776 1777
	    #
	    # If the node was rebooted, then we can determine if
	    # the vnode is dead, or worth waiting for.
	    #
1778
	    elsif ($pnode->_rebooted()) {
Leigh Stoller's avatar
Leigh Stoller committed
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
		#
		# Virtnodes automatically boot up, but we still have
		# to wait for them. 
		#
		if ($pnode->allocstate() eq TBDB_ALLOCSTATE_RES_READY()) {
		    #
		    # Set the allocstate for the local vnodes that were
		    # sucessfully rebooted and came to ISUP above. These do
		    # not need to be setup again. We move them to
		    # RES_READY, so vnode_setup will ignore them. If they
		    # fail to hit ISUP, we will move them to DOWN so that
		    # vnode_setup will ignore them again, in the teardown
		    # phase.
		    #
		    $node->SetAllocState(TBDB_ALLOCSTATE_RES_READY());
		    print "$node_id will boot up with $pnode_id\n"
			if ($parent->debug());
		}
		else {
		    #
		    # Something went wrong with the physnode reboot, so the
		    # virtnodes are DOA.
		    #
Leigh Stoller's avatar
Leigh Stoller committed
1802
		    $node->_setupstatus($libossetup::SETUP_FAILED);
Leigh Stoller's avatar
Leigh Stoller committed
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
		    $typehandler->WaitDone($node);
		    next;
		}
	    }
	    else {
		#
		# If the physnode was not rebooted, then the node is either
		# new and not processed yet, or it was an existing node and
		# swapmod was called with the no-reboot/reconfig option, in
		# which case we have to send the node through vnode_setup.
		#
		if ($pnode->allocstate() eq TBDB_ALLOCSTATE_RES_READY()) {
		    #
		    # Node is already part of the experiment and not
		    # going to be rebooted or reconfiged, so must go
		    # through vnode_setup, and it can happen now since the
		    # physnode is ready. 
		    #
		    print "$node_id needs vnode_setup\n"
			if ($parent->debug());

		    $node->_setupoperation($libossetup::REBOOT);
		}
		else {
		    print "Skipping $node_id this time around\n"
			if ($parent->debug());
1829
		    next;
Leigh Stoller's avatar
Leigh Stoller committed
1830 1831 1832 1833