libosload_switch.pm.in 59.5 KB
Newer Older
1 2 3 4

package libosload_switch;

use strict;
5
use libosload_new;
6 7 8 9 10 11 12 13 14 15

use base qw(libosload_common);
use vars qw($AUTOLOAD);

use libdb;
use libtestbed;
use libtblog;
use libreboot;
use Node;
use Group;
16
use Lan;
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
use English;
use IPC::Open3;
use POSIX ":sys_wait_h";
use Digest::SHA1 qw(sha1_hex);
use Data::Dumper;
#use overload ('""' => 'Stringify');
use File::Temp qw(tempfile);

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

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

    $self->{TIPTUNNELS} = {};

    return $self;
}

#
# IMPORTANT: this *has* to be here.  A simple glob like
#   *AUTOLOAD = \&libosload_common::AUTOLOAD;
# did not allow the module to dynamically load into libosload -- I had 
# to invoke AUTOLOAD in the parent class via $self.
#    return $self->SUPER::AUTOLOAD(@_);
# Actually, that didn't work either!  I had to have my own autoload sub.
#
sub AUTOLOAD {
    my $self = shift;
    my $type = ref($self) or die("$self is not an object\n");

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

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

#
# Configure stuff
#
my $TB		= "@prefix@";
my $TESTMODE    = @TESTMODE@;
my $TBOPS       = "@TBOPSEMAIL@";
my $SSHTB       = "$TB/bin/sshtb";
my $POWER       = "$TB/bin/power";
my $USERS       = "@USERNODE@";
my $BOSSNODE_IP = "@BOSSNODE_IP@";
my $USERNODE_IP = "@USERNODE_IP@";
my $OURDOMAIN   = "@OURDOMAIN@";
my $CONTROL_NETMASK = "@CONTROL_NETMASK@";
my $CONTROL_ROUTER_IP = "@CONTROL_ROUTER_IP@";

#
# Constants
#
my $LSZ   = "/usr/local/bin/lsz";
# NOTE: console on boss is a wrapper for console/tiptunnel that handles
# grabbing the ACL file, permissions checking, various args!  We specify
# tiptunnel mode via -t, and either set speed or go interactive below as
# necessary.
my $TIPCMD = "$TB/bin/console -t";
my $DEFSPEED = 9600;

my $FAIL_ON_SPEEDSET = 1;

my $TMPDIR = "/tmp";

#
# Console interaction vars
#
# what to send to produce output on console -- interrupt char
my $tchar = chr(0x03);
# prompt regexp
my $prompt = '((=>)|(#))';
# speeds to search at
my @speeds = (9600,115200); # ,14400,19200,28800,38400,57600,76800,230400);
# expect sequences
my %sequences = 
    ( 'bootToRom' => 
      { 'timeout' => 30*5,
	'seq' => [ [ 'Select profile.*:\s*$', '0', 'line' ],
		   [ '=>', undef, 'line'] ] },
      'bootToPrimary' =>
      { 'timeout' => 30*5,
	'seq' => [ [ 'Select profile.*:\s*$', '1', 'line' ],
		   [ '=>', undef, 'line'] ] },
      'bootToSecondary' =>
      { 'timeout' => 30*5,
	'seq' => [ [ 'Select profile.*:\s*$', '2', 'line' ],
		   [ '=>', undef, 'line'] ] },
      'bootFromRomToPrimary' =>
      { 'timeout' => 5,
	'presend' => $tchar,
	'seq' => [ [ $prompt,"jp 1\n",'line' ] ] },
      'bootIntoOS' =>
      { 'timeout' => 120,
	'seq' => [ [ 'Waiting for Speed Sense.  Press \<Enter\> twice to continue.', 
		     sub { my $chin = shift; 
			   sleep(4); 
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
		     }, 'line' ],
		   [ 'Press any key to continue', "\n", 'line' ],
		   [ '#\s*', undef, 'line' ] ] },
      # we have to give the switch time to reload
      'bootAfterLoad' =>
      { 'timeout' => 30*5,
	'seq' => [ [ 'Waiting for Speed Sense.  Press \<Enter\> twice to continue.', 
		     sub { my $chin = shift; 
			   sleep(4); 
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
			   sleep(4); syswrite($chin,"\r");
		     }, 'line' ],
		   [ 'Press any key to continue', "\n", 'line' ],
		   [ '#\s*', undef, 'line' ] ] },
      'reboot' =>
      { 'timeout' => 300,
	'presend' => $tchar,
	'seq' => [ [ '((#\s+)|(=>))$', "boot\n", 'line' ] ] },
      'rebootContinue' =>
      { 'timeout' => 300,
	'presend' => $tchar,
	'seq' => [ [ '((#\s+)|(=>))$', "boot\n", 'line' ],
154
		   [ '(C|c)ontinue (\(|\[)y\/n(\)|\])\?\s*$', "y", 'line' ] ] },
155 156 157 158
      'rebootContinueOpt' =>
      { 'timeout' => 5,
	'presend' => $tchar,
	'seq' => [ [ '((#\s+)|(=>))$', "boot\n", 'line' ],
159 160
		   [ '(C|c)ontinue (\(|\[)y\/n(\)|\])\?\s*$', "y", 'line' ],
		   [ 'save current configuration (\(|\[)y\/n(\)|\])\s*$?', 'y', 'line' ] ] },
161 162 163 164 165
      # just drain, send nothing.
      'drain' =>
      { 'timeout' => 10,
	'drain' => 1,
	'seq' => [  ] },
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
      # do stuff before and after we kick off xmodem
      'initxmodem' =>
      { 'timeout' => 30,
	'presend' => $tchar,
	'seq' => [ [ '=>\s*$', "do\n", 'line' ],
		   [ 'continue\? \(Y\/N\)>\s*$', "Y\n", 'line' ] ] },
      'finishxmodem' =>
      { 'timeout' => 60*5,
	'seq' => [ [ 'Download for this Product\, proceeding', undef, 'line' ],
		   [ 'pass CRC check', undef, 'line' ],
		   [ 'Ready for code execution', undef, 'line' ],
		   [ 'Select profile.*:\s*$', '1', 'line' ] ] },
      # make it be raw instead of using escape sequences!
      'godumb' =>
      { 'timeout' => 30,
	'presend' => $tchar,
	'seq' => [ [ '#\s+', "configure terminal\n", 'line' ],
		   [ '#\s+', "no page\n", 'line' ],
		   [ '#\s+', "console local-terminal none\n", 'line' ],
		   # must write memory so we don't get prompted to save
		   [ '#\s+', "write memory\n", 'line' ],
		   [ '#\s+', undef, 'line' ] ] },

    );

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

    my $retval = $self->SUPER::AddNode($nodeobject,$imagelist,$args);

    #
    # Never force node reloads -- only reload if new/old image is actually
199
    # different.  So, if they haven't set a force flag, default it 0.
200 201 202 203
    #
    if (!defined($self->nodeflag($nodeobject,'force'))) {
	$self->nodeflag($nodeobject,'force',0);
    }
204 205 206 207 208

    #
    # We never allow switches to be rebooted -- we control that ourselves.
    # Power cycling during a flash operation could be disastrous.
    #
209 210
    $self->nodeflag($nodeobject,'noreboot',1);

211 212 213 214 215 216 217 218 219 220 221 222
    #
    # Set default values for dotftp and doxmodem if the user didn't set
    # them.  Basically these let callers directly influence whether tftp
    # and/or xmodem are invoked to handle the reload.
    #
    if (!defined($self->nodeflag($nodeobject,'dotftp'))) {
	$self->nodeflag($nodeobject,'dotftp',1);
    }
    if (!defined($self->nodeflag($nodeobject,'doxmodem'))) {
	$self->nodeflag($nodeobject,'doxmodem',0);
    }

223 224 225 226 227 228 229 230
    return $retval;
}

sub GetMaxRetries($)
{
    return 0;
}

231
sub PreSetupReload($$)
232 233 234 235 236 237 238
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

    my @images = @{$self->GetImages($nodeobject)};
    my $newimageid = $images[0]->imageid();
    my $newpart = $images[0]->loadpart();
239
    my $newosid = $images[0]->default_osid();
240 241 242 243 244 245 246 247 248

    #
    # Grab the existing partitions first, THEN overwrite them!
    # We need to see if we're going to have to do a reload or not, unless
    # we've already been told to force one!
    # So, if our image and osid are in the table already, don't load;
    # otherwise set the force-load flag ourselves!
    #
    if (!$self->nodeflag($nodeobject,'force')) {
249 250
	my $qres = DBQueryWarn("select * from `partitions`".
			       " where node_id='$node_id' and `partition`=$newpart");
251 252 253 254 255
	if (!$qres->numrows()) {
	    tbinfo "$self PreSetupReload($node_id): forcing reload; nothing in partitions table for this node\n";
	    $self->nodeflag($nodeobject,'force',1);
	}

256 257 258 259
	while (my $rowref = $qres->fetchrow_hashref()) {
	    if ($rowref->{partition} == $newpart) {
		if ($newimageid == $rowref->{imageid}
		    && $newosid == $rowref->{osid}) {
260
		    tbinfo "$self PreSetupReload($node_id): not forcing reload because new and current images are the same!\n";
261 262 263
		    return 0;
		}
		else {
264
		    tbinfo "$self PreSetupReload($node_id): forcing reload because new and current images are different!\n";
265 266 267 268 269 270 271 272
		    $self->nodeflag($nodeobject,'force',1);
		}

		last;
	    }
	}
    }

