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

=pod
26

27 28
Send a UDP message to this node, containing a 
libwanetmon::serialize_hash() hash
29 30
with the following key/value pairs:

31 32
cmdtype => one of the following types, and associated key/values
           (examples given)
33 34 35 36 37 38 39
EDIT:
dstnode  => plab2
testtype => latency or bw
testper  => 30
INIT:
  ** todo **
destnodes => "plab1 plab2"
40
SINGLE: ** DEPRECIATED **
41 42
dstnode => plabxxx
testtype => latency or bw
43 44
STOPALL:
STATUS: *TODO*
45 46 47 48

where,
EDIT: Modify a specific link test to specific destination node.
INIT: Initialize the link tests with default destination nodes and frequency.
49 50
    Measurements to nodes not in init set but already scheduled 
    will not be erased or changed.
51

52
SINGLE ** DEPRECIATED **: Perform a single link test to a specifc destination node.
53 54 55 56
STOPALL: Erase all scheduled measurements.
STATUS: get status of bgmon as a string description. In the reply,
        the message contains "ACK\n" followed by the status string terminated
        by  "\n"
57

58
*TODO* ACK documentation?
59

60 61 62 63 64 65

OPERATION NUANCES:
- If a ping test is scheduled to have a period shorter than the normal
  latency to the destination, pings will be run sequentially one after
  the other. There will be no simultaneous tests of the same type to the same
  destination.
66
- If a path latency is longer than 60 seconds, an error value is reported
67 68 69 70
  instead of a latency (milliseconds) value. See %ERRID
- If a testing process abnormally exits with a value not 0 (say, iperf dies),
  then the test is rescheduled to be run at a future time. This time is
  the normal period times the %TEST_FAIL_RETRY ratio. (TODO: add error
71 72 73 74
  reporting here.) CHANGED: 8/3/06  This behavior has changed to the following:
    - regardless of the return value, parsing the results continues as normal,
      with the parsing function dealing with setting the error codes in the
      result.
75 76 77
- If a node/sliver is rebooted, our startup script should run and re-start
  bgmon. However, the current state of running tests is lost (on purpose!).
  The management application can query the status using the STATUS command
78 79 80 81 82
=cut

use Getopt::Std;
use strict;
use DB_File;
83 84
use IO::Socket::INET;
use IO::Select;
85
use libwanetmon;
86
use Cmdqueue;
87 88

$| = 1;
89 90

sub usage {
Dan Gebhardt's avatar
Dan Gebhardt committed
91 92
        warn "Usage: $0 [-s server] [-c cmdport] [-a ackport] [-p sendport] [-e pid/eid] <-d working_dir> [hostname]\n";
        return 1;
93 94
}

95 96 97 98
#
# Continuous ping hack
#
my $CONT_THRESHOLD = 2;		# if period < this value (sec), go continuous
99 100

#*****************************************
101
my $pollPer = 0.1;  #number of seconds to sleep between poll loops
102
my %MAX_SIMU_TESTS = (latency => "10",
Dan Gebhardt's avatar
Dan Gebhardt committed
103 104
                      bw      => "1",
                      outage  => "10");
105
my $cacheSendRate = 5;  #number of cached results per second
106 107
my %cacheLastSentAt;    #{indx} -> tstamp of last sent cache result
my $cacheIndxWaitPer = 5; #wait x sec between cache send attempts of same indx
108
my $iperfduration = 5;  #length of each iperf test in seconds
109
my $iperftimeout = 30;   #kill an iperf process lasting longer than this.
110 111
my $fpingTimeoutDef = 10000; #milliseconds for fping to timeout
my $outManID = "outageMan"; #name to use for ManagerID when an outage is detctd
112 113
my $outDet_maxPastSuc = 12; #consider a path for outage detection if a valid
                            #result appeared within this many hours in the past
114
my %outTestFreq = ( high  => 1,
Dan Gebhardt's avatar
Dan Gebhardt committed
115 116 117
                    med   => 10,
                    low   => 600,
                    outageEnd=> 10 );
118
my %outTestDur =  ( high  => 60,
Dan Gebhardt's avatar
Dan Gebhardt committed
119 120 121
                    med   => 60,
                    low   => 0,
                    outageEnd=> 120 );
122 123

=pod
124 125
# percentage of testing period to wait after a test process abnormally exits
# note: 0.1 = 10%
126
my %TEST_FAIL_RETRY= (latency => 0.3,
Dan Gebhardt's avatar
Dan Gebhardt committed
127
                      bw      => 0.5);
128
=cut  
129 130
my $rcvBufferSize = 2048;  #max size for an incoming UDP message
my %outsockets = ();       #sockets keyed by dest node
131 132
#MARK_RELIABLE
# each result waiting to be acked has an id number and corresponding file
133
my $resultDBlimit = 12000;  #approx 24 hours of data at "normal" test rates
134
my $magic         = "0xDeAdBeAf";
135

136 137
my %testevents = ();
#queue for each test type containing tests that need to
138
# be run.
139
my %waitq = ( latency => [],
Dan Gebhardt's avatar
Dan Gebhardt committed
140
              bw      => [] );
141
my %runningtestPIDs = ();  # maps from PID's -> array of destnode, bw
142 143 144 145
my $status;  #keeps track of status of this bgmon. Possible values are:
             # anyscheduled_no, anyscheduled_yes
$status = "anyscheduled_no";

146 147 148 149 150
#*****************************************
# PROTOTYPES
sub sendOldResults;
sub spawnTest($$);
sub getRunningTestsCnt($);
151
sub parsedata($$$);
152 153 154 155 156 157 158 159 160
sub printTimeEvents;
sub saveTestToLocalDB($);
sub delLocalDBEntry($);
sub sendResults($$);
sub createtmpfilename($$);
sub createDBfilename();
sub detectHang($);
sub isMsgValid(\%);
sub updateTestEvent($);
161 162
sub addCmd($$);
sub updateOutageState($);
163
sub updateOutageState_lossCheck($);
164
sub initTestEv($$$$$$$);
165 166 167
sub getstats;
sub diffstats($$);
sub printstats($$);
168 169 170
#*****************************************

my %opt = ();
171
getopts("s:c:a:p:e:d:i:hC",\%opt);
172 173 174 175

#if ($opt{h}) { exit &usage; }
#if (@ARGV > 1) { exit &usage; }

176
my ($server, $cmdport, $cmdackport, $sendport, $ackport,$expid,$workingdir,$iperfport, $nocontinuous);
177 178

if ($opt{s}) { $server = $opt{s}; } else { $server = "ops"; }
179
if ($opt{c}) { $cmdport = $opt{c}; } else { $cmdport = 5052; }
180 181 182
if ($opt{a}) { $ackport = $opt{a}; } else { $ackport = 5050; }
if ($opt{p}) { $sendport = $opt{p}; } else { $sendport = 5051; }
if ($opt{e}) { $expid = $opt{e}; } else { $expid = "none"; }
183
if ($opt{d}) { $workingdir = $opt{d}; chdir $workingdir; }
184
if ($opt{i}) { $iperfport = $opt{i}; } else { $iperfport = 5002; }
185 186 187
if ($opt{C}) { $nocontinuous = 1; }

my $debug = 1;
188

