libosload_switch.pm.in 56.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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 154

package libosload_switch;

use strict;
use lib '@prefix@/lib';
use libosload;

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

use libdb;
use libtestbed;
use libtblog;
use libreboot;
use Node;
use Group;
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' ],
		   [ 'continue \[y\/n\]\?\s*$', "y", 'line' ] ] },
155 156 157 158 159 160 161 162 163 164 165
      'rebootContinueOpt' =>
      { 'timeout' => 5,
	'presend' => $tchar,
	'seq' => [ [ '((#\s+)|(=>))$', "boot\n", 'line' ],
		   [ 'continue \[y\/n\]\?\s*$', "y", 'line' ],
		   [ 'save current configuration \[y\/n\/\^C\]\s*$?', 'y', 'line' ] ] },
      # 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 239 240 241 242 243 244 245 246 247 248 249 250 251
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();

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

    #
    # 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')) {
	my $qres = DBQueryWarn("select * from partitions".
			       " where node_id='$node_id' and partition=$newpart");
252 253 254 255 256
	if (!$qres->numrows()) {
	    tbinfo "$self PreSetupReload($node_id): forcing reload; nothing in partitions table for this node\n";
	    $self->nodeflag($nodeobject,'force',1);
	}

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

		last;
	    }
	}
    }

274 275 276 277 278
    #
    # 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.
    #
279
    if ($self->nodeflag($nodeobject,'force')) {
280 281 282 283 284 285 286 287 288 289 290 291
	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());
    }

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

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

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

308
    if ($self->nodeflag($nodeobject,'force')) {
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
	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();
    my $rowref = $self->imageinfo($newimageid);
    my $newosid = $rowref->{'default_osid'};

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

363
    $self->dprint(0,"SetupReconfigure($node_id): putting switch in SHUTDOWN");
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    #
    # 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!
394
    #$self->dprint(0,"_doTipTunnel($node_id): forcing capture reset!");
395 396
    #system("${CONSOLE_RESET} $node_id");

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

    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;
407
	tbwarn "$self _doTipTunnel($node_id): reload tiptunnel exited" . 
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	    " 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';

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

    # 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;
458 459
    
    $self->dprint(0,"Reconfigure($node_id): starting");
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

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

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

500
    $self->dprint(2,"Reconfigure($node_id): trying to generate config first");
501 502 503
    my @config = $self->generateConfig($nodeobject);
    if ($self->debug()) {
	foreach my $cl (@config) {
504
	    $self->dprint(4,"Reconfigure($node_id): config line: $cl\n");
505 506 507 508 509 510 511 512 513 514 515
	}
    }

    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();
516
    $reboot_args{'waitmode'} = 0;
517 518
    $reboot_args{'nodelist'} = [ $node_id ];
    $reboot_args{'powercycle'} = 1;
519
    $reboot_args{'force'}    = 1;
520

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

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

538
	$self->dprint(1,"Reconfigure($node_id): trying console reboot");
539 540
	if ($self->expect($nodeobject,undef,undef,
			  $sequences{'rebootContinue'}) < 0) {
541 542 543 544 545 546 547 548 549 550 551 552 553
	    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";
554 555 556 557 558 559 560 561 562 563 564
		goto failure;
	    }
	}
	$rebooting = 1;
    }
    elsif ($retval == 1) {
	# already in ROM monitor
	;
    }
    elsif ($retval <= 0) {
	# have to reboot -- no other choice
565 566 567
	if (defined($self->nodeinfo($nodeobject,'flashing'))
	    && !$self->nodeinfo($nodeobject,'flashing')) {
	    $self->dprint(0,"Reconfigure($node_id): could not obtain output on switch; rebooting!");
568

569 570 571 572 573 574 575 576 577
	    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";
578 579 580 581 582
	    goto failure;
	}
	$rebooting = 1;
    }

583
    $self->dprint(1,"Reconfigure($node_id): child setting state to BOOTING");
584 585 586 587 588 589 590 591 592
    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);

593
	$self->dprint(1,"Reconfigure($node_id): running bootToRom");
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	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
610
    $self->dprint(1,"Reconfigure($node_id): booting into OS");
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 653 654 655 656
    $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) {
657
	$self->dprint(1,"Reconfigure($node_id): exiting with $rc");
658 659
	exit $rc;
    }