273 274 275 276 277
    #
    # We have to check to see if the user can really do a reload -- if not,
    # we have to bail, unfortunately!  It's unfortunate because we have now 
    # failed the swapin when we probably should detect it much sooner.
    #
278
    if ($self->nodeflag($nodeobject,'force')) {
279 280 281 282 283 284 285 286 287 288 289 290
	if (!EmulabFeatures->FeatureEnabled("SwitchFlash",
					    $self->nodeflag($nodeobject,'user'),
					    $self->nodeflag($nodeobject,'group'),
					    $self->nodeflag($nodeobject,'experiment'))) {
	    tberror "$self PreSetupReload($node_id): you do not have permission to flash switches!\n";
	    return -1;
	}
	require libosload_new;
	# XXX -- @nodelist
	$self->loadobj(libosload_new->New());
    }

291 292 293 294
    #
    # If we're really gonna do it, then save our state so we can restore
    # if it seems like our load failed.
    #
295
    if ($self->nodeflag($nodeobject,'force')) {
296 297 298 299 300 301 302 303 304 305 306
	$self->SaveNodeDiskInfo($nodeobject);
    }

    return $self->SUPER::PreSetupReload($nodeobject);
}

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

307
    if ($self->nodeflag($nodeobject,'force')) {
308 309 310 311 312 313 314 315 316 317 318 319 320 321
	return $self->SUPER::UpdatePartitions($nodeobject);
    }

    return 0;
}

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

    my @images = @{$self->GetImages($nodeobject)};
    my $newimageid = $images[0]->imageid();
    my $newpart = $images[0]->loadpart();
322
    my $newosid = $images[0]->default_osid();
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360

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

    if ($newpart > 1) {
	tberror "$self ($node_id): switches can load only into first partition!";
	return -1;
    }

    #
    # Unless we've been told to force a load, check the partitions table, see
    # what's loaded already; if our image and osid and on there, don't load;
    # otherwise set the force-load flag ourselves!
    #
    if (!$self->nodeflag($nodeobject,'force')) {
	tbinfo "$self SetupReload($node_id): not forcing reload!\n";
	return 0;
    }

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

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

    return 0;
}

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

361
    $self->dprint(0,"SetupReconfigure($node_id): putting switch in SHUTDOWN");
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    #
    # The switch goes 'down', then starts to reconfigure.
    #
    # NOTE: we *have* to do this here before any parents start polling on
    # us being in ISUP, so we can't rely on Reconfgiure taking care of this.
    # Like SetupReload, this operation should happen in the parent process
    # before allowing Reconfigure to spawn a child.
    #
    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);

    return 0;
}

sub _doTiptunnel($$;$)
{
    my ($self,$nodeobject,$tipref) = @_;
    my $node_id = $nodeobject->node_id();
    my %tiphash = ();

    if (defined($tipref)) {
	# just use it -- maybe it came from another reload, reboot, or reconfig
	$self->tipinfo($nodeobject,$tipref);
	return $tipref;
    }

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

    # XXX do later!
392
    #$self->dprint(0,"_doTipTunnel($node_id): forcing capture reset!");
393 394
    #system("${CONSOLE_RESET} $node_id");

395
    $self->dprint(0,"_doTipTunnel($node_id): opening console connection");
396 397 398 399 400 401 402 403 404

    my ($chin,$chout,$cherr);
    my $tippid = open3($chout,$chin,$cherr,"$TIPCMD " . $node_id);

    #
    # Install a signal handler so we can catch PIPEs without dying.
    #
    $SIG{PIPE} = sub {
	my $signo = shift;
405
	tbwarn "$self _doTipTunnel($node_id): reload tiptunnel exited" . 
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
	    " unexpectedly with SIG$signo!\n";
	return 0;
    };

    %tiphash = ( 'in' => $chin, 'out' => $chout, 'err' => $cherr,
		 'pid' => $tippid, 'linehist' => [], 'databuf' => '' );

    # save it off
    $self->{TIPTUNNELS}->{$node_id} = \%tiphash;

    return \%tiphash;
}

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

    return -1
	if (!exists($self->{TIPTUNNELS}->{$node_id}));

    my $tippid = $self->{TIPTUNNELS}->{$node_id}->{pid};

    # don't catch these when we kill our tiptunnel child
    $SIG{PIPE} = 'IGNORE';

433
    $self->dprint(0,"_undoTiptunnel($node_id): killing tiptunnel");
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

    # try to kill tiptunnel
    kill(1,$tippid);
    sleep(1);
    $retval = waitpid($tippid,WNOHANG);
    sleep(1);
    if ($retval <= 0) {
	kill(9,$tippid);
	sleep(1);
	$retval = waitpid($tippid,WNOHANG);
    }
    # and finally remove this guy!
    delete $self->{TIPTUNNELS}->{$node_id};

    return 0;
}

sub Reconfigure($$;$)
{
    my ($self,$nodeobject,$dowait) = @_;
    my $node_id = $nodeobject->node_id();
    my $retval;
456 457
    
    $self->dprint(0,"Reconfigure($node_id): starting");
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

    # By default, don't create a child
    if (!defined($dowait)) {
	$dowait = 1;
    }

    # Our return code: defaults to fail; only succeeds near end
    my $rc = -1;

    #
    # This 1) wipes the current configuration from within the ROM monitor, and
    # 2) boots into teh OS and writes a new configuration
    #

    #
    # For now, we allow Reconfigure to block -- it will be called from Reload
    # or from ossetup... so no need to spawn more children!
    #
    if (!$dowait) {
	if (defined($self->nodeinfo($nodeobject,'reloadchildpid'))) {
	    tberror "$self Reconfigure($node_id): already a reload in progress?\n";
	    return -1;
	}

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

    # child continues:

495
    $self->dprint(2,"Reconfigure($node_id): child setting state to SHUTDOWN");
496 497
    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);

498
    $self->dprint(2,"Reconfigure($node_id): trying to generate config first");
499
    my @config = $self->generateConfig($nodeobject);
500 501 502
    if (!@config) {
 	tberror "$self Reconfigure($node_id): could not generate config!\n";
 	return -1;
503 504 505 506 507 508 509 510 511
    }
    if (!defined($self->_doTiptunnel($nodeobject))) {
	tberror "$self Reconfigure($node_id): could not get tiptunnel info!\n";
	return -1;
    }

    # get set for any potential power cycles
    my %reboot_args     = ();
    $reboot_args{'debug'}    = $self->debug();
512
    $reboot_args{'waitmode'} = 0;
513 514
    $reboot_args{'nodelist'} = [ $node_id ];
    $reboot_args{'powercycle'} = 1;
515
    $reboot_args{'force'}    = 1;
516

517 518 519
    #
    # First, get the switch to respond on console.
    #
520 521 522 523 524 525
    $retval = $self->probeForOutput($nodeobject);
    my $rebooting = 0;
    if ($FAIL_ON_SPEEDSET && $retval < 0) {
	goto failure;
    }
    elsif ($retval == 2) {
526
	$self->dprint(1,"Reconfigure($node_id): switch already in OS, attempting reboot");
527 528 529 530 531 532 533

	if ($self->expect($nodeobject,undef,undef,
			  $sequences{'godumb'}) < 0) {
	    tbwarn "$self Reconfigure($node_id): could not set dumb mode; continuing anyway!\n"
		if ($self->debug());
	}

534
	$self->dprint(1,"Reconfigure($node_id): trying console reboot");
535 536
	if ($self->expect($nodeobject,undef,undef,
			  $sequences{'rebootContinue'}) < 0) {
537 538 539 540 541 542 543 544 545 546 547 548 549
	    if (defined($self->nodeinfo($nodeobject,'flashing'))
		&& !$self->nodeinfo($nodeobject,'flashing')) {
		tbwarn "$self Reconfigure($node_id): console reboot failed; power cycling!\n";

		my %reboot_failures = ();
		if (nodereboot(\%reboot_args,\%reboot_failures)) {
		    # && exists($reboot_failures{$node_id})) {
		    tberror "$self Reconfigure($node_id): power cycle failed!\n";
		    goto failure;
		}
	    }
	    else {
		tberror "$self Reconfigure($node_id): console reboot failed and cannot power cycle (maybe still flashing)\n";
550 551 552 553 554 555 556 557 558 559 560
		goto failure;
	    }
	}
	$rebooting = 1;
    }
    elsif ($retval == 1) {
	# already in ROM monitor
	;
    }
    elsif ($retval <= 0) {
	# have to reboot -- no other choice
561 562 563
	if (defined($self->nodeinfo($nodeobject,'flashing'))
	    && !$self->nodeinfo($nodeobject,'flashing')) {
	    $self->dprint(0,"Reconfigure($node_id): could not obtain output on switch; rebooting!");
564

565 566 567 568 569 570 571 572 573
	    my %reboot_failures = ();
	    if (nodereboot(\%reboot_args,\%reboot_failures)) {
		#&& exists($reboot_failures{$node_id})) {
		tberror "$self Reconfigure($node_id): power cycle failed!\n";
		goto failure;
	    }
	}
	else {
	    tberror "$self Reconfigure($node_id): could not obtain output on switch and cannot reboot (possibly flashing)!\n";
574 575 576 577 578
	    goto failure;
	}
	$rebooting = 1;
    }

579
    $self->dprint(1,"Reconfigure($node_id): child setting state to BOOTING");
580 581 582 583 584 585 586 587 588
    TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);

    #
    # Ok, if we're rebooting, we have to wait...
    #
    if ($rebooting) {
	# reset capture speed to default
	$self->setSpeed($nodeobject,$DEFSPEED);

589
	$self->dprint(1,"Reconfigure($node_id): running bootToRom");
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
	if (($retval = $self->expect($nodeobject,undef,undef,
				     $sequences{'bootToRom'})) < 0) {
	    # XXX retry?
	    tberror "$self Reconfigure($node_id): could not enter ROM monitor after reboot! ($retval, $!)\n";
	    goto failure;
	}
    }

    # now that we're in the ROM monitor, we clear the configs:
    $retval = $self->wipeFiles($nodeobject);
    if ($retval < 0) {
	tberror "$self Reconfigure($node_id): could not wipe old switch data files: $retval,$!\n";
	goto failure;
    }

    # Boot the node from the ROM monitor to the primary flash slot OS