189 190 191 192 193 194
my $thismonaddr;
if( defined  $ARGV[0] ){
    $thismonaddr = $ARGV[0];
}else{
    $_ = `cat /var/emulab/boot/nodeid`;
    /plabvm(\d+)-/;
195
    if( defined $1 ){
Dan Gebhardt's avatar
Dan Gebhardt committed
196
        $thismonaddr = "plab$1" ;
197
    }else{
Dan Gebhardt's avatar
Dan Gebhardt committed
198 199
        $thismonaddr = `hostname`;
        chomp $thismonaddr;
200
    }
201 202
}
print "thismonaddr = $thismonaddr\n";
203 204 205
print "command-port = $cmdport\n";
print "result send port = $sendport\n";
print "ackport = $ackport\n";
206

207 208 209
# initialize seed for random number generation
srand (time ^ unpack "%L*", `uname -a`);

210
# Create a TCP socket to receive commands on
211
my $socket_cmd = IO::Socket::INET->new( LocalPort => $cmdport,
212
#TODO: added this as comment, in case it breaks: LocalHost => $thismonaddr,
Dan Gebhardt's avatar
Dan Gebhardt committed
213 214 215 216
                                        Proto    => 'tcp',
                                        Blocking => 0,
                                        Listen   => 1,
                                        ReuseAddr=> 1 )
217 218 219
    or die "Couldn't create socket on $cmdport\n";
# Create a UDP socket to receive acks on
my $socket_ack = IO::Socket::INET->new( LocalPort => $ackport,
Dan Gebhardt's avatar
Dan Gebhardt committed
220
                                        Proto    => 'udp' )
221
    or die "Couldn't create socket on $ackport\n";
222

223
my $socket_snd = IO::Socket::INET->new( PeerPort => $sendport,
Dan Gebhardt's avatar
Dan Gebhardt committed
224 225
                                        Proto    => 'udp',
                                        PeerAddr => $server );
226

227 228 229 230
#create Select object.
my $sel = IO::Select->new();
$sel->add($socket_cmd);
$sel->add($socket_ack);
231

232
my $subtimer_reset = 10;  # subtimer reaches 0 this many times thru poll loop
233 234
my $subtimer = $subtimer_reset;  #decrement every poll-loop.

235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
#
# XXX / TODO: This is a hack to keep the "outage detection"
# stuff working.  Outage detection should probably be its own tool.
#
sub hacky_evalLatencyResult($){
    my ($result) = @_;
    my %eval_result = (split(/[=,]/, $result));
    if( $eval_result{error} != 0 ){
        return -1;
    }else{
        return $eval_result{latency};
    }
}


251 252 253
sub handleincomingmsgs()
{
    my $inmsg;
254
    my $cmdHandle;
255

256
    my @ready = $sel->can_read($pollPer);
257
    foreach my $handle (@ready){
Dan Gebhardt's avatar
Dan Gebhardt committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        my %sockIn;
        if( $handle eq $socket_ack ){
            $handle->recv( $inmsg, $rcvBufferSize );
            %sockIn = %{ deserialize_hash($inmsg) };
        }elsif( $handle eq $socket_cmd ){
            $cmdHandle = $handle->accept();
            $inmsg = <$cmdHandle>;
            chomp $inmsg;
            %sockIn = %{ deserialize_hash($inmsg) };
            if( !isMsgValid(%sockIn) ){
                close $cmdHandle;
                return 0; 
            }
            print $cmdHandle "ACK\n";
            
        }
#       print "received msg: $inmsg\n";

        if( !isMsgValid(%sockIn) ){ return 0; }

        my $cmdtype = $sockIn{cmdtype}; 
        if( $cmdtype eq "ACK" ){
            my $index = $sockIn{index};
            my $tstamp =$sockIn{tstamp};

            # delete cache entry if ACK tstamp  matches the actual stored data
            my %db;
            my $filename = createDBfilename();
            tie( %db, "DB_File", $filename) or 
                eval {
                    warn time()." cannot open db file";
                    return -1;
                };
            my %results = %{ deserialize_hash($db{$index}) };
292
#            print time()." Ack for index $index. Deleting cache entry\n";
Dan Gebhardt's avatar
Dan Gebhardt committed
293 294 295 296 297 298 299 300 301 302 303 304 305
            print "rcved ACK, but UDP/tstamp not defined\n" 
                if( !defined $tstamp );
            print "rcved ACK, but dbfile/tstamp not defined\n" 
                if( !defined $results{tstamp} );
            delLocalDBEntry($index)
                if( $tstamp eq $results{tstamp} );
        }
        elsif( $cmdtype eq "EDIT" ){
            my $linkdest = $sockIn{dstnode};
            my $testtype = $sockIn{testtype};
            my $newtestper = $sockIn{testper};
            my $duration =$sockIn{duration};
            my $managerID=$sockIn{managerID};
306 307 308 309 310 311 312 313 314 315 316 317

            #XXX / TODO: How to handle tool parameterization if an
            #EDIT comes in with a different toolname, etc..!
            # -- what are the issues?
            initTestEv(
                $linkdest,$testtype,
                $sockIn{toolname},
                $sockIn{toolwrapperpath},
                $sockIn{tooltype},
                $sockIn{req_params},
                $sockIn{opt_params}
                );
Dan Gebhardt's avatar
Dan Gebhardt committed
318 319
            my $testev = \%{ $testevents{$linkdest}{$testtype} };

320 321 322 323 324 325
#            print time()." EDIT:\n";
#            print( "linkdest=$linkdest\n".
#                   "testype =$testtype\n".
#                   "testper=$newtestper\n" );
#            print "duration=".$sockIn{duration}."\n" 
#                if( defined $sockIn{duration} );
Dan Gebhardt's avatar
Dan Gebhardt committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

            #add new cmd to queue
            addCmd( $testev, Cmd->new($managerID, $newtestper, $duration) );
        }
        elsif( $cmdtype eq "INIT" ){
            print time()." INIT: ";
            my $testtype = $sockIn{testtype};
            my @destnodes 
                = split(" ",$sockIn{destnodes});
#           my $testper = $sockIn{testper};
            my $newtestper = $sockIn{testper};
            my $duration =$sockIn{duration};
            my $managerID=$sockIn{managerID};
            
            #distribute start times from offset 0 to testper/2
341
#TODO: HANDLE OFFSET SOMEWHERE!!
Dan Gebhardt's avatar
Dan Gebhardt committed
342 343 344 345 346
            my $offsetinc = 0;
            if( (scalar @destnodes) != 0 ){
                $offsetinc = $newtestper/(scalar @destnodes)/2.0;
            }
            my $offset = 0;
347
            foreach my $linkdest (@destnodes){
348 349 350 351 352 353 354 355 356
#                initTestEv($linkdest,$testtype);
                initTestEv(
                    $linkdest,$testtype,
                    $sockIn{toolname},
                    $sockIn{toolwrapperpath},
                    $sockIn{tooltype},
                    $sockIn{req_params},
                    $sockIn{opt_params}
                    );
Dan Gebhardt's avatar
Dan Gebhardt committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
                my $testev = \%{ $testevents{$linkdest}{$testtype} };
                #add new cmd to queue
                addCmd( $testev, 
                        Cmd->new($managerID, $newtestper, $duration) );
                $offset += $offsetinc;
            }
            print " $testtype  $newtestper\n";
        }
        elsif( $cmdtype eq "STOPALL" ){
            print time()." STOPALL\n";
            my $managerID=$sockIn{managerID} if( defined $sockIn{managerID} );

            #delete those entries of this managerID
            for my $destaddr ( keys %testevents ) {
                for my $testtype ( keys %{ $testevents{$destaddr} } ){
                    my $testev = \%{ $testevents{$destaddr}{$testtype} };
                    #update scheduled tests in case something changed
                    if( defined $testev->{cmdq} ){
                        $testev->{cmdq}->rmCmds( $managerID );
                        updateTestEvent( $testev );
                    }
                }
            }
        }
        elsif( $cmdtype eq "DIE" ){
            die "Received termination command. Exiting.\n";
        }
        elsif( $cmdtype eq "GETSTATUS" ){
            if( defined $cmdHandle ){
                print $cmdHandle "$status\n";
            }
        }
        if( defined $cmdHandle ){
            close $cmdHandle;
        }
392 393 394 395 396 397 398 399
    }
}