660
    $self->dprint(0,"Reconfigure($node_id): returning $rc");
661 662 663 664 665 666 667 668
    return $rc;
}

sub Reload($$) 
{
    my ($self,$nodeobject) = @_;
    my $node_id = $nodeobject->node_id();
    my $retval;
669
    my $didflash = 0;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

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

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

    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'))) {
688 689 690 691 692 693
	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.
	#
694 695 696 697
	TBSetNodeNextOpMode($node_id,TBDB_NODEOPMODE_RELOADPUSH);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
	# give stated time to change op modes
	sleep(4);
698 699 700
	TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADSETUP);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADDONE);
701 702 703
	# reset to teh op mode of the loaded image.
	$nodeobject->Refresh();
	$nodeobject->ResetNextOpMode($self->debug());
704 705 706 707
	TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);
	TBSetNodeEventState($node_id,TBDB_NODESTATE_ISUP);

708 709 710
	return 0;
    }

711 712
    $self->dprint(0,"Reload($node_id): starting");

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    #
    # 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')) {
728 729 730 731 732 733
	    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.
	    #
734 735 736 737
	    TBSetNodeNextOpMode($node_id,TBDB_NODEOPMODE_RELOADPUSH);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
	    # give stated time to change op modes
	    sleep(4);
738 739 740
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADSETUP);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADDONE);
741 742 743
	    # reset to teh op mode of the loaded image.
	    $nodeobject->Refresh();
	    $nodeobject->ResetNextOpMode($self->debug());
744
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_SHUTDOWN);
745 746
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);
	    TBSetNodeEventState($node_id,TBDB_NODESTATE_ISUP);
747

748 749 750 751 752
	    $rc = $self->Reconfigure($nodeobject);
	    goto done;
	}
    }

753
    $self->dprint(1,"Reload($node_id): child setting state to RELOADSETUP");
754 755 756 757
    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADSETUP);

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

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

    my $rebooting = 0;
    my $doreboot = 0;
772 773 774 775 776 777 778 779 780 781 782 783
    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) {
784 785 786
	goto failure;
    }
    elsif ($retval == 2) {
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
	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;
	    }
	}
806 807
    }
    elsif ($retval == 1) {
808 809 810 811 812 813 814 815 816 817 818 819 820
	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;
	    }
821
	}
822 823 824
	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");
825 826 827 828 829 830
	}
    }
    elsif ($retval <= 0) {
	$doreboot = 1;
    }

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

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

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
	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;
	    }
871 872 873
	}
    }

874 875 876 877 878 879 880
    # 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());
	}
881 882 883
    }

    #
884
    # Ok, we're in either the OS (try tftp) or ROM monitor (try xmodem)!
885 886
    #

887
    $self->dprint(1,"Reload($node_id): child setting state to RELOADING");
888 889
    TBSetNodeEventState($node_id,TBDB_NODESTATE_RELOADING);

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
    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;
	    }
906 907
	}
	else {
908 909 910 911 912 913
	    # 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;
	    }
914 915
	}
    }
916 917 918 919 920 921 922
    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";
923 924 925 926 927 928 929 930 931 932 933
	    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.
    #