606
    $self->dprint(1,"Reconfigure($node_id): booting into OS");
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
    $retval = $self->expect($nodeobject,undef,undef,
			    $sequences{'bootFromRomToPrimary'});
    if ($retval < 0) {
	# XXX retry?
	tberror "$self Reconfigure($node_id): could not boot into OS from ROM monitor ($retval, $!)\n";
	goto failure;
    }
    $retval = $self->expect($nodeobject,undef,undef,
			    $sequences{'bootIntoOS'});
    if ($retval < 0) {
	# XXX retry?
	tberror "$self Reconfigure($node_id): could not boot into OS from ROM monitor ($retval, $!)\n";
	goto failure;
    }

    if ($self->expect($nodeobject,undef,undef,
		      $sequences{'godumb'}) < 0) {
	tbwarn "$self Reconfigure($node_id): could not set dumb mode; continuing anyway!\n"
	    if ($self->debug());
    }

    # now write the config
    $retval = $self->writeConfig($nodeobject,\@config);
    if ($retval < 0) {
	tberror "$self Reconfigure($node_id): could not write new config: $retval,$!\n";
	goto failure;
    }

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

    # Success!
    $rc = 0;
    goto done;

  failure:
    #TBSetNodeEventState($node_id,TBDB_NODESTATE_ISUP);
    ;

  done:
    # and finally remove this guy!
    $self->_undoTiptunnel($nodeobject);
    # only exit if we created a child
    if (!$dowait) {
653
	$self->dprint(1,"Reconfigure($node_id): exiting with $rc");
654 655
	exit $rc;
    }
656
    $self->dprint(0,"Reconfigure($node_id): returning $rc");
657 658 659 660 661 662 663 664
    return $rc;
}

sub Reload($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();
    my $retval;
665
    my $didflash = 0;
666 667 668 669 670 671

    # Our return code: defaults to fail; only succeeds near end
    my $rc = -1;

    my @images = @{$self->GetImages($nodeobject)};
    my $imageid = $images[0]->imageid();
672 673
    my $filename = $images[0]->path();
    my $osid = $images[0]->default_osid();
674 675 676 677 678 679 680 681 682

    if (defined($self->nodeinfo($nodeobject,'reloadchildpid'))) {
	tberror "$self Reload($node_id): is a reload already in progress?\n";
	return -1;
    }

    if (!((defined($self->nodeflag($nodeobject,'force'))
	   && $self->nodeflag($nodeobject,'force'))
	  || $self->nodeflag($nodeobject,'reconfig'))) {
683 684 685 686 687 688
	tbinfo "$self Reload($node_id): no reload or reconfig to do, simulating reloaddone instead!\n";

	#
	# BUT -- we need to simulate it from stated's perspective so that 
	# the reloads table is cleared.
	#
689 690 691 692
	TBSetNodeNextOpMode($node_id,TBDB_NODEOPMODE_RELOADPUSH);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
	# give stated time to change op modes
	sleep(4);
693 694 695
	TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADSETUP);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADDONE);
696 697 698
	# reset to teh op mode of the loaded image.
	$nodeobject->Refresh();
	$nodeobject->ResetNextOpMode($self->debug());
699 700 701 702
	TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_ISUP);

703 704 705
	return 0;
    }

706 707
    $self->dprint(0,"Reload($node_id): starting");

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    #
    # Reload can't block, so fork and make a note of ourself!
    #
    my $childpid = $self->ChildCreate([]);
    if ($childpid) {
	# parent:
	$self->nodeinfo($nodeobject,'reloadchildpid',$childpid);
	return 0;
    }

    # child continues:

    if (!defined($self->nodeflag($nodeobject,'force'))
	|| !$self->nodeflag($nodeobject,'force')) {
	if ($self->nodeflag($nodeobject,'reconfig')) {
723 724 725 726 727 728
	    tbinfo "$self Reload($node_id): jumping straight to Reconfigure after simulating unnecessary reload\n";

	    #
	    # BUT -- we need to simulate it from stated's perspective so that 
	    # the reloads table is cleared.
	    #
729 730 731 732
	    TBSetNodeNextOpMode($node_id,TBDB_NODEOPMODE_RELOADPUSH);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
	    # give stated time to change op modes
	    sleep(4);
733 734
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADSETUP);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);
735 736 737

	    $rc = $self->Reconfigure($nodeobject);

738
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADDONE);
739 740 741
	    # reset to teh op mode of the loaded image.
	    $nodeobject->Refresh();
	    $nodeobject->ResetNextOpMode($self->debug());
742
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
743 744
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_ISUP);
745

746 747 748 749
	    goto done;
	}
    }

750
    $self->dprint(1,"Reload($node_id): child setting state to RELOADSETUP");
751 752 753 754
    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADSETUP);

    if (!defined($self->_doTiptunnel($nodeobject))) {
	tberror "$self Reload($node_id): could not get tiptunnel info!\n";
755 756
	$rc = -1;
	goto failure;
757 758 759 760 761
    }

    # get set for any potential power cycles
    my %reboot_args     = ();
    $reboot_args{'debug'}    = $self->debug();
762
    $reboot_args{'waitmode'} = 0;
763 764
    $reboot_args{'nodelist'} = [ $node_id ];
    $reboot_args{'powercycle'} = 1;
765
    $reboot_args{'force'}    = 1;
766 767 768

    my $rebooting = 0;
    my $doreboot = 0;
769 770 771 772 773 774 775 776 777 778 779 780
    my $dotftp = $self->nodeflag($nodeobject,'dotftp');
    my $doxmodem = $self->nodeflag($nodeobject,'doxmodem');

    #
    # First, get the switch to respond on console.
    #
    $retval = $self->probeForOutput($nodeobject);
    # if it times out, or the prompt is not found, just whack it
    if ($retval == -3 || $retval == -1) {
	$doreboot = 1;
    }
    elsif ($retval < 0) {
781 782 783
	goto failure;
    }
    elsif ($retval == 2) {
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
	if ($dotftp) {
	    # If we want tftp, we want to stay in the OS!
	    $self->dprint(1,"Reload($node_id): switch already in OS");
	}
	elsif ($doxmodem) {
	    # If we want xmodem, we have to reboot into the ROM monitor
	    $self->dprint(1,"Reload($node_id): switch already in OS, rebooting to ROM monitor");
	    my $seqnum;
	    if ($self->expect($nodeobject,undef,undef,
			      $sequences{'rebootContinueOpt'},\$seqnum) < 0
		&& $seqnum < 1) {
		tbwarn "$self Reload($node_id): reboot to ROM monitor failed; power cycling!\n"
		    if ($self->debug());
		$doreboot = 1;
	    }
	    else {
		$rebooting = 1;
	    }
	}
803 804
    }
    elsif ($retval == 1) {
805 806 807 808 809 810 811 812 813 814 815 816 817
	if ($dotftp) {
	    # Boot the node from the ROM monitor to the primary flash slot OS
	    $self->dprint(0,"Reload($node_id): booting into OS");
	    $retval = $self->expect($nodeobject,undef,undef,
				    $sequences{'bootFromRomToPrimary'});
	    if ($retval < 0) {
		tbwarn "$self Reload($node_id): console reboot failed; power cycling!\n"
		    if ($self->debug());
		$doreboot = 1;
	    }
	    else {
		$rebooting = 1;
	    }
818
	}
819 820 821
	elsif ($doxmodem) {
	    # If we want xmodem, we want to stay in the ROM monitor!
	    $self->dprint(1,"Reload($node_id): switch already in ROM monitor");
822 823 824 825 826 827
	}
    }
    elsif ($retval <= 0) {
	$doreboot = 1;
    }

828
    # we're going to try to reboot