#
#  MAIN POLL LOOP
#    check for newly sent commands, checks for finished tests,
#    starts new tests, etc..
#
400 401
while (1) {

402 403
    $subtimer--;

404 405
    sendOldResults();

406
    handleincomingmsgs();
407

408 409
    #set status of this bgmon
    if( keys %testevents != 0){
Dan Gebhardt's avatar
Dan Gebhardt committed
410
        $status = "anyscheduled_yes";
411
    }else{
Dan Gebhardt's avatar
Dan Gebhardt committed
412
        $status = "anyscheduled_no";
413 414
    }

415
    #re-try wait Q every $subtimer_reset times through poll loop
416
    #try to run tests on queue
Dan Gebhardt's avatar
Dan Gebhardt committed
417 418 419 420 421
    if( $subtimer == 0 ){       

        foreach my $testtype (keys %waitq){

            if( scalar(@{$waitq{$testtype}}) != 0 ){
422 423 424 425 426
#                print time_all()." $testtype QUEUE: ";
#                foreach my $node (@{$waitq{$testtype}}){
#                    print "$node ";
#                }
#                print "\n";
Dan Gebhardt's avatar
Dan Gebhardt committed
427 428 429 430 431
            }
            #
            # Run next scheduled test
            spawnTest( undef, $testtype );
        }
432 433
    }

434

435 436 437 438 439
    # Reap all dead children.
    #mark flags of finished tests
#    my @deadpids;
    use POSIX ":sys_wait_h";
    while( (my $pid = waitpid(-1,&WNOHANG)) > 0 ){
Dan Gebhardt's avatar
Dan Gebhardt committed
440 441 442 443 444 445 446
        my $destaddr = $runningtestPIDs{$pid}[0];
        my $testtype = $runningtestPIDs{$pid}[1];
        my $testev = \%{ $testevents{$destaddr}{$testtype} };
        # handle the case where a test (iperf) times out and bgmon kills it
        if( $testev->{"timedout"} == 1 ){
            $testev->{"flag_scheduled"} = 0;
            $testev->{"timedout"} = 0;
447
            
Dan Gebhardt's avatar
Dan Gebhardt committed
448 449 450 451 452
        }elsif( defined $testev ){
            $testev->{"flag_finished"} = 1;
        }
        $testev->{"pid"} = 0;
        delete $runningtestPIDs{$pid};  
453
    } 
454

455 456 457 458 459
    #
    # Check status of running tests.
    # * if a continuous test has produced more output, sechedule an event
    # * check for running tests which are taking too long and kill them
    #
460
    foreach my $pid (keys %runningtestPIDs){
Dan Gebhardt's avatar
Dan Gebhardt committed
461 462 463
        my $destaddr = $runningtestPIDs{$pid}[0];
        my $testtype = $runningtestPIDs{$pid}[1];
        my $testev = \%{ $testevents{$destaddr}{$testtype} };
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        my $killit = 0;

        if ($testev->{"continuous"}) {
            my $filename = $testev->{"outfile"};
            my $fsize = $testev->{"lastsize"};
            my $cursize = (stat($filename))[7];
            print time_all().": c$testtype test: fn=$filename, fs=$cursize, lastfs=$fsize\n" if ($debug > 1);
            if (defined($cursize)) {
                if ($cursize > $fsize) {
                    $testev->{"new_results"} = $fsize;
                    $testev->{"tstamp"} = time_all();
                } else {
                    undef $testev->{"new_results"};
                }
            } else {
                # something is horribly wrong, kill the process
                $killit = "no output file";
            }
        }
Dan Gebhardt's avatar
Dan Gebhardt committed
483 484 485 486 487 488
        if( $testtype eq "bw" &&
            time_all() >
            $testev->{"tstamp"} + 
            $iperftimeout )    
        {
            # bw test is running too long, so kill it
489 490
            $killit = "timeout";
        }
Dan Gebhardt's avatar
Dan Gebhardt committed
491

492
        if ($killit) {
Dan Gebhardt's avatar
Dan Gebhardt committed
493
            kill 'TERM', $pid;
494
            print time_all()." $testtype $killit: killed $destaddr, ".
Dan Gebhardt's avatar
Dan Gebhardt committed
495 496 497 498 499
                "pid=$pid\n";

            $testev->{"timedout"} = 1;

            #delete tmp filename
500
            my $filename = $testev->{"outfile"};
Dan Gebhardt's avatar
Dan Gebhardt committed
501
            unlink($filename) or warn "can't delete temp file";
502 503 504 505 506 507
            undef $testev->{"new_results"};
            undef $testev->{"lastsize"};
#
# The special iperf timeout hack is to be handled by the iperf wrapper.
#
=pod            
Dan Gebhardt's avatar
Dan Gebhardt committed
508 509 510 511 512 513 514
            my %results = 
                ("sourceaddr" => $thismonaddr,
                 "destaddr" => $destaddr,
                 "testtype" => $testtype,
                 "result" => $ERRID{timeout},
                 "tstamp" => $testev->{tstamp},
                 "magic"  => "$magic",
515
                 "ts_finished" => time()
516
                );
Dan Gebhardt's avatar
Dan Gebhardt committed
517 518 519 520
            #save result to local DB
            my $index = saveTestToLocalDB(\%results);
            #send result to remote DB
            sendResults(\%results, $index);
521
=cut
Dan Gebhardt's avatar
Dan Gebhardt committed
522
        }
523 524 525 526 527

    }

    #iterate through all event structures
    for my $destaddr ( keys %testevents ) {
Dan Gebhardt's avatar
Dan Gebhardt committed
528
        for my $testtype ( keys %{ $testevents{$destaddr} } ){
529
            
Dan Gebhardt's avatar
Dan Gebhardt committed
530
            my $testev = \%{ $testevents{$destaddr}{$testtype} };
531
            
Dan Gebhardt's avatar
Dan Gebhardt committed
532
            #check for finished events
533
            if( $testev->{"flag_finished"} == 1 ||
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
                ($testev->{"continuous"} &&
                 defined($testev->{"new_results"})) ){
                my @raw_lines;
                
                #read raw results from temp file
                #  NOTE: parsing is now done in the wrapper, and we return the
                #  entire wrapper output
                # this stuff left in for the "continuous hack" (for now)
                my $filename = $testev->{"outfile"};
                if (!$testev->{"flag_finished"} ||
                    !$testev->{"continuous"}) {
                    open FILE, "< $filename"
                        or warn "can't open file $filename";
                    if ($testev->{"new_results"}) {
                        seek(FILE, $testev->{"new_results"}, 0);
                    }
                    @raw_lines = <FILE>;
                    if (!$testev->{"flag_finished"}) {
                        $testev->{"lastsize"} = tell(FILE);
                    }
                    close FILE;
                }
                
                if ($testev->{"flag_finished"}) {
                    unlink($filename) or warn "can't delete temp file";
                    undef $testev->{"new_results"};
                    undef $testev->{"lastsize"};
                } else {
                    print "c$testtype test: read ", scalar(@raw_lines),
                    " lines, size=", $testev->{"lastsize"}, "\n" if ($debug > 1);
564 565 566 567 568 569 570 571 572 573 574 575
		}

		#
		# XXX should pass each line individually for a continuous
		# test as it might represent multiple probes.  However, we
		# currently don't have per-line timestamps so the multiple
		# lines would all have the same timestamp and all but one
		# will be discarded anyway.
		#
		if (@raw_lines) {
		    my $raw;
		    foreach my $line (@raw_lines){
576
                $raw = $raw.$line;
577 578 579
		    }

		    #parse raw data
580
#            print "RAW data = $raw\n";
581
		    my $parsedData = parsedata($testtype,
582 583
                                       $testev->{"continuous"},
                                       $raw);
584 585 586 587 588 589 590 591 592 593
		    $testev->{"results_parsed"} = $parsedData;

		    my %results = 
			("sourceaddr" => $thismonaddr,
			 "destaddr" => $destaddr,
			 "testtype" => $testtype,
			 "result" => $parsedData,
			 "tstamp" => $testev->{tstamp},
			 "magic"  => "$magic",
			 "ts_finished" => time()
594 595 596 597 598
             ,"toolname" => $testev->{toolname}
             ,"toolwrapperpath" => $testev->{toolwrapperpath}
             ,"tooltype" => $testev->{tooltype}
             ,"req_params" => $testev->{req_params}
             ,"opt_params" => $testev->{opt_params}
599 600 601 602 603 604 605 606 607
			 );

		    #MARK_RELIABLE
		    #save result to local DB
		    my $index = saveTestToLocalDB(\%results);

		    #send result to remote DB
		    sendResults(\%results, $index);
		}
Dan Gebhardt's avatar
Dan Gebhardt committed
608 609

                #reset flags
610 611 612 613 614 615 616 617 618 619 620 621 622 623
		if ($testev->{"flag_finished"}) {
		    $testev->{"flag_finished"} = 0;
		    $testev->{"flag_scheduled"} = 0;
		}

		# XXX avoid for continuous til I understand
		if (@raw_lines) {
		    # Check for outage
		    if( $testtype eq "latency" ){
			updateOutageState( $destaddr );
		    }elsif( $testtype eq "outage" ){
			updateOutageState_lossCheck( $destaddr );
		    }
		}
Dan Gebhardt's avatar
Dan Gebhardt committed
624 625 626 627 628 629 630 631 632 633 634
            }

            #schedule new tests
            if( $testev->{"flag_scheduled"} == 0 && 
                $testev->{"testper"} > 0 )
            {
                
                if( $testev->{limitTime} > 0 &&
                    time() >= $testev->{limitTime} )
                {
                    my $oldper = $testev->{testper};
635 636 637 638 639 640
                    print time().": Ending test $testtype for $destaddr\n";
                    $testev->{"end_stats"} = getstats();
                    printstats("End", $testev->{"end_stats"});
                    my $diff = diffstats($testev->{"start_stats"},
                                         $testev->{"end_stats"});
                    printstats("Total", $diff);
Dan Gebhardt's avatar
Dan Gebhardt committed
641 642 643
                    # Rate increase expired. Get new value from Q
                    $testev->{cmdq}->cleanQueue();  #rid expired values
                    $testev->{testper} = 0;  #reset existing period
644
                    undef $testev->{continuous};
Dan Gebhardt's avatar
Dan Gebhardt committed
645 646 647 648 649 650 651 652 653 654 655
                    updateTestEvent($testev);
                    print "resetting period from $oldper";
                    print " to ".$testev->{testper}."\n";
                }

                if( time_all() < 
                    $testev->{"timeOfNextRun"} + $testev->{"testper"} )
                {
                    #if time of next run is in the future, set it to that
                    $testev->{"timeOfNextRun"} += $testev->{"testper"};
                }else{
656 657 658 659 660 661 662 663 664 665 666 667
                    if ( ($testev->{"timeOfNextRun"}  == 0) &&
                         ( $testev->{"managerID"} eq "automanagerclient" ) &&
                         ($testtype eq "bw" ) ) {
                        # init the test based on random initial time
                        my $range = $testev->{"testper"} - 2 * $iperfduration;
                        my $random_init = int(rand($range));
                        $testev->{"timeOfNextRun"} =  time_all() + $random_init;
                    } else {
                        #if time of next run is in the past, set to current time
                        $testev->{"timeOfNextRun"}
                        = time_all();
                    }
Dan Gebhardt's avatar
Dan Gebhardt committed
668 669 670 671 672 673 674 675 676 677 678
                }

                $testev->{"flag_scheduled"} = 1;
            }

            #check for new tests ready to run
            if( $testev->{"timeOfNextRun"} <= time_all() &&
                $testev->{"flag_scheduled"} == 1 && 
                $testev->{"pid"} == 0 )
            {
                #run test
679 680 681 682
                print time().": Starting test $testtype for $destaddr\n"
                    if( $debug > 1 );
                $testev->{"start_stats"} = getstats();
                printstats("Start", $testev->{"start_stats"});
Dan Gebhardt's avatar
Dan Gebhardt committed
683 684 685 686 687 688 689 690 691 692 693 694
                spawnTest( $destaddr, $testtype );
            }

        }#end loop

        # may not be needed, but may help detect errors
        my $hangres = detectHang($destaddr);
        if( $hangres eq "bw" ){
            print "HANG: $hangres,  $destaddr\n";
            # reset time of next run
            $testevents{$destaddr}{bw}{"timeOfNextRun"} = time_all();
        }
695 696
    }

697
    if( $subtimer == 0 ){
Dan Gebhardt's avatar
Dan Gebhardt committed
698
        $subtimer = $subtimer_reset;
699 700 701
    }
}