934 935 936 937
    if ((defined($self->nodeflag($nodeobject,'reconfig')) 
	 && $self->nodeflag($nodeobject,'reconfig'))
	|| (defined($self->nodeflag($nodeobject,'reconfig_will_follow')) 
	    && $self->nodeflag($nodeobject,'reconfig_will_follow'))) {
938
	$self->dprint(1,"Reload($node_id): running bootToRom after load");
939 940 941 942 943 944 945 946 947 948 949 950
	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 {
951
	$self->dprint(1,"Reload($node_id): running bootIntoOS after reload");
952 953 954 955 956 957 958 959 960 961 962 963 964
	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);

965 966
    my $osinfo = OSinfo->Lookup($osid);
    if ($nodeobject->OSSelect($osinfo,"def_boot_osid",$self->debug())) {
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
	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')) {
988
	$self->dprint(1,"Reload($node_id): doing reconfig after reload");
989 990 991 992 993 994 995 996 997 998 999
	$rc = $self->Reconfigure($nodeobject);
    }
    else {
	#
	# Make sure the node hits ISUP
	#
	#TBSetNodeEventState($node_id,TBDB_NODESTATE_BOOTING);
    }
	

  failure:
1000 1001 1002 1003
    if (!$didflash) {
	$self->RestoreNodeDiskInfo($nodeobject);
    }

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

1031
    $self->dprint(3,"setSpeed($nodeid): flipped speed to $speed, pausing briefly");
1032 1033

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

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

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

1061
    $self->dprint(2,"probeForOutput($node_id): probing via current/INT");
1062 1063 1064 1065 1066 1067 1068 1069 1070
    # 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 = ();
1071
	    $self->dprint(2,"probeForOutput($node_id): probing via $speed/INT");
1072
	    if ($self->setSpeed($nodeobject,$speed)) {
1073 1074 1075 1076 1077 1078 1079 1080
		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";
		}
1081 1082 1083 1084 1085 1086 1087 1088
	    }
	    else {
		# try the interrupt char option
		$retval = $self->expect($nodeobject,\@linehist,undef,
					{ 'timeout' => 2,
					  'presend' => $tchar,
					  'seq' => [ [ $prompt,undef,'line' ] ] });
		if ($retval < 0) {
1089
		$self->dprint(2,"probeForOutput($node_id): probing via $speed/ENTER");
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		    # 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) {
1104
		    $self->dprint(0,"probeForOutput($node_id): found switch at $speed!");
1105 1106 1107 1108 1109
		    $sfound = 1;
		    $sspeed = $speed;
		    last;
		}
		elsif ($retval == -3) {
1110
		    tbwarn "$self probeForOutput($node_id): timed out.\n";
1111 1112
		}
		elsif ($retval == -1) {
1113
		    tbwarn "$self probeForOutput($node_id): prompt not found.\n";
1114 1115
		}
		elsif ($retval == -2) {
1116
		    tbwarn "$self probeForOutput($node_id): error in read.\n";
1117 1118
		}
		else {
1119
		    tbwarn "$self probeForOutput($node_id): unknown error!\n";
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
		}
	    }
	}
    }
    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*/)) {
1134
	    $self->dprint(0,"probeForOutput: found OS");
1135 1136 1137 1138 1139
	    return 2;
	}
	elsif (@linehist[scalar(@linehist)-1] =~ /=>\s*$/ 
	       || (scalar(@linehist) > 1 
		   && @linehist[scalar(@linehist)-2] =~ /=>\s*$/)) {
1140
	    $self->dprint(0,"probeForOutput: found ROM monitor");
1141 1142 1143
	    return 1;
	}
	else {
1144
	    $self->dprint(0,"probeForOutput: got output, but not sure how to parse:" . Dumper(@linehist));
1145 1146 1147 1148
	    return 0;
	}
    }

1149
    return $retval;
1150 1151 1152 1153 1154 1155 1156 1157 1158
}

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

1159
    $self->dprint(0,"_checkFlashSlots($node_id): getting flash contents");
1160 1161 1162 1163 1164 1165
    $retval = $self->expect($nodeobject,\@linehist,undef,
			    { 'timeout' => 3,
			      'presend' => $tchar,
			      'seq' => [ [ '#\s+', "show flash\n", 'line' ],
					 [ '#\s+', undef, 'line'] ] });
    if ($retval < 0) {
1166
	tbwarn "$self _checkFlashSlots($node_id): could not get flash contents: $retval,$!\n";
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
	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 = ();
1201
	$self->dprint(1,"wipeFiles($node_id): getting files in $path");
1202 1203 1204 1205 1206 1207
	$retval = $self->expect($nodeobject,\@linehist,undef,
				{ 'timeout' => 10,
				  'presend' => $tchar,
				  'seq' => [ [ '=>', "ll ${path}\n", 'line' ],
					     [ '=>', undef, 'line'] ] });
	if ($retval < 0) {
1208
	    tbwarn "$self wipeFiles($node_id): could not list configs: $retval,$!\n";
1209 1210 1211 1212 1213 1214
	    return -1;
	}

	my @files = ();
	foreach my $line (@linehist) {
	    chomp($line);
1215 1216 1217
	    $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*$/) {
1218 1219 1220 1221 1222 1223 1224 1225 1226
		push @files, $1;
	    }
	}

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

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

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

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

    if (defined($nodeobject)) {
	my $expt = $nodeobject->Reservation();
	if (defined($expt)) {
	    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 1343
	    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;
	    }
	}
    };

    my @cnetlines = ();