829
    if ($doreboot) {
830
	$self->dprint(1,"Reload($node_id): power cycling!");
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849

	my %reboot_failures = ();
	if (nodereboot(\%reboot_args,\%reboot_failures)) {
	    #&& exists($reboot_failures{$node_id})) {
	    tberror "$self ($node_id): power cycle failed!\n";
	    goto failure;
	}
	$rebooting = 1;
	# reset for next use
	$doreboot = 0;
    }

    #
    # Ok, if we're rebooting, we have to wait...
    #
    if ($rebooting) {
	# reset capture speed to default
	$self->setSpeed($nodeobject,$DEFSPEED);

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
	if ($dotftp) {
	    $self->dprint(1,"Reload($node_id): running bootIntoOS");
	    if (($retval = $self->expect($nodeobject,undef,undef,
					 $sequences{'bootIntoOS'})) < 0) {
		# XXX retry?
		tberror "$self Reload($node_id): could not enter OS for tftp load! ($retval, $!)\n";
		goto failure;
	    }
	}
	elsif ($doxmodem) {
	    # Boot the node into the ROM monitor
	    $self->dprint(0,"Reload($node_id): booting into ROM monitor");
	    $retval = $self->expect($nodeobject,undef,undef,
				    $sequences{'bootToRom'});
	    if ($retval < 0) {
		tberror "$self Reload($node_id): could not enter ROM monitor for xmodem load! ($retval, $!)\n";
		goto failure;
	    }
868 869 870
	}
    }

871 872 873 874 875 876 877
    # If we need to get to the OS, get rid of all the terminal junk.
    if ($dotftp) {
	if ($self->expect($nodeobject,undef,undef,
			  $sequences{'godumb'}) < 0) {
	    tbwarn "$self Reload($node_id): could not set dumb mode; continuing anyway!\n"
		if ($self->debug());
	}
878 879 880
    }

    #
881
    # Ok, we're in either the OS (try tftp) or ROM monitor (try xmodem)!
882 883
    #

884
    $self->dprint(1,"Reload($node_id): child setting state to RELOADING");
885 886
    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);

887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    if ($dotftp) {
	$retval = $self->uploadImageTftp($nodeobject,$filename,\$didflash);
	if ($didflash) {
	    $self->nodeinfo($nodeobject,'flashing',1);
	}
	if ($retval < 0) {
	    if (defined($self->nodeinfo($nodeobject,'osload_allowxmodem'))
		&& $self->nodeinfo($nodeobject,'osload_allowxmodem')) {
		tbwarn "$self Reload($node_id): tftp failed; trying xmodem\n";
		# XXX xmodem
		goto failure;
	    }
	    else {
		tberror "$self Reload($node_id): could not upload new image via tftp: $retval,$!\n";
		goto failure;
	    }
903 904
	}
	else {
905 906 907 908 909 910
	    # reboot!
	    if (($retval = $self->expect($nodeobject,undef,undef,
					 $sequences{'rebootContinue'})) < 0) {
		tberror "$self Reload($node_id): could not reboot into new image: $retval,$!\n";
		goto failure;
	    }
911 912
	}
    }
913 914 915 916 917 918 919
    if ($doxmodem) {
	$retval = $self->uploadImageXmodem($nodeobject,$filename,\$didflash);
	if ($didflash) {
	    $self->nodeinfo($nodeobject,'flashing',1);
	}
	if ($retval < 0) {
	    tberror "$self Reload($node_id): could not upload new image via xmodem: $retval,$!\n";
920 921 922 923 924 925 926 927 928 929 930
	    goto failure;
	}
    }

    # We're rebooting, so reset our capture's speed to the switch's default
    $self->setSpeed($nodeobject,$DEFSPEED);

    #
    # If we're going to do a reconfig too, stop in the ROM monitor so that
    # Reconfigure can wipe the current configs.
    #
931 932 933 934
    if ((defined($self->nodeflag($nodeobject,'reconfig')) 
	 && $self->nodeflag($nodeobject,'reconfig'))
	|| (defined($self->nodeflag($nodeobject,'reconfig_will_follow')) 
	    && $self->nodeflag($nodeobject,'reconfig_will_follow'))) {
935
	$self->dprint(1,"Reload($node_id): running bootToRom after load");
936 937 938 939 940 941 942 943 944 945 946 947
	if (($retval = $self->expect($nodeobject,undef,undef,
				     $sequences{'bootToRom'})) < 0) {
	    # XXX retry?
	    tberror "$self Reload($node_id): could not enter ROM monitor after reload! ($retval, $!)\n";
	    goto failure;
	}
    }
    #
    # Otherwise, just boot straight into the OS -- and if we did a load, wait
    # more time!
    #
    else {
948
	$self->dprint(1,"Reload($node_id): running bootIntoOS after reload");
949 950 951 952 953 954 955 956 957 958 959 960 961
	if (($retval = $self->expect($nodeobject,undef,undef,
				     $sequences{'bootIntoOS'})) < 0) {
	    # XXX retry?
	    tberror "$self Reload($node_id): could not enter OS after reload! ($retval, $!)\n";
	    goto failure;
	}
    }

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

962 963
    my $osinfo = OSinfo->Lookup($osid);
    if ($nodeobject->OSSelect($osinfo,"def_boot_osid",$self->debug())) {
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
	tberror "$self ($node_id): os_select $osid failed!";
	goto failure;
    }

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

    # Success!
    $rc = 0;

    #
    # If we're supposed to push a new config too, do that.
    #
    if ($self->nodeflag($nodeobject,'reconfig')) {
985
	$self->dprint(1,"Reload($node_id): doing reconfig after reload");
986 987 988 989 990 991 992 993 994 995 996
	$rc = $self->Reconfigure($nodeobject);
    }
    else {
	#
	# Make sure the node hits ISUP
	#
	#TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);
    }
	

  failure:
997 998 999 1000
    if (!$didflash) {
	$self->RestoreNodeDiskInfo($nodeobject);
    }

1001 1002 1003 1004
  done:
    # and finally remove this guy!
    $self->_undoTiptunnel($nodeobject);
    # yes, this assumes we create a child!
1005
    $self->dprint(0,"Reload($node_id): exiting with $rc");
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    exit $rc;
}

#
# Helper function defs
#
sub setSpeed($$$) {
    my ($self,$nodeobject,$speed) = @_;
    my $nodeid = $nodeobject->node_id();

    if (!defined($speed)) {
	return 1;
    }

    my $retval = system("$TIPCMD -s $speed $nodeid");
    #
    # if system throws us an error, we need to catch it!
    #
    if ($retval != -1) {
	$retval = $retval >> 8;
    }

1028
    $self->dprint(3,"setSpeed($nodeid): flipped speed to $speed, pausing briefly");
1029 1030

    select(undef,undef,undef,0.50);
1031
    $self->dprint(3,"setSpeed($nodeid): done with status $retval");
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

    return $retval;
}

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

    #
    # See if we can get some output from the switch by sending it interrupts
    # until we get a prompt.  If interrupts don't work, we also send it
    # a series of <ENTER> chars, because the switch speed sense detection
    # requires that and will not response to interrupt chars.  One of these two 
    # sequences *should* generate something on console if the switch is alive.
    #
    my $sfound = 0;
    my $retval;
    my $sspeed;
    my @linehist = ();

    my $tipref = $self->_doTiptunnel($nodeobject);
    my ($chin,$chout,$cherr) = 
	($tipref->{'in'},$tipref->{'out'},$tipref->{'err'});

1056
    $self->dprint(0,"probeForOutput($node_id): starting probing");
1057

1058
    $self->dprint(2,"probeForOutput($node_id): probing via current/INT");