702

703 704 705
my $iterSinceLastRun = 0;  #when cacheSendRate < 1/pollPer, only send old
                           # results a fraction of the number of calls to
                           # sendOldResults
706 707
sub sendOldResults()
{
708 709 710
    #
    # Check for results that could not be sent due to error. We want to wait
    # a little while though to avoid resending data that has yet to be
711
    # acked because the network is slow or down.
712 713
    #
    my $count    = 0;
Dan Gebhardt's avatar
Dan Gebhardt committed
714
        # Wake up and send only this number at once.
715
    my $maxcount = int( $pollPer*$cacheSendRate );
716

717 718 719
    my %db;
    my $filename = createDBfilename();
    tie( %db, "DB_File", $filename) or 
Dan Gebhardt's avatar
Dan Gebhardt committed
720 721 722 723
        eval {
            warn time()." cannot open db file";
            return -1;
        };
724

725
    my @ids = keys %db;
726
   
727 728
    $iterSinceLastRun++;
    while( ($count < $maxcount && $count < scalar(@ids)) 
Dan Gebhardt's avatar
Dan Gebhardt committed
729
        || ($iterSinceLastRun > (1/($pollPer*$cacheSendRate))) )
730
    {
731
        $count++;
Dan Gebhardt's avatar
Dan Gebhardt committed
732 733 734 735 736 737 738 739
        if( scalar(@ids) == 0 ){
            last;
        }
        my $index = $ids[int( rand scalar(@ids) )];
        my %results = %{ deserialize_hash($db{$index}) };
        next if( (defined $cacheLastSentAt{$index})  &&
                 time() - $cacheLastSentAt{$index} < 
                 $cacheIndxWaitPer );
740
        next if( !defined $results{ts_finished} );
Dan Gebhardt's avatar
Dan Gebhardt committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
        if (!exists($results{"magic"}) || $results{"magic"} ne $magic) {
            # Hmm, something went wrong!
            print "Old results for index $index are scrogged; deleting!\n";
            delLocalDBEntry($index);
            @ids = keys %db;
#           next;
        }

        $iterSinceLastRun = 0;

        #don't send recently completed tests
        next if( time() - $results{ts_finished} < 10 );
        print "sending old result:  $index\n";
        sendResults(\%results, $index);

        $cacheLastSentAt{$index} = time();
757
    }
758

759 760 761 762 763

    untie %db;

    #TODO?: combine re-sends into a large message?

764 765 766 767 768 769 770 771 772 773 774
}