1344 1345 1346 1347 1348 1349 1350 1351
    #
    # 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";
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
    if (defined($cnetport) && $cnetport ne '') {
	push @cnetlines, "vlan 999";
	push @cnetlines, "  name \"EmulabControlPort\"";
	push @cnetlines, "  untagged $cnetport";
	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}";
	    #
1367
	    # don't do this -- assume that the hostkey never gets 
1368 1369 1370 1371
	    # overwritten.  Generating takes too long!  Eventually, maybe
	    # detect if it got wiped and then generate if necessary.
	    #
	    #push @cnetlines, "crypto key generate ssh";
1372
	    #
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
	    # 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";
	}
    }

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    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";
    }

1404 1405 1406
    my @config = (
	"hostname \"" . $node_id . "\"",
	@cnetlines,
1407
	# this prompts; must handle manually!
1408 1409 1410 1411 1412
	#"include-credentials",
	"aaa authentication ssh login public-key",
	"aaa authentication ssh login local",
	@keylines,
	@passwdlines,
1413 1414 1415 1416
	'snmp-server community "' . $community . '" Unrestricted',
	'snmp-server contact "testbed-ops@flux.utah.edu"',
	# try to cover our hind ends and eliminate loops!
	"spanning-tree",
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	"no web-management",
	"no telnet-server",
	"tftp client",
	"no tftp server",
	"no tftp6 client",
	"no tftp6 server",
	"no autorun",
	"no banner motd",
	);

    return @config;
}

sub writeConfig($$$) {
    my ($self,$nodeobject,$configref) = @_;
1432
    my $node_id = $nodeobject->node_id();
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
    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) {
1453
	tberror "$self writeConfig($node_id): could not get into configure terminal mode: $retval, $!\n";
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
	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' ],
					 [ '\?\[y\/n\]\s+$', "y\n", 'line' ],
					 [ '\?\[y\/n\]\s+$', "y\n", 'line' ] ] });
    if ($retval < 0) {
1468
	tbwarn "$self writeConfig($node_id): include-credentials funky, but continuing!: $retval, $!\n";
1469 1470 1471 1472 1473 1474 1475 1476 1477
    }

#    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)
1478
    $self->dprint(0,"writeConfig($node_id): starting main body");
1479 1480 1481 1482 1483 1484
    $retval = $self->expect($nodeobject,undef,undef,
			    { 'timeout' => 90,
			      'presend' => $tchar,
			      'seq' => [ @configseq,
					 [ '#\s*$', undef, 'line'] ] });
    if ($retval < 0) {
1485
	tberror "$self writeConfig($node_id): could not write config: $retval: $!\n";
1486 1487
	return -1;
    }
1488
    $self->dprint(0,"writeConfig($node_id): done");
1489 1490 1491 1492

    return 0;
}

1493 1494
sub uploadImageTftp($$$;$) {
    my ($self,$nodeobject,$filename,$flashedref) = @_;
1495 1496
    my $node_id = $nodeobject->node_id();
    my $retval;
1497
    my $didflash = 0;
1498 1499 1500 1501 1502 1503 1504 1505

    #
    # 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.
    #
1506
    $self->dprint(0,"uploadImageTftp($node_id): starting");
1507 1508 1509 1510 1511 1512

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

    if (system("cp $filename $tmpfilename")) {
1518
	tberror "$self uploadImageTftp($node_id): could not copy $filename to $tmpfilename: $!";
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
	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) {
1540
	tberror "$self uploadImageTftp($node_id): could not enable tftp client on switch: $retval,$!";
1541 1542 1543 1544 1545
	goto failure;
    }

    my @linehist = ();
    $retval = $self->expect($nodeobject,\@linehist,undef,
1546
			    { 'timeout' => 120,
1547 1548 1549 1550 1551
			      'presend' => $tchar,
			      'seq' => [ [ '#\s*$', "copy tftp flash ${BOSSNODE_IP} $tmpfilename\n", 'line' ],
					 [ 'continue \[y\/n\]\?\s*', "y\n", 'line' ],
					 [ '#\s*$', undef, 'line' ] ] });
    if ($retval < 0) {
1552
	tberror "$self uploadImageTftp($node_id): could not upload file via tftp: $retval,$!";
1553 1554
	# we have to assume that it happened
	$didflash = 1;
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
	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;
1573 1574
	# we didn't actually flash anything
	$didflash = 0;
1575 1576 1577
	goto failure;
    }

1578
    $self->dprint(0,"uploadImageTftp($node_id): tftp upload appears successful!");
1579 1580

    unlink($tmpfilename);
1581 1582 1583
    if (defined($flashedref)) {
	$$flashedref = 1;
    }
1584 1585 1586 1587
    return 0;

  failure:
    unlink($tmpfilename);
1588 1589 1590
    if (defined($flashedref)) {
	$$flashedref = $didflash;
    }
1591 1592 1593
    return -1;
}