1059 1060 1061 1062 1063 1064 1065 1066 1067
    # try current speed
    $retval = $self->expect($nodeobject,\@linehist,undef,
			    { 'timeout' => 2,
			      'presend' => $tchar,
			      'seq' => [ [ $prompt,undef,'line' ] ] });
    # flip through speeds
    if ($retval < 0) {
	foreach my $speed (@speeds) {
	    @linehist = ();
1068
	    $self->dprint(2,"probeForOutput($node_id): probing via $speed/INT");
1069
	    if ($self->setSpeed($nodeobject,$speed)) {
1070 1071 1072 1073 1074 1075 1076 1077
		if ($FAIL_ON_SPEEDSET) {
		    tberror "$self probeForOutput($node_id): setSpeed failed with $!\n";
		    $retval = -4;
		    last;
		}
		else {
		    tbwarn "$self probeForOutput($node_id): setSpeed failed with $!\n";
		}
1078 1079 1080 1081 1082 1083 1084 1085
	    }
	    else {
		# try the interrupt char option
		$retval = $self->expect($nodeobject,\@linehist,undef,
					{ 'timeout' => 2,
					  'presend' => $tchar,
					  'seq' => [ [ $prompt,undef,'line' ] ] });
		if ($retval < 0) {
1086
		$self->dprint(2,"probeForOutput($node_id): probing via $speed/ENTER");
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
		    # try the <ENTER> option
		    syswrite($chout,"\r");
		    sleep(3); syswrite($chout,"\r");
		    sleep(2); syswrite($chout,"\r");
		    sleep(2); syswrite($chout,"\r");
		    @linehist = ();
		    $retval = $self->expect($nodeobject,
					    \@linehist,undef,
					    { 'timeout' => 8,
					      'presend' => "\n",
					      'seq' => [ [ '#\s*',undef,'line' ] ] });
		}

		if ($retval >= 0) {
1101
		    $self->dprint(0,"probeForOutput($node_id): found switch at $speed!");
1102 1103 1104 1105 1106
		    $sfound = 1;
		    $sspeed = $speed;
		    last;
		}
		elsif ($retval == -3) {
1107
		    tbwarn "$self probeForOutput($node_id): timed out.\n";
1108 1109
		}
		elsif ($retval == -1) {
1110
		    tbwarn "$self probeForOutput($node_id): prompt not found.\n";
1111 1112
		}
		elsif ($retval == -2) {
1113
		    tbwarn "$self probeForOutput($node_id): error in read.\n";
1114 1115
		}
		else {
1116
		    tbwarn "$self probeForOutput($node_id): unknown error!\n";
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
		}
	    }
	}
    }
    else {
	# don't know what speed we're at, but we're fine until we have to reboot
	$sfound = 1;
    }

    if ($sfound) {
	# see which prompt we're at -- the ROM monitor or OS
	if (@linehist[scalar(@linehist)-1] =~ /#\s*/ 
	    || (scalar(@linehist) > 1 
		&& @linehist[scalar(@linehist)-2] =~ /#\s*/)) {
1131
	    $self->dprint(0,"probeForOutput: found OS");
1132 1133 1134 1135 1136
	    return 2;
	}
	elsif (@linehist[scalar(@linehist)-1] =~ /=>\s*$/ 
	       || (scalar(@linehist) > 1 
		   && @linehist[scalar(@linehist)-2] =~ /=>\s*$/)) {
1137
	    $self->dprint(0,"probeForOutput: found ROM monitor");
1138 1139 1140
	    return 1;
	}
	else {
1141
	    $self->dprint(0,"probeForOutput: got output, but not sure how to parse:" . Dumper(@linehist));
1142 1143 1144 1145
	    return 0;
	}
    }

1146
    return $retval;
1147 1148 1149 1150 1151 1152 1153 1154 1155
}

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

1156
    $self->dprint(0,"_checkFlashSlots($node_id): getting flash contents");
1157 1158 1159 1160 1161 1162
    $retval = $self->expect($nodeobject,\@linehist,undef,
			    { 'timeout' => 3,
			      'presend' => $tchar,
			      'seq' => [ [ '#\s+', "show flash\n", 'line' ],
					 [ '#\s+', undef, 'line'] ] });
    if ($retval < 0) {
1163
	tbwarn "$self _checkFlashSlots($node_id): could not get flash contents: $retval,$!\n";
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
	return -1;
    }

    my %rethash = ();
    foreach my $line (@linehist) {
	if ($line =~ /(\w+) Image\s*:\s+(\d+)\s+([\d\/]+)\s+([\w\d\.]+)/) {
	    my $img = lc($1);
	    $rethash{$img}{size} = $2;
	    $rethash{$img}{date} = $3;
	    $rethash{$img}{version} = $4;
	}
	elsif ($line =~ /Boot Rom Version\s*:\s+(.*)$/) {
	    $rethash{rom}{version} = $1;
	}
	elsif ($line =~ /Default Boot\s*:\s+(\w+)/) {
	    $rethash{default} = $1;
	}
    }

    return \%rethash;
}

#
# Wipes config, ssh, and ssl data files.
#
sub wipeFiles($$) {
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

    my $retval = 0;
    my @linehist = ();

    foreach my $path ('/cfa0/cfg','/cfa0/ssh','/cfa0/ssl') {
	@linehist = ();
1198
	$self->dprint(1,"wipeFiles($node_id): getting files in $path");
1199 1200 1201 1202 1203 1204
	$retval = $self->expect($nodeobject,\@linehist,undef,
				{ 'timeout' => 10,
				  'presend' => $tchar,
				  'seq' => [ [ '=>', "ll ${path}\n", 'line' ],
					     [ '=>', undef, 'line'] ] });
	if ($retval < 0) {
1205
	    tbwarn "$self wipeFiles($node_id): could not list configs: $retval,$!\n";
1206 1207 1208 1209 1210 1211
	    return -1;
	}

	my @files = ();
	foreach my $line (@linehist) {
	    chomp($line);
1212 1213 1214
	    $self->dprint(3,"wipeFiles($node_id): rm checking line '$line'");
	    if ($line =~ /^[\w\-]+\s+\d+\s+\d+\s+\d+\s+\d+\s+\w+\s+\d+\s+\d+\s+([^\r\n]+)\r*$/
		|| $line =~ /^[\w\-]+\s+\d+\s+\d+\s+\d+\s+\d+\s+\w+\s+\d+\s+\d+:\d+\s+([^\r\n]+)\r*$/) {
1215 1216 1217 1218 1219 1220 1221 1222 1223
		push @files, $1;
	    }
	}

	foreach my $file (@files) {
	    next 
		if ($file eq '.' || $file eq '..' || $file eq './' 
		    || $file eq '../');

1224
	    # also filter out hostkey removal... this makes switch boot
1225 1226 1227 1228 1229
	    # take a *long* time! ... or so it seems.
	    next 
		if ($file =~ /host_ssh/);

	    my $filepath = "${path}/${file}";
1230
	    $self->dprint(2,"wipeFiles($node_id): trying to rm file '$filepath'");
1231 1232 1233 1234 1235 1236
	    $retval = $self->expect($nodeobject,undef,undef,
				    { 'timeout' => 10,
				      'presend' => $tchar,
				      'seq' => [ [ '=>', "rm ${filepath}\n", 'line' ],
						 [ '=>', undef, 'line'] ] });
	    if ($retval < 0) {
1237
		tberror "$self wipeFiles($node_id): could not delete $filepath: $retval, $!\n";
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
		return -2;
	    }
	}
    }

    return 0;
}

sub _translatePort($$$) {
    my ($self,$card,$port) = @_;
    return "" . chr($card+(ord('A')-1)) . "$port";
}
	