#############################################################################


exit(0);



#############################################################################

775 776 777 778 779
#
# Run a test with the oldest destination on the Q.
#  destination given in parameters is added to Q.
#  if undef is given for destination, just run dest at head of Q.
#
780 781 782 783 784 785
sub spawnTest($$)
{
    my ($linkdest, $testtype) = @_;
    
    use Errno qw(EAGAIN);

786 787 788 789
    #
    #Add to queue if it doesn't exist already
    #  this seach is inefficient... use a hash? sparse array? sorted list?
    my $flag_duplicate = 0;
790
    if( defined $linkdest ){
Dan Gebhardt's avatar
Dan Gebhardt committed
791 792 793 794 795 796 797 798 799
        foreach my $element ( @{$waitq{$testtype}} ){
            if( $element eq $linkdest ){
                $flag_duplicate = 1;
            }
        }
        if( $flag_duplicate == 0 ){
            unshift @{$waitq{$testtype}}, $linkdest;
#           print time_all()." added $linkdest to Q $testtype\n";
        }
800
    }
801

802 803
    #exit and don't fork if the max number of tests is already being run
    if( getRunningTestsCnt($testtype) >= $MAX_SIMU_TESTS{$testtype} ){
Dan Gebhardt's avatar
Dan Gebhardt committed
804
        return -1;
805 806
    }

807 808
    #set the destination to be head of Q.
    if( scalar @{$waitq{$testtype}} == 0 ){
Dan Gebhardt's avatar
Dan Gebhardt committed
809
        return 0;
810 811
    }
    $linkdest = pop @{$waitq{$testtype}};
812
    my $fpingTimeout = $testevents{$linkdest}{$testtype}{fpingTimeout};
813
    my $contin = $testevents{$linkdest}{$testtype}{continuous};
814
#    print time()." running $linkdest / $testtype\n";
815

816
  FORK:{
817
      my $filename = createtmpfilename($linkdest,$testtype);
818
      if( my $pid = fork ){
Dan Gebhardt's avatar
Dan Gebhardt committed
819 820 821 822
          #parent
          #save child pid in test event
          $testevents{$linkdest}{$testtype}{"pid"} = $pid;
          $testevents{$linkdest}{$testtype}{"tstamp"} = time_all();
823 824
          $testevents{$linkdest}{$testtype}{"outfile"} = $filename;
          $testevents{$linkdest}{$testtype}{"lastsize"} = 0;
Dan Gebhardt's avatar
Dan Gebhardt committed
825 826
          $runningtestPIDs{$pid} = [$linkdest, $testtype];
          
827
      }elsif( defined $pid ){
828 829 830 831 832 833 834 835 836 837 838 839
          #child          

          if( $testtype eq "latency" || 
              $testtype eq "bw")
          {
              my $toolwrapperpath 
                  = "$testevents{$linkdest}{$testtype}{toolwrapperpath}";
              my $toolparams =
                  $testevents{$linkdest}{$testtype}{req_params} ." ".
#                  $testevents{$linkdest}{$testtype}{opt_params} .
                  " target $linkdest";
              
840 841
              print "Running test: $toolwrapperpath $toolparams\n"
                  if( $debug > 2 );
842 843 844 845
              exec "sudo $toolwrapperpath $toolparams >$filename 2>&1"
                  or die "can't exec: $!\n";
          }
=pod
Dan Gebhardt's avatar
Dan Gebhardt committed
846 847 848
          #############################
          ###ADD MORE TEST TYPES HERE###
          #############################
849

Dan Gebhardt's avatar
Dan Gebhardt committed
850 851 852
          if( $testtype eq "latency" ){
              #command line for "LATENCY TEST"
#             print "##########latTest\n";
853 854 855
	      my $duration = 0;
	      my $period = $testevents{$linkdest}{$testtype}{"testper"};
	      if ($contin) {
856 857
		  $duration = int($testevents{$linkdest}{$testtype}{"limitTime"})
              - time() + 1;
858
		  if ($duration < 0 || $duration > (24*60*60)) {
859
          $contin = 0;
860 861 862 863 864 865 866 867 868 869
		  }
	      }
	      if ($contin) {
		  # run ping for $duration seconds with the specified interval
		  open FILE, ">$filename"; close FILE;
		  exec "sudo ".
		      "ping -w $duration -i $period $linkdest >$filename 2>&1"
			  or die "can't exec: $!\n";
	      } else {
		  #one ping, using fping
870
          # (2 total attempts, 10 sec timeout between)
871 872 873 874 875
		  exec "sudo $workingdir".
		      "fping -t$fpingTimeout -s -r1 $linkdest >& $filename"
			  or die "can't exec: $!\n";
	      }
	  }elsif( $testtype eq "bw" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
876 877 878
              #command line for "BANDWIDTH TEST"
#             print "###########bwtest\n";
              exec "$workingdir".
879 880 881 882 883
    "iperf -c $linkdest -t $iperfduration -p $iperfport >$filename"
    or die "can't exec: $!";
      }
=cut
          elsif( $testtype eq "outage" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
884 885
              exec "$workingdir".
                  "fping -c16 -p250 $linkdest >& $filename"
886
                  or die "can't exec: $!\n";
Dan Gebhardt's avatar
Dan Gebhardt committed
887 888 889
          }else{
              warn "bad testtype: $testtype";
          }
890
      }elsif( $! == EAGAIN ){
Dan Gebhardt's avatar
Dan Gebhardt committed
891 892 893
          #recoverable fork error, redo;
          sleep 1;
          redo FORK;
894
      }else{ die "can't fork: $!\n";}
895
    }
896
    return 0;
897 898 899 900 901 902 903 904 905
}