1594 1595
sub uploadImageXmodem($$$;$) {
    my ($self,$nodeobject,$filename,$flashedref) = @_;
1596 1597 1598 1599 1600 1601 1602
    my $node_id = $nodeobject->node_id();
    my $retval;

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

1603 1604
    $self->dprint(0,"uploadImageXmodem($node_id): starting");

1605 1606 1607 1608
    if (defined($flashedref)) {
	$$flashedref = 0;
    }

1609 1610 1611 1612
    #
    # Ok, we're here... let's setup the load.  Change speeds on both switch and
    # capture.  Then do the expect dance, and trigger lsz.
    #
1613
    $self->dprint(1,"uploadImageXmodem($node_id): changing speed to 115200 for upload");
1614 1615
    syswrite($chout,"speed 115200\n");
    if ($retval = $self->setSpeed($nodeobject,115200)) {
1616
	tberror "$self uploadImageXmodem($node_id): setSpeed failed with $retval, $!\n";
1617 1618 1619
	return -1;
    }

1620
    if (1) {
1621
	$self->dprint(1,"uploadImageXmodem($node_id): running initxmodem");
1622 1623 1624
	$retval = $self->expect($nodeobject,undef,undef,
				$sequences{'initxmodem'});
	if ($retval < 0) {
1625
	    tberror "$self uploadImageXmodem($node_id): initxmodem expect sequence failed: $retval, $!\n";
1626 1627
	    return -1;
	}
1628 1629 1630 1631 1632 1633

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

1634
	$self->dprint(1,"uploadImageXmodem($node_id): hooking up lsz child");
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
	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);
	}

1646
	$self->dprint(1,"uploadImageXmodem($node_id): parent waiting for child $pid");
1647
	$retval = waitpid($pid,0);
1648
	$retval = $? >> 8;
1649 1650 1651 1652 1653 1654

	#
	# 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.
	#
1655
	$self->dprint(1,"uploadImageXmodem($node_id): child returned $retval");
1656

1657 1658 1659 1660 1661 1662 1663 1664
	if ($retval) {
	    return -1;
	}

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

1665
	$self->dprint(1,"uploadImageXmodem($node_id): running finishxmodem");
1666 1667 1668
	$retval = $self->expect($nodeobject,undef,undef,
				$sequences{'finishxmodem'});
	if ($retval < 0) {
1669
	    tberror "$self uploadImageXmodem($node_id): finishxmodem expect sequence failed: $retval, $!\n";
1670 1671 1672 1673
	    return -1;
	}
    }
    else {
1674
	$self->dprint(1,"uploadImageXmodem($node_id): skipping imaging and reloading, rebooting");
1675 1676 1677
	$retval = $self->expect($nodeobject,undef,undef,
				$sequences{'reboot'});
	if ($retval < 0) {
1678
	    tberror "$self uploadImageXmodem($node_id): skipping imaging and reboot failed: $retval, $!\n";
1679 1680 1681 1682
	    return -1;
	}
    }

1683
    $self->dprint(1,"uploadImageXmodem($node_id): flipping capture to default speed");
1684
    if ($retval = $self->setSpeed($nodeobject,$DEFSPEED)) {
1685
	tbwarn "$self uploadImageXmodem($node_id): setSpeed($DEFSPEED) failed with $retval, $!\n";
1686 1687 1688
	return -1;
    }

1689
    $self->dprint(1,"uploadImageXmodem($node_id): waiting for switch to boot");