sub generateConfig($$) {
    my ($self,$nodeobject,) = @_;
    my $node_id = $nodeobject->node_id();

    my $retval = 0;
    my @linehist = ();

    my @keylines = ();
    my @passwdlines = ();
    # XXX assume one control net port for now!
    my ($cnetport,$cnetip,$cnetmask,$cnetgw);
1262 1263
    my $experiment;
    my @trunklines = ();
1264 1265

    # install boss's root pubkey first!
1266 1267 1268
    my $rootpubkey;
    TBGetSiteVar("node/ssh_pubkey",\$rootpubkey);
    if (defined($rootpubkey) && $rootpubkey ne '') {
1269 1270 1271 1272 1273 1274
	push @keylines, "ip ssh public-key manager \"$rootpubkey\"";
    }

    if (defined($nodeobject)) {
	my $expt = $nodeobject->Reservation();
	if (defined($expt)) {
1275
	    $experiment = $expt;
1276 1277
	    my $group = Group->Lookup($expt->pid(),$expt->gid());

1278 1279 1280 1281 1282
	    my $dopasswds = 
		$self->nodeinfo($nodeobject,'osload_loadpasswds');
	    my $useonlydefaultkeys = 
		$self->nodeinfo($nodeobject,'osload_onlydefaultkeys');

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
	    my @users = ();
	    $group->MemberList(\@users,$Group::MEMBERLIST_FLAGS_GETTRUST);
	    foreach my $u (@users) {
		my $uid = $u->uid();
		my $trust = $u->GetTempData();
		my $level;
		# if they're a root, give them the keys to the kingdom
		if ($trust eq $Group::MemberShip::TRUSTSTRING_PROJROOT
		    || $trust eq $Group::MemberShip::TRUSTSTRING_GROUPROOT
		    || $trust eq $Group::MemberShip::TRUSTSTRING_LOCALROOT) {
		    $level = 'manager';
		}
		# if they're just a user, they only get operator switch privs
		elsif ($trust eq $Group::MemberShip::TRUSTSTRING_USER) {
		    $level = 'operator';
		}
		# if they're not approved, of course don't do anything
		else {
		    next;
		}

		if (defined($dopasswds) && $dopasswds) {
		    push @passwdlines, "password $level user-name $uid sha1 \"" . sha1_hex($u->pswd()) . "\"";
		}

		my @keys = ();

		if (defined($useonlydefaultkeys) && $useonlydefaultkeys) {
		    $u->GetDefaultSSHKeys(\@keys);
		}
		else {
		    $u->GetSSHKeys(\@keys);
		}
	    
		foreach my $k (@keys) {
		    next
			if (scalar(@keylines) >= 10);
		    
		    push @keylines, "ip ssh public-key $level \"$k\"";
		}
	    }
	}

	my @ifaces = ();
	$nodeobject->AllInterfaces(\@ifaces);
	foreach my $i (@ifaces) {
	    if ($i->role eq TBDB_IFACEROLE_CONTROL()) {
		$cnetport = $self->_translatePort($i->card(),$i->port());
		$cnetip = $i->IP();
		$cnetmask = $i->mask();
		if (!defined($cnetmask) || $cnetmask eq '') {
		    $cnetmask = $CONTROL_NETMASK;
		}
		$cnetgw = $CONTROL_ROUTER_IP;

		last;
	    }
	}
    };

1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
    if (defined($experiment)) {
	#
	# Grab all the vlans for the experiment and find the trunks between
	# switches that include this switch. 
	#
	my $trunkindex = 3;
	my @vlans;
	if (VLan->ExperimentVLans($experiment, \@vlans) != 0) {
	    tberror("Could not get list of all vlans for $experiment\n");
	    return ();
	}
	foreach my $vlan (@vlans) {
	    my @members;
	    
	    next
		if ($vlan->type() ne "wire");
	    next
		if ($vlan->GetRole() ne "trunk");

	    if ($vlan->MemberList(\@members)) {
		tberror("Could not get member list of members for $vlan\n");
		return ();
	    }
	    foreach my $member (@members) {
		my ($membnode_id, $membiface);
		if ($member->GetNodeIface(\$membnode_id, \$membiface)) {
		    tberror("Could not get node/iface for $member\n");
		    return ();
		}
		next
		    if ($membnode_id->node_id() ne $node_id);

		my $interface = Interface->LookupByIface($nodeobject, $membiface);
		if (!defined($interface)) {
		    tberror("Could not lookup interface for $member\n");
		    return ();
		}
		my $card  = $interface->card();
		my $port  = $interface->port();
1382
		my $portname = $self->_translatePort($card, $port);
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
		
		#
		# A trunk has to be in at least one vlan in tagged mode, for
	        # snmpit to think it is a trunk. 
		#
		push @trunklines, "trunk $portname trk${trunkindex} lacp";
		push @trunklines, "vlan $trunkindex";
		push @trunklines, "  tagged Trk${trunkindex}";
		push @trunklines, "  exit";
		push @trunklines, "vlan 1";
		push @trunklines, "  no untagged Trk${trunkindex}";
		push @trunklines, "  exit";
		$trunkindex++;
	    }
	}
    }

1400
    my @cnetlines = ();
1401 1402 1403 1404 1405 1406 1407 1408
    #
    # We *HAVE* to remove anything that might have snuck into vlan 1
    # in the control net subnet, before trying to assign one in vlan 999.
    # This seems to sometimes happen via DHCP...
    #
    push @cnetlines, "vlan 1";
    push @cnetlines, "  no ip address";
    push @cnetlines, "exit";
1409 1410 1411 1412
    if (defined($cnetport) && $cnetport ne '') {
	push @cnetlines, "vlan 999";
	push @cnetlines, "  name \"EmulabControlPort\"";
	push @cnetlines, "  untagged $cnetport";
1413 1414 1415
	# Prevent the upstream control switch from becoming STP root.
	# Kirk firgured this out for me!
	push @cnetlines, "  spanning-tree $cnetport bpdu-filter";
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
	if (defined($cnetip) && $cnetip ne '') {
	    push @cnetlines, "  ip address ${cnetip} ${cnetmask}";
	    push @cnetlines, "exit";

	    # various other IP config:
	    push @cnetlines, "ip default-gateway ${cnetgw}";
	    push @cnetlines, "ip authorized-managers ${BOSSNODE_IP} access Manager";
	    push @cnetlines, "ip authorized-managers ${USERNODE_IP} access Manager";
	    push @cnetlines, "ip dns server-address priority 1 ${BOSSNODE_IP}";
	    push @cnetlines, "ip dns domain-name ${OURDOMAIN}";
	    #
1427
	    # don't do this -- assume that the hostkey never gets 
1428 1429 1430 1431
	    # overwritten.  Generating takes too long!  Eventually, maybe
	    # detect if it got wiped and then generate if necessary.
	    #
	    #push @cnetlines, "crypto key generate ssh";
1432
	    #
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
	    # We allow ssh, but not scp/sftp (because otherwise we can't
	    # have our tftp client support... which we prefer for reloads
	    push @cnetlines, "ip ssh";
	    push @cnetlines, "no ip ssh filetransfer";
		
	    push @cnetlines, "ip ssh public-key manager \"\"";
	}
	else {
	    push @cnetlines, "exit";
	}
    }

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    my $community = "private";
    my $qres = DBQueryFatal("select sst.snmp_community" . 
			    "  from switch_stacks as ss" .
			    " left join switch_stack_types as sst" . 
			    "  on ss.stack_id=sst.stack_id" . 
			    " where ss.node_id='$node_id'");
    if (defined($qres) && $qres->numrows()) {
	my @row = $qres->fetchrow_array();
	if (!defined($row[0])) {
	    tbwarn "Could not find snmp_community for experiment switch $node_id, using default of '$community'!\n";
	}
	else {
	    $community = $row[0];
	}
    }
    else {
	tbwarn "Could not find snmp_community for experiment switch $node_id!\n";
    }

1464 1465 1466
    my @config = (
	"hostname \"" . $node_id . "\"",
	@cnetlines,
1467
	@trunklines,
1468
	# this prompts; must handle manually!
1469 1470 1471 1472 1473
	#"include-credentials",
	"aaa authentication ssh login public-key",
	"aaa authentication ssh login local",
	@keylines,
	@passwdlines,
1474 1475 1476 1477
	'snmp-server community "' . $community . '" Unrestricted',
	'snmp-server contact "testbed-ops@flux.utah.edu"',
	# try to cover our hind ends and eliminate loops!
	"spanning-tree",
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
	"no web-management",
	"no telnet-server",
	"tftp client",
	"no tftp server",
	"no tftp6 client",
	"no tftp6 server",
	"no autorun",
	"no banner motd",
	);

1488 1489 1490 1491 1492
    if ($self->debug()) {
	foreach my $cl (@config) {
	    $self->dprint(4,"Reconfigure($node_id): config line: $cl\n");
	}
    }
1493 1494 1495 1496 1497
    return @config;
}

sub writeConfig($$$) {
    my ($self,$nodeobject,$configref) = @_;
1498
    my $node_id = $nodeobject->node_id();
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    my @config = @$configref;

    # setup most of our config lines
    my @configseq = ();
    foreach my $line (@config) {
	push @configseq, [ '#\s+$', $line."\n", 'line' ];
    }

    push @configseq, [ '#\s+$', "end\n", 'line' ];
    push @configseq, [ '#\s+$', "write memory\n", 'line' ];

    my $retval;

    # do a quick flip to get into config mode!
    $retval = $self->expect($nodeobject,undef,undef,
			    { 'timeout' => 10,
			      'presend' => $tchar,
			      'seq' => [ [ '#\s+$', "configure terminal\n", 'line' ],
					 [ '#\s*$', undef, 'line'] ] });
    if ($retval < 0) {
1519
	tberror "$self writeConfig($node_id): could not get into configure terminal mode: $retval, $!\n";
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
	return -1;
    }

    # oh boy, this is icky -- sometimes we get
    # asked to confirm, sometimes not.  so, best
    # effort: we check for the prompts and answer
    # them if they appear; but don't be fatal if they don't!
    $retval = $self->expect($nodeobject,undef,undef,
			    { 'timeout' => 10,
			      'presend' => $tchar,
			      'seq' => [ [ '#\s+$', "include-credentials\n", 'line' ],
1531 1532
					 [ '\?(\(|\[)y\/n(\)|\])\s+$', "y\n", 'line' ],
					 [ '\?(\(|\[)y\/n(\)|\])\s+$', "y\n", 'line' ] ] });
1533
    if ($retval < 0) {
1534
	tbwarn "$self writeConfig($node_id): include-credentials funky, but continuing!: $retval, $!\n";
1535 1536 1537 1538 1539 1540 1541 1542 1543
    }

#    my @configseq = ( [ '#\s+$', "configure terminal\n", 'line' ],
#		      [ '#\s+$', "include-credentials\n", 'line' ],
#		      [ '\?\[y\/n\]\s+$', "y\n", 'line' ],
#		      [ '\?\[y\/n\]\s+$', "y\n", 'line' ] );

    # NOTE: we give it a huge timeout below so that we can generate a hostkey
    # (this can take a long time)
1544
    $self->dprint(0,"writeConfig($node_id): starting main body");
1545 1546 1547 1548 1549 1550
    $retval = $self->expect($nodeobject,undef,undef,
			    { 'timeout' => 90,
			      'presend' => $tchar,
			      'seq' => [ @configseq,
					 [ '#\s*$', undef, 'line'] ] });
    if ($retval < 0) {
1551
	tberror "$self writeConfig($node_id): could not write config: $retval: $!\n";
1552 1553
	return -1;
    }
1554
    $self->dprint(0,"writeConfig($node_id): done");
1555 1556 1557 1558

    return 0;
}