sub getRunningTestsCnt($)
{
    my ($type) = @_;
    my $testcount = 0;

    #count currently running tests
    for my $destaddr ( keys %testevents ) {
Dan Gebhardt's avatar
Dan Gebhardt committed
906 907 908 909 910
        if( defined $testevents{$destaddr}{$type} &&
            $testevents{$destaddr}{$type}{"pid"} > 0 ){
            #we have a running process, so inc it's counter
            $testcount++;
        }
911 912 913 914 915
    }
#    print "testcount = $testcount\n";
    return $testcount;
}
#############################################################################
916
sub parsedata($$$)
917 918
{
    my $type = $_[0];
919 920
    my $iscontin = $_[1];
    my $raw = $_[2];
921 922 923 924 925 926 927 928 929 930
    my $parsed;
    $_ = $raw;

#    print "Raw=$_";

    #############################
    ###ADD MORE TEST TYPES HERE###
    #############################
    #latency test
    if( $type eq "latency" ){
931 932 933 934 935 936 937 938 939 940 941 942 943
        
        if ($iscontin) {
            # "traditional" ping output
            if( /icmp_seq=\d+ ttl=\d+ time=([\d\.]+) ms/ ) {
                $parsed = "$1" if ( $1 ne "0.000" );
            }elsif( /unknown host/ ){
                $parsed = $ERRID{unknownhost};
            }elsif( /100% packet loss/ ){
                $parsed = $ERRID{timeout};
            }
        } else {
            $parsed = $raw;
            # fping output
944
=pod
945 946 947 948 949 950 951 952 953 954 955 956
            if( /^ICMP / )
            {
                $parsed = $ERRID{ICMPunreachable};
            }elsif( /address not found/ ){
                $parsed = $ERRID{unknownhost};
            }elsif( /2 timeouts/ ){
                $parsed = $ERRID{timeout};
            }elsif( /[\s]+([\S]*) ms \(avg round trip time\)/ ){
                $parsed = "$1" if( $1 ne "0.00" );
            }else{
                $parsed = $ERRID{unknown};
            }
957
=cut
958
        }
959 960
=pod
        #this section of parsing is for linux ping hosts.
Dan Gebhardt's avatar
Dan Gebhardt committed
961 962 963 964 965 966 967 968 969 970 971
        if(     /100\% packet loss/ ){
            $parsed = $ERRID{timeout};
        }elsif( /Time to live exceeded/ ){ # ?
            $parsed = $ERRID{ttlexceed};
        }elsif( /unknown host/ ){
            $parsed = $ERRID{unknownhost};
        }elsif( /time=(.*)\s?ms/ ){
            $parsed = "$1";
        }else{
            $parsed = $ERRID{unknown};
        }
972
        # This section of parsing is a bit wrong.. for freebsd hosts??
Dan Gebhardt's avatar
Dan Gebhardt committed
973 974 975 976 977 978 979 980 981
        if( /0 packets received/ ){
            $parsed = $ERRID{timeout};
        }elsif( /Time to live exceeded/ ){
            $parsed = $ERRID{ttlexceed};
        }elsif( /time=(.*)\s?ms/ ){
            $parsed = "$1";
        }else{
            $parsed = $ERRID{unknown};
        }
982
=cut
983
    }elsif( $type eq "bw" ){
984 985
        $parsed = $raw;
=pod
Dan Gebhardt's avatar
Dan Gebhardt committed
986 987
        if(    /connect failed: Connection timed out/ ){
            # this one shouldn't happen, if the timeout check done by
988
            # bgmon is set low enough.
Dan Gebhardt's avatar
Dan Gebhardt committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
            $parsed = $ERRID{timeout};
        }elsif( /write1 failed:/ ){
            $parsed = $ERRID{iperfHostUnreachable};
        }elsif( /error: Name or service not known/ ){
            $parsed = $ERRID{unknownhost};
        }elsif( /\s+(\S*)\s+([MK])bits\/sec/ ){
            $parsed = $1;
            if( $2 eq "M" ){
                $parsed *= 1000;
            }
        }else{
            $parsed = $ERRID{unknown};
        }
#       print "parsed=$parsed\n";
1003
=cut
1004
    }elsif( $type eq "outage" ){
1005
        #print "parsing Outage data\n";
Dan Gebhardt's avatar
Dan Gebhardt committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        if( /loss = \d+\/\d+\/([\d.]+)%/ ){
            $parsed = $1;
        }else{
            $parsed = "";
        }
        if( defined($parsed) && 
            $parsed < 100 )
        {
            $parsed = "lossy";
        }elsif( $parsed == 100 ){
            $parsed = "down";
        }
1018
        #print "parsed data = $parsed\n";
1019
    }
1020
    
1021 1022 1023 1024 1025 1026 1027
    return $parsed;
}


#############################################################################
sub printTimeEvents {
    for my $destaddr ( keys %testevents ) {
Dan Gebhardt's avatar
Dan Gebhardt committed
1028 1029 1030 1031 1032 1033 1034
        for my $testtype ( keys %{ $testevents{$destaddr} } ){
            print 
                "finished? ".
                $testevents{$destaddr}{$testtype}{"flag_finished"}."\n".
                "scheduled?= ".
                $testevents{$destaddr}{$testtype}{"flag_scheduled"}."\n".
                "testper?= ".
1035
                $testevents{$destaddr}{$testtype}{"testper"}."\n".
Dan Gebhardt's avatar
Dan Gebhardt committed
1036 1037 1038 1039 1040
                "timeOfNextRun= ".
                $testevents{$destaddr}{$testtype}{"timeOfNextRun"}."\n" .
                "results_parsed= ".
                $testevents{$destaddr}{$testtype}{"results_parsed"}."\n";
        }
1041 1042 1043 1044 1045 1046
    }
}



#############################################################################
1047
#MARK_RELIABLE
1048 1049
sub saveTestToLocalDB($)
{
1050
    my ($results) = @_;
1051
    
1052 1053 1054
    my %db;
    my $filename = createDBfilename();
    tie( %db, "DB_File", $filename ) or 
Dan Gebhardt's avatar
Dan Gebhardt committed
1055 1056 1057 1058
        eval {
            warn time()." cannot create db file";
            return -1;
        };
1059

1060 1061 1062 1063 1064
    #
    # Find an unused index. Leave zero unused to indicate we ran out.
    #
    my $index;
    for ($index = 1; $index < $resultDBlimit; $index++) {
Dan Gebhardt's avatar
Dan Gebhardt committed
1065 1066
        last
            if( !defined($db{$index}) );
1067 1068
    }
    return 0
Dan Gebhardt's avatar
Dan Gebhardt committed
1069
        if ($index == $resultDBlimit);
1070

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    
    $db{$index} = serialize_hash($results);
    untie %db;

    return $index;
}

sub delLocalDBEntry($)
{
    my ($index) = @_;
1081
    my %db;
1082 1083
    my $filename = createDBfilename();
    tie( %db, "DB_File", $filename) or 
Dan Gebhardt's avatar
Dan Gebhardt committed
1084 1085 1086 1087
        eval {
            warn time()." cannot open db file";
            return -1;
        };    
1088 1089

    if( defined $db{$index} ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1090
        delete $db{$index};
1091
    }
1092

1093
    untie %db;
1094 1095 1096 1097
}

#############################################################################
sub sendResults($$){
1098 1099 1100
    my ($results, $index) = @_;

    my %result = ( expid    => $expid,
Dan Gebhardt's avatar
Dan Gebhardt committed
1101 1102 1103 1104 1105
                   linksrc  => $results->{sourceaddr},
                   linkdest => $results->{destaddr},
                   testtype => $results->{testtype},
                   result   => $results->{result},
                   tstamp   => $results->{tstamp},
1106 1107 1108 1109 1110 1111 1112
                   index    => $index
                   ,"toolname" => $results->{toolname}
                   ,"toolwrapperpath" => $results->{toolwrapperpath}
                   ,"tooltype" => $results->{tooltype}
                   ,"req_params" => $results->{req_params}
                   ,"opt_params" => $results->{opt_params}
        );
1113 1114
    my $result_serial = serialize_hash( \%result );
    $socket_snd->send($result_serial);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
}