1690 1691 1692
    $retval = $self->expect($nodeobject,undef,undef,
			    $sequences{'bootAfterLoad'});
    if ($retval < 0) {
1693
	tberror "$self uploadImageXmodem($node_id): bootAfterLoad expect sequence failed: $retval, $!\n";
1694 1695 1696
	return -1;
    }

1697
    $self->dprint(0,"uploadImageXmodem($node_id): success!");
1698 1699 1700
    return 0;
}

1701 1702
sub expect($$$$$;$) {
    my ($self,$nodeobject,$histbufref,$databufref,$seqref,$seqnumref) = @_;
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
    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));

1715
    my ($timeout,@seqs,$presend,$drain);
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
    if (exists($seqref->{'timeout'})) {
	$timeout = $seqref->{'timeout'};
    }
    if (exists($seqref->{'seq'})) {
	@seqs = @{$seqref->{'seq'}};
    }
    else {
	return -5;
    }
    if (exists($seqref->{'presend'})) {
	$presend = $seqref->{'presend'};
    }
1728 1729 1730
    if (exists($seqref->{'drain'})) {
	$drain = $seqref->{'drain'};
    }
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742

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

1743 1744
    if (defined($presend) || (defined($drain) && $drain)) {
	$self->dprint(3,"expect: draining");
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767

	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/) {
1768
		$self->dprint(2,"expect: select interrupted, retrying");
1769 1770 1771 1772 1773 1774 1775 1776
		sleep(1);
	    }
	    if ($retval < 0) {
		tbwarn "$self expect: error in select: $retval,$!\n";
		$rc = -2;
		goto out;
	    }
	    elsif ($retval == 0) {
1777
		$self->dprint(2,"expect: select found nothing to read!");
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
		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]/) {
1805
		    $self->dprint(4,"expect: esc $escseq");
1806 1807 1808 1809 1810 1811 1812 1813 1814
		    $escseq = undef;
		}
		next;
	    }

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

	    if ($char eq "\n") {
1815
		$self->dprint(4,"expect: drain rotating line buf");
1816 1817 1818 1819 1820
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];
	    }
	}

1821 1822 1823 1824
	if (defined($presend)) {
	    $self->dprint(3,"expect: presending '$presend'");
	    syswrite($out,$presend);
	}
1825 1826 1827 1828 1829 1830 1831
    }

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

1832
	$self->dprint(3,"expect: looking for '$rval':");
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857

	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/) {
1858
		$self->dprint(2,"expect: select interrupted, retrying");
1859 1860 1861 1862 1863 1864 1865 1866
		sleep(1);
	    }
	    if ($retval < 0) {
		tberror "$self expect: error in select: $retval,$!\n";
		$rc = -2;
		goto out;
	    }
	    elsif ($retval == 0) {
1867
		$self->dprint(2,"expect: select found nothing to read!");
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
		$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]/) {
1908
		    $self->dprint(4,"expect: esc $escseq");
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
		    $escseq = undef;
		}
		next;
	    }

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

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

1922
	    $self->dprint(4,"expect: checking if '".$$mdataref."' matches '$rval'");
1923
	    if ($$mdataref =~ $rval) {
1924
		$self->dprint(2,"expect: '".$$mdataref."' matched '$rval'!");
1925 1926 1927
		if (defined($sval)) {
		    if (ref($sval) eq 'CODE') {
			$sval->($out);
1928
			$self->dprint(3,"expect: ran code instead of sending!");
1929 1930 1931
		    }
		    else {
			syswrite($out,$sval);
1932
			$self->dprint(3,"expect: sent '$sval'");
1933 1934 1935
		    }
		}
		else {
1936
		    $self->dprint(3,"expect: matched but not sending because undef was given");
1937
		}
1938
		$self->dprint(4,"expect: rotating line buf at match");
1939 1940 1941 1942 1943 1944 1945
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];

		$found = $localfound = 1;
	    }

	    if ($char eq "\n") {
1946 1947
		$self->dprint(4,"read '".chomp($$lineref)."' while looking for '$rval'\n");
		$self->dprint(4,"expect: rotating line buf at newline");
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
		$histbufref->[scalar(@$histbufref)] = '';
		$lineref = \$histbufref->[scalar(@$histbufref)-1];
	    }

	    last if ($localfound);
	}
    }

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

  out:
1964 1965 1966 1967 1968 1969 1970
    # 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;
    }
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
    #
    # 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;