1559 1560
sub uploadImageTftp($$$;$) {
    my ($self,$nodeobject,$filename,$flashedref) = @_;
1561 1562
    my $node_id = $nodeobject->node_id();
    my $retval;
1563
    my $didflash = 0;
1564 1565 1566 1567 1568 1569 1570 1571

    #
    # This must be done from the OS serial command prompt!  We need to disable
    # scp/sftp, enable tftp client, and then pull the file.  This means we
    # must first copy the file into /tftpboot/tmp/foo so that our tftp server
    # can send it, and make sure we remove the file once the command completes
    # successfully.
    #
1572
    $self->dprint(0,"uploadImageTftp($node_id): starting");
1573 1574 1575 1576 1577 1578

    #
    # Make a temp file for the image.
    #
    my (undef,$tmpfilename) = tempfile("/tftpboot/osload-tmp/osload_switch_img_XXXXXX",OPEN => 0);
    if (!defined($tmpfilename)) {
1579
	tberror "$self uploadImageTftp($node_id): could not create tempfile for switch image binary: $!";
1580 1581 1582 1583
	goto failure;
    }

    if (system("cp $filename $tmpfilename")) {
1584
	tberror "$self uploadImageTftp($node_id): could not copy $filename to $tmpfilename: $!";
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
	goto failure;
    }

    #
    # XXX: assumes the switch has ntowrk connectivity already!
    #
    # reconfig the switch: make sure to disable scp/sftp filetransfer
    # before enabling tftp -- we can't hvae both
    #
    $retval = $self->expect($nodeobject,undef,undef,
			    { 'timeout' => 10,
			      'presend' => $tchar,
			      'seq' => [ [ '#\s*$', "configure terminal\n", 'line' ],
					 [ '#\s*$', "no ip ssh filetransfer\n", 'line' ],
					 [ '#\s*$', "tftp client\n", 'line' ],
					 [ '#\s*$', "end\n", 'line' ],
					 # must write memory so we don't get 
					 # prompted to save
					 [ '#\s+', "write memory\n", 'line' ],
					 [ '#\s*$', undef, 'line'] ] });
    if ($retval < 0) {
1606
	tberror "$self uploadImageTftp($node_id): could not enable tftp client on switch: $retval,$!";
1607 1608 1609 1610
	goto failure;
    }

    my @linehist = ();
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
    #
    # Sadly, once we get past a specific version of HP switch firmware, we have
    # to check to see if we need to append the "allow-no-signature" option to
    # the tftp flash command, so that the older, unsigned image can be flashed.
    # But of course, older releases don't support that option :).  So, try first
    # with the option; then without if it fails.
    #
    my $has_sig_support = 1;
    my $sigstuff = " allow-no-signature";
    $retval = $self->expect($nodeobject,\@linehist,undef,
			    { 'timeout' => 60,
			      'presend' => $tchar,
			      'seq' => [ [ '#\s*$', "copy tftp flash 0.0.0.0 /foo  primary allow-no-signature\n", 'line' ],
					 [ '#\s*$', undef, 'line' ] ] });
    if ($retval < 0) {
	tberror "$self uploadImageTftp($node_id): could not check for allow-no-signatures option, assuming does not have it: $retval,$!";
	$has_sig_support = 0;
	$sigstuff = "";
    }
    else {
	for my $line (@linehist) {
David Johnson's avatar
David Johnson committed
1632 1633
	    #print "ANS CHECK: $line\n";
	    if ($line =~ /Invalid input:\s+allow-no-signature/i) {
1634 1635 1636 1637 1638 1639 1640
		$has_sig_support = 0;
		$sigstuff = "";
	    }
	}
    }

    @linehist = ();
1641
    $retval = $self->expect($nodeobject,\@linehist,undef,
1642
			    { 'timeout' => 300,
1643
			      'presend' => $tchar,
1644 1645
			      'seq' => [ [ '#\s*$', "copy tftp flash ${BOSSNODE_IP} $tmpfilename primary $sigstuff\n", 'line' ],
					 [ '(C|c)ontinue (\(|\[)y\/n(\)|\])\?\s*', "y\n", 'line' ],
1646 1647
					 [ '#\s*$', undef, 'line' ] ] });
    if ($retval < 0) {
1648
	tberror "$self uploadImageTftp($node_id): could not upload file via tftp: $retval,$!";
1649 1650
	# we have to assume that it happened
	$didflash = 1;
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
	goto failure;
    }

    #
    # Check for various return codes we know can happen!
    #
    my $errormsg;
    foreach my $line (@linehist) {
	if ($line =~ /(Corrupted download file)/
	    || $line =~ /(Wrong file)/) {
	    $errormsg = $1;
	    last;
	}
    }

    if (defined($errormsg)) {
	tberror "$self Reload($node_id): tftp upload failed: $errormsg\n";
	$retval = -2;
1669 1670
	# we didn't actually flash anything
	$didflash = 0;
1671 1672 1673
	goto failure;
    }

1674
    $self->dprint(0,"uploadImageTftp($node_id): tftp upload appears successful!");
1675 1676

    unlink($tmpfilename);
1677 1678 1679
    if (defined($flashedref)) {
	$$flashedref = 1;
    }
1680 1681 1682 1683
    return 0;

  failure:
    unlink($tmpfilename);
1684 1685 1686
    if (defined($flashedref)) {
	$$flashedref = $didflash;
    }
1687 1688 1689
    return -1;
}

1690 1691
sub uploadImageXmodem($$$;$) {
    my ($self,$nodeobject,$filename,$flashedref) = @_;
1692 1693 1694 1695 1696 1697 1698
    my $node_id = $nodeobject->node_id();
    my $retval;

    my $tipref = $self->_doTiptunnel($nodeobject);
    my ($chin,$chout,$cherr) = 
	($tipref->{'in'},$tipref->{'out'},$tipref->{'err'});

1699 1700
    $self->dprint(0,"uploadImageXmodem($node_id): starting");

1701 1702 1703 1704
    if (defined($flashedref)) {
	$$flashedref = 0;
    }

1705 1706 1707 1708
    #
    # Ok, we're here... let's setup the load.  Change speeds on both switch and
    # capture.  Then do the expect dance, and trigger lsz.
    #
1709
    $self->dprint(1,"uploadImageXmodem($node_id): changing speed to 115200 for upload");
1710 1711
    syswrite($chout,"speed 115200\n");
    if ($retval = $self->setSpeed($nodeobject,115200)) {
1712
	tberror "$self uploadImageXmodem($node_id): setSpeed failed with $retval, $!\n";
1713 1714 1715
	return -1;
    }

1716
    if (1) {
1717
	$self->dprint(1,"uploadImageXmodem($node_id): running initxmodem");
1718 1719 1720
	$retval = $self->expect($nodeobject,undef,undef,
				$sequences{'initxmodem'});
	if ($retval < 0) {
1721
	    tberror "$self uploadImageXmodem($node_id): initxmodem expect sequence failed: $retval, $!\n";
1722 1723
	    return -1;
	}
1724 1725 1726 1727 1728 1729

	# drain what we can...
	$self->dprint(1,"uploadImageXmodem($node_id): draining");
	$self->expect($nodeobject,undef,undef,
		      $sequences{'drain'});

1730
	$self->dprint(1,"uploadImageXmodem($node_id): hooking up lsz child");
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
	my $pid = fork();
	if (!$pid) {
	    # hook up child stdin/out to tiptunnel so lsz can write there.
	    open(STDOUT,">&",$chout) or die "open: $!\n";
	    open(STDIN,">&",$chin) or die "open: $!\n";

	    exec("$LSZ -X -b $filename");
	    # should never get here unless exec fails
	    exit(-5);
	}

1742
	$self->dprint(1,"uploadImageXmodem($node_id): parent waiting for child $pid");
1743
	$retval = waitpid($pid,0);
1744
	$retval = $? >> 8;
1745 1746 1747 1748 1749 1750

	#
	# bit of a race here -- we can't read from capture until lsz finishes.
	# Fortunately, the switch is slow to process the upload, so we can pretty
	# much count on getting some lines showing success or failure.
	#
1751
	$self->dprint(1,"uploadImageXmodem($node_id): child returned $retval");
1752

1753 1754 1755 1756 1757 1758 1759 1760
	if ($retval) {
	    return -1;
	}

	if (defined($flashedref)) {
	    $$flashedref = 1;
	}

1761
	$self->dprint(1,"uploadImageXmodem($node_id): running finishxmodem");
1762 1763 1764
	$retval = $self->expect($nodeobject,undef,undef,
				$sequences{'finishxmodem'});
	if ($retval < 0) {
1765
	    tberror "$self uploadImageXmodem($node_id): finishxmodem expect sequence failed: $retval, $!\n";
1766 1767 1768 1769
	    return -1;
	}
    }
    else {
1770
	$self->dprint(1,"uploadImageXmodem($node_id): skipping imaging and reloading, rebooting");
1771 1772 1773
	$retval = $self->expect($nodeobject,undef,undef,
				$sequences{'reboot'});
	if ($retval < 0) {
1774
	    tberror "$self uploadImageXmodem($node_id): skipping imaging and reboot failed: $retval, $!\n";
1775 1776 1777 1778
	    return -1;
	}
    }

1779
    $self->dprint(1,"uploadImageXmodem($node_id): flipping capture to default speed");
1780
    if ($retval = $self->setSpeed($nodeobject,$DEFSPEED)) {
1781
	tbwarn "$self uploadImageXmodem($node_id): setSpeed($DEFSPEED) failed with $retval, $!\n";
1782 1783 1784
	return -1;
    }

1785
    $self->dprint(1,"uploadImageXmodem($node_id): waiting for switch to boot");
1786 1787 1788
    $retval = $self->expect($nodeobject,undef,undef,
			    $sequences{'bootAfterLoad'});
    if ($retval < 0) {
1789
	tberror "$self uploadImageXmodem($node_id): bootAfterLoad expect sequence failed: $retval, $!\n";
1790 1791 1792
	return -1;
    }

1793
    $self->dprint(0,"uploadImageXmodem($node_id): success!");
1794 1795 1796
    return 0;
}