#############################################################################

sub createtmpfilename($$)
{
    return "$workingdir$_[0]-$_[1].tmp";
}

1125
sub createDBfilename()
1126
{
1127 1128
#    return "$workingdir$_[0].bgmonbdb";
    return "$workingdir"."cachedResults.bdb";
1129 1130 1131 1132 1133
}


#############################################################################

1134 1135 1136
#
# return a warning (bw, for now) if a test has not been run for a while
# after when it is scheduled to be
1137 1138 1139
sub detectHang($)
{
    my ($nodeid) = @_;
1140
    my $TIMEOUT_NUM_PER = 10;
1141

1142
    if( defined $testevents{$nodeid}{bw} &&
Dan Gebhardt's avatar
Dan Gebhardt committed
1143 1144 1145 1146
        $testevents{$nodeid}{bw}{flag_scheduled} == 1 &&
        time_all() > $testevents{$nodeid}{bw}{timeOfNextRun} +
        $testevents{$nodeid}{bw}{testper} * $TIMEOUT_NUM_PER
        && $testevents{$nodeid}{bw}{testper} >0 )
1147
    {
Dan Gebhardt's avatar
Dan Gebhardt committed
1148
        return "bw";
1149 1150 1151 1152
    }
    
    return "nohang";
}
1153 1154


1155
sub isMsgValid(\%)
1156
{
1157
    my ($hashref) = @_;
1158 1159
    my %msgHash = %$hashref;
    if( !defined($msgHash{cmdtype}) ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1160 1161
        warn "bad message format\n";
        return 0;  #bad message
1162
    }
1163
    if( $msgHash{expid} ne $expid ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1164
        return 0;  #not addressed to this experiment
1165
    }
1166
    return 1;
1167
}
1168

1169
#
1170 1171 1172
#  Adjust latency measurement frequency if a path is detected to have
#   gone down. Also adjusts the timeout frequency of fping to allow for
#   a more frequent probing.
1173 1174 1175 1176 1177 1178
#
=pod
state transitions

CurrentState   Input                 NextState
----------------------------------------------
1179
normal         gotErr&PrevSucc       lossCheck
1180
               else                  normal
1181 1182 1183 1184
lossCheck      pingSucc
               |  lossCheck=lossy    normal
               lossCheck=down        highFreq
               else                  lossCheck
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
highFreq       <60sec&ERR            highFreq
               >60sec&ERR            medFreq
               SUCCESS               outageEnd
medFreq        <10min&ERR            medFreq
               >10min&ERR            lowFreq
               SUCCESS               outageEnd
lowFreq        ERR                   lowFreq
               SUCCESS               outageEnd
outageEnd      <120sec&SUCCESS       outageEnd
               >120sec&SUCCESS       normal
               ERR                   highFreq
=cut

1198 1199 1200 1201 1202 1203 1204 1205 1206
#
#   CALLED FROM A OUTAGETEST RESULT
sub updateOutageState_lossCheck($)
{
    my ($destaddr) = @_;
    my $latref = \%{ $testevents{$destaddr}{latency} };
    my $outref = \%{ $testevents{$destaddr}{outage} };
    my $curstate = $latref->{outagestate};
    if( $curstate eq "lossCheck" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
        if( $outref->{results_parsed} eq "lossy" ){
            # STATE TRANSITION -> normal
            # ** but start outageEnd monitoring for a time
            # Delete outageManID entry in cmdqueue
            #  set period to 0
            addCmd( $latref, Cmd->new($outManID,
                                      $outTestFreq{outageEnd},
                                      $outTestDur{outageEnd}) );
            $latref->{outagestate} = "normal";
            $latref->{outStateTime} = 0;
            $latref->{fpingTimeout} = $fpingTimeoutDef;
            print "NEW STATE: normal\n";
        }elsif( $outref->{results_parsed} eq "down" ){
            # STATE TRANSITION -> highFreq
            addCmd( $latref, Cmd->new($outManID,
                                      $outTestFreq{high},
                                      0) );  #forever, since internally managed
            $latref->{outagestate} = "highFreq";
            $latref->{outStateTime} = time();
            $latref->{fpingTimeout} = $outTestFreq{high}*1000/2;
            print "NEW STATE: highFreq\n";
        }
1229 1230 1231 1232 1233
    }
}

#
#   MUST BE CALLED WITH A $TESTEV POINTING TO A LATENCY TESTTYPE HASH
1234
sub updateOutageState($)
1235
{
1236 1237
    my ($destaddr) = @_;
    my $testev = \%{ $testevents{$destaddr}{latency} };
1238
    my $curstate = $testev->{outagestate};
1239
    my $nextstate = $curstate;
1240 1241 1242

#    if( $testev->{results_parsed} > 0 ){
    if( hacky_evalLatencyResult($testev->{results_parsed}) > 0 ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1243 1244
        #valid result, so note the time that this was seen
        $testev->{lastValidLatTime} = time();
1245 1246
    }

1247
    # SWITCH ON "outagestate"
1248
    if( $curstate eq "normal" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        if( isWorkingPathDown($testev) > 0 ){
            # STATE TRANSITION -> lossCheck
            $nextstate = "lossCheck";
            # run outage check
            $testevents{$destaddr}{outage}{testper} = 0;
            $testevents{$destaddr}{outage}{timeOfNextRun} = time_all()-1;
            $testevents{$destaddr}{outage}{flag_scheduled} = 1;
            $testevents{$destaddr}{outage}{pid} = 0;
            $testevents{$destaddr}{outage}{flag_finished} =0;
            $testevents{$destaddr}{outage}{timedout} = 0;
        }
1260
    }elsif( $curstate eq "lossCheck" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1261 1262 1263 1264 1265 1266 1267 1268 1269
        if( isWorkingPathDown($testev) < 0 ){
            # STATE TRANSITION -> normal
            # Delete outageManID entry in cmdqueue
            #  set period to 0
            addCmd( $testev, Cmd->new($outManID,0,0) );
            $nextstate = "normal";
            $testev->{outStateTime} = 0;
            $testev->{fpingTimeout} = $fpingTimeoutDef;
        }
1270
    }elsif( $curstate eq "highFreq" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
        if( isWorkingPathDown($testev) > 0 &&
            time() - $testev->{outStateTime} > $outTestDur{high} )
        {
            # STATE TRANSITION -> medFreq
            addCmd( $testev, Cmd->new($outManID,
                                      $outTestFreq{med},
                                      0) );  #forever, since internally managed
            $nextstate = "medFreq";
            $testev->{outStateTime} = time();
            $testev->{fpingTimeout} = $outTestFreq{med}*1000/2;
        }elsif( isWorkingPathDown($testev) < 0 ){
            # STATE TRANSITION -> outageEnd
            $nextstate = outSetState_outageEnd($testev);
        }
1285
    }elsif( $curstate eq "medFreq" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        if( isWorkingPathDown($testev) > 0 &&
            time() - $testev->{outStateTime} > $outTestDur{med} )
        {
            # STATE TRANSITION -> lowFreq
            addCmd( $testev, Cmd->new($outManID,
                                      $outTestFreq{low},
                                      0) );  #forever, since internally managed
            $nextstate = "lowFreq";
            $testev->{outStateTime} = time();
            $testev->{fpingTimeout} = $fpingTimeoutDef;
        }elsif( isWorkingPathDown($testev) < 0 ){
            # STATE TRANSITION -> outageEnd
            $nextstate = outSetState_outageEnd($testev);
        }
1300
    }elsif( $curstate eq "lowFreq" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1301 1302 1303 1304
        if( isWorkingPathDown($testev) < 0 ){
            # STATE TRANSITION -> outageEnd
            $nextstate = outSetState_outageEnd($testev);
        }
1305
    }elsif( $curstate eq "outageEnd" ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        if( isWorkingPathDown($testev) < 0 &&
            time() - $testev->{outStateTime} > $outTestDur{outageEnd} )
        {
            # STATE TRANSITION -> normal
            # Delete outageManID entry in cmdqueue
            #  set period to 0
            addCmd( $testev, Cmd->new($outManID,0,0) );
            $nextstate = "normal";
            $testev->{outStateTime} = 0;
            $testev->{fpingTimeout} = $fpingTimeoutDef;
        }elsif( isWorkingPathDown($testev) > 0 ){
            # STATE TRANSITION -> highFreq
            $nextstate = "highFreq";
            $testev->{outStateTime} = time();
            $testev->{fpingTimeout} = $outTestFreq{high}*1000/2;
        }
1322
    }
1323

1324
    # save new state
1325
    if( $curstate ne $nextstate ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1326
        print "NEW STATE: $nextstate\n";
1327
    }
1328
    $testev->{outagestate} = $nextstate;
1329
}
1330