1797 1798
sub expect($$$$$;$) {
    my ($self,$nodeobject,$histbufref,$databufref,$seqref,$seqnumref) = @_;
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
    my $node_id = $nodeobject->node_id();
    my $retval;

    # our return code; error by default
    my $rc = -1;

    my $tipref = $self->_doTiptunnel($nodeobject);
    my ($in,$out,$err) = ($tipref->{'in'},$tipref->{'out'},$tipref->{'err'});

    return -1 
	if (!defined($seqref));

1811
    my ($timeout,@seqs,$presend,$drain);
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    if (exists($seqref->{'timeout'})) {
	$timeout = $seqref->{'timeout'};
    }
    if (exists($seqref->{'seq'})) {
	@seqs = @{$seqref->{'seq'}};
    }
    else {
	return -5;
    }
    if (exists($seqref->{'presend'})) {
	$presend = $seqref->{'presend'};
    }
1824 1825 1826
    if (exists($seqref->{'drain'})) {
	$drain = $seqref->{'drain'};
    }
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

    # if they didn't give us any history buffers to fill, just do it locally
    # so we can actually match
    if (!defined($histbufref)) {
	my @histbuf = ();
	$histbufref = \@histbuf;
    }
    if (!defined($databufref)) {
	my $databuf = '';
	$databufref = \$databuf;
    }

1839 1840
    if (defined($presend) || (defined($drain) && $drain)) {
	$self->dprint(3,"expect: draining");
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863

	my $escseq = undef;
	while (1) {
	    my $char;
	    my ($rin,$ein) = ('','');
	    my ($rout,$eout);
	    vec($rin,fileno($in),1) = 1;
	    #vec($ein,fileno($err),1) = 1;

	    my $lineref;
	    # pick up where we left off if there is history
	    if (scalar(@$histbufref)
		&& $histbufref->[scalar(@$histbufref)-1] !~ /\n$/) {
		$lineref = \$histbufref->[scalar(@$histbufref)-1];
	    }
	    else {
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];
	    }

	    my $retval;
	    while (($retval = select($rout=$rin,undef,$eout=$ein,2)) < 0 
		   && $! =~ /Interrupted system call/) {
1864
		$self->dprint(2,"expect: select interrupted, retrying");
1865 1866 1867 1868 1869 1870 1871 1872
		sleep(1);
	    }
	    if ($retval < 0) {
		tbwarn "$self expect: error in select: $retval,$!\n";
		$rc = -2;
		goto out;
	    }
	    elsif ($retval == 0) {
1873
		$self->dprint(2,"expect: select found nothing to read!");
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
		last;
	    }

	    while (($retval = sysread($in,$char,1)) < 0
		   && $! =~ /interrupt/i) {
		sleep(1);
	    }
	    if ($retval == 0) {
		tbwarn "$self expect: unexpected EOF in sysread in expect drain loop; stopping drain!\n";
		last;
	    }
	    elsif ($retval != 1) {
		tbwarn "$self expect: error ($retval,$!) in sysread in expect drain loop; stopping drain!\n";
		last;
	    }

	    #
	    # Strip out ANSI escape sequences
	    #
	    if (ord($char) == 8 || ord($char) == 24) { next; }
	    elsif (ord($char) == 27) {
		$escseq = ''; #$char;
		next;
	    }
	    if (defined($escseq)) {
		$escseq .= $char;
		if ($char =~ /[HfABCDsuJKmh\|p]/) {
1901
		    $self->dprint(4,"expect: esc $escseq");
1902 1903 1904 1905 1906 1907 1908 1909 1910
		    $escseq = undef;
		}
		next;
	    }

	    $$databufref .= $char;
	    $$lineref .= $char;

	    if ($char eq "\n") {
1911
		$self->dprint(4,"expect: drain rotating line buf");
1912 1913 1914 1915 1916
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];
	    }
	}

1917 1918 1919 1920
	if (defined($presend)) {
	    $self->dprint(3,"expect: presending '$presend'");
	    syswrite($out,$presend);
	}
1921 1922 1923 1924 1925 1926 1927
    }

    my $found = 0;
    my $i;
    for ($i = 0; $i < scalar(@seqs); ++$i) {
	my ($rval,$sval,$mtype) = @{$seqs[$i]};

1928
	$self->dprint(3,"expect: looking for '$rval':");
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

	my ($rin,$ein) = ('','');
	my ($rout,$eout);
	vec($rin,fileno($in),1) = 1;
	#vec($ein,fileno($err),1) = 1;

	my $lineref;
	# pick up where we left off if there is history
	if (scalar(@$histbufref)
	    && $histbufref->[scalar(@$histbufref)-1] !~ /\n$/) {
	    $lineref = \$histbufref->[scalar(@$histbufref)-1];
	}
	else {
	    $histbufref->[scalar(@$histbufref)] = '';
	    $lineref = \$histbufref->[scalar(@$histbufref)-1];
	}

	my $localfound = 0;
	my $escseq = undef;
	while (1) {
	    my $char;

	    my $retval;
	    while (($retval = select($rout=$rin,undef,$eout=$ein,$timeout)) < 0 
		   && $! =~ /Interrupted system call/) {
1954
		$self->dprint(2,"expect: select interrupted, retrying");
1955 1956 1957 1958 1959 1960 1961 1962
		sleep(1);
	    }
	    if ($retval < 0) {
		tberror "$self expect: error in select: $retval,$!\n";
		$rc = -2;
		goto out;
	    }
	    elsif ($retval == 0) {
1963
		$self->dprint(2,"expect: select found nothing to read!");
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
		$rc = -3;
		goto out;
	    }

	    while (($retval = sysread($in,$char,1)) < 0
		   && $! =~ /interrupt/i) {
		sleep(1);
	    }
	    if ($retval == 0) {
		tbwarn "$self expect: unexpected EOF in sysread in expect loop!\n";
		last;
	    }
	    elsif ($retval != 1) {
		tbwarn "$self expect: error ($retval,$!) in sysread in expect loop\n";
		last;
	    }

#	    if (sysread($in,$char,1) != 1) {
#		tbwarn "$self expect: error in sysread in expect loop!\n";
#		if ($self->debug()) {
#		    print "$self expect: had read the following lines:\n\n";
#		    foreach my $ln (@$histbufref) {
#			print "$ln";
#		    }
#		    print "\n\n";
#		}
#		last;
#	    }

	    #
	    # Strip out ANSI escape sequences
	    #
	    if (ord($char) == 8 || ord($char) == 24) { next; }
	    elsif (ord($char) == 27) {
		$escseq = ''; #$char;
		next;
	    }
	    if (defined($escseq)) {
		$escseq .= $char;
		if ($char =~ /[HfABCDsuJKmh\|p]/) {
2004
		    $self->dprint(4,"expect: esc $escseq");
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
		    $escseq = undef;
		}
		next;
	    }

	    $$databufref .= $char;
	    $$lineref .= $char;

	    my $mdataref = $lineref;
	    if ($mtype eq 'all') {
		$mdataref = $databufref;
	    }

2018
	    $self->dprint(4,"expect: checking if '".$$mdataref."' matches '$rval'");
2019
	    if ($$mdataref =~ $rval) {
2020
		$self->dprint(2,"expect: '".$$mdataref."' matched '$rval'!");
2021 2022 2023
		if (defined($sval)) {
		    if (ref($sval) eq 'CODE') {
			$sval->($out);
2024
			$self->dprint(3,"expect: ran code instead of sending!");
2025 2026 2027
		    }
		    else {
			syswrite($out,$sval);
2028
			$self->dprint(3,"expect: sent '$sval'");
2029 2030 2031
		    }
		}
		else {
2032
		    $self->dprint(3,"expect: matched but not sending because undef was given");
2033
		}
2034
		$self->dprint(4,"expect: rotating line buf at match");
2035 2036 2037 2038 2039 2040 2041
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];

		$found = $localfound = 1;
	    }

	    if ($char eq "\n") {
2042 2043
		$self->dprint(4,"read '".chomp($$lineref)."' while looking for '$rval'\n");
		$self->dprint(4,"expect: rotating line buf at newline");
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];
	    }

	    last if ($localfound);
	}
    }

    if (!$found) {
	$rc = -1;
    }
    else {
	$rc = $i;
    }

  out:
2060 2061 2062 2063 2064 2065 2066
    # Save off which sequence number we were on in case we need to return
    # negative to tell caller how we failed.  This gives callers the option
    # of having a partially-failed sequence still be useful, depending on
    # how far it got!
    if (defined($seqnumref)) {
	$$seqnumref = $i;
    }
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
    #
    # Save off our histories if there is anything in them!
    #
    if (@$histbufref > 0) {
	push @{$tipref->{linehist}}, @$histbufref;
    }
    if ($$databufref ne '') {
	$tipref->{databuf} .= $$databufref;
    }

    return $rc;
}

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