1331 1332 1333 1334
sub outSetState_outageEnd($)
{
    my ($testev) = @_;
    addCmd( $testev, Cmd->new($outManID,
Dan Gebhardt's avatar
Dan Gebhardt committed
1335 1336
                              $outTestFreq{outageEnd},
                              0) );  #forever, since internally managed
1337 1338 1339 1340 1341
#    $testev->{outagestate} = "outageEnd";
    $testev->{outStateTime} = time();
    $testev->{fpingTimeout} = $outTestFreq{outageEnd}*1000/2;
    return "outageEnd";
}
1342

1343 1344 1345 1346
sub isWorkingPathDown($)
{
    my ($testev) = @_;
    my $secSinceUp = time() - $testev->{lastValidLatTime};
1347 1348
#    if( $testev->{results_parsed} < 0 && 
    if( hacky_evalLatencyResult($testev->{results_parsed}) < 0 && 
Dan Gebhardt's avatar
Dan Gebhardt committed
1349
        $secSinceUp < $outDet_maxPastSuc*60*60 )
1350
    {
Dan Gebhardt's avatar
Dan Gebhardt committed
1351 1352
        #path is down and was up recently
        return $secSinceUp;  #return seconds since last being up
1353
    }else{
Dan Gebhardt's avatar
Dan Gebhardt committed
1354
        return -1;
1355
    }
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
}

#
# update testevents with latest from queue.
#   input: ref to testev
#
# Called from places which change the cmdqueue:
#   receive an EDIT/INIT/STOPALL, test expired, outage detected/measured
#
sub updateTestEvent($)
{
    my ($testev) = @_;
    my $curPer = $testev->{testper};
    my $head = $testev->{cmdq}->head();

    if( !defined $head ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1372 1373 1374 1375
        #if no tests in queue, stop testev.
        print "NO HEAD for ".$testev->{testper}."\n";
        $testev->{flag_scheduled} = 0;
        $testev->{testper} = 0;
1376 1377
    }
    #compare currently running test info with head of queue
1378
    elsif( !defined $curPer ||
Dan Gebhardt's avatar
Dan Gebhardt committed
1379 1380 1381
           $curPer == 0 ||
#          $head->period() < $curPer )
           $head->period() != $curPer )
1382
    {
Dan Gebhardt's avatar
Dan Gebhardt committed
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
        #replace running info with that from head:
        #  testper, limitTime, flag_scheduled, timeOfNextRun, managerID
        print "replacing period $curPer with ".$head->period()."\n";
        $testev->{testper} = $head->period();
        if( $head->duration() == 0 ){
            $testev->{limitTime} = 0;
        }else{
            $testev->{limitTime} = time_all() + $head->timeleft();
        }
        $testev->{flag_scheduled} = 0;
        $testev->{timeOfNextRun} = 0;
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

	# See if we should change the continuous status
	print "testper=", $testev->{testper},
	      ", limit=", $testev->{limitTime}, "\n";
	if (!$nocontinuous &&
	    $testev->{limitTime} > 0 && $testev->{testper} < $CONT_THRESHOLD) {
	    $testev->{continuous} = 1;
	} else {
	    undef $testev->{continuous};
	}

Dan Gebhardt's avatar
Dan Gebhardt committed
1405 1406
        $testev->{managerID} = $head->managerid();
        print $testev->{cmdq}->getQueueInfo();
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    }
}

#
# add a command to the queue of a testev
#
sub addCmd($$)
{
    my ($testev, $cmd) = @_;
    $testev->{cmdq}->add($cmd);
    #update scheduled tests in case something changed
    updateTestEvent( $testev );
}

1421
sub initTestEv($$$$$$$)
1422
{
1423 1424
    my ($dest, $type, $toolname, $toolwrapperpath, $tooltype,
        $req_params, $opt_params) = @_;
1425 1426

    if( !defined $testevents{$dest}{$type} ){
Dan Gebhardt's avatar
Dan Gebhardt committed
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
        $testevents{$dest}{$type} = {
                                     cmdq => Cmdqueue->new(),
                                     flag_scheduled => 0,
                                     flag_finished  => 0,
                                     testper        => 0,
                                     timeOfNextRun  => 0,
                                     limitTime      => 0,
                                     pid            => 0,
                                     timedout       => 0,
                                     outagestate    => "normal",
                                     lastValidLatTime => 0,
                                     fpingTimeout   => $fpingTimeoutDef
                                     };
1440
    }
1441 1442 1443 1444 1445
    $testevents{$dest}{$type}{toolname} = $toolname;
    $testevents{$dest}{$type}{toolwrapperpath} = $toolwrapperpath;
    $testevents{$dest}{$type}{tooltype} = $tooltype;
    $testevents{$dest}{$type}{req_params} = $req_params;
    $testevents{$dest}{$type}{opt_params} = $opt_params;
1446
}
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471

sub getstats()
{
    my %h;

    my ($utime,$stime,$cutime,$cstime);
    if (open(FD, "</proc/self/stat")) {
	($utime,$stime,$cutime,$cstime)	= (split(/\s+/, <FD>))[13..16];
	close(FD);
    }
    $h{utime} = $utime;
    $h{stime} = $stime;
    $h{cutime} = $cutime;
    $h{cstime} = $cstime;
    return \%h;
}

sub diffstats($$)
{
    my ($rs,$re) = @_;

    my %before = %{$rs};
    my %after = %{$re};
    my %diff;
    foreach my $key (keys(%before)) {
1472
        $diff{$key} = $after{$key} - $before{$key};
1473 1474 1475 1476 1477 1478 1479 1480 1481
    }
    return \%diff;
}

sub printstats($$)
{
    my ($hdr,$stats) = @_;

    print("$hdr: utime=", $stats->{utime},
1482 1483 1484 1485
          ", stime=", $stats->{stime},
          ", cutime=", $stats->{cutime},
          ", cstime=", $stats->{cstime}, "\n")
        if( $debug > 0 );
1486
}