cnetwatch.in 22.5 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2017-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 
# {{{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/>.
# 
# }}}
#

#
# Periodically check traffic rates of nodes on the control net.
# Whine if "excessive".
#
Mike Hibler's avatar
Mike Hibler committed
29
# TODO:
30 31
#  - Maybe add node_type/node attributes as well as sitevars for thresholds
#    since some node types or nodes may have fatter cnets than others.
Mike Hibler's avatar
Mike Hibler committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45
#
#  - if the email period (e.g., 10 minutes) encompasses multiple report
#    periods (e.g., 5 minutes), try to combine contiguous over-limit reports
#    into a single email line. For example:
#
#       Node       Pkts/sec         Mb/sec When
#    dbox3:0          55389            324 2017-05-09 10:33:40 for 325 sec
#    dbox3:0          55640            324 2017-05-09 10:39:05 for 323 sec
#
#    could become:
#
#       Node       Pkts/sec         Mb/sec When
#    dbox3:0          55389            324 2017-05-09 10:33:40 for 648 sec
#
46 47 48
use English;
use Getopt::Std;
use Sys::Syslog;
49
use IO::Handle;
50 51

#
52 53
# Arbitrary thresholds: 50Kp/s or 500Mb/s for the given alert interval.
# These can be overridden by sitevariables below.
54 55 56 57 58 59
#
my $MAX_PPS =     50000;
my $MAX_BPS = 500000000;

sub usage()
{
60
    print STDERR "Usage: cnetwatch [-ahdM1] [-I interval] [-A interval] [-l logfile] [node ...]\n";
61 62 63 64
    print STDERR "\nMonitor control net usage and report on abnormally high ";
    print STDERR "traffic volumes.\n";
    print STDERR "   -h         This message\n";
    print STDERR "   -a         Monitor all nodes\n";
65 66 67 68
    print STDERR "   -I	seconds Interval at which to gather stats\n";
    print STDERR "   -A	seconds Interval over which rates are calculated and alerts sent\n";
    print STDERR "              (must be a multiple of the gather interval)\n";
    print STDERR "   -M         Send email about alerts in addition to logging via syslog\n";
69
    print STDERR "   -d         Run in debug (foreground) mode\n";
70 71 72
    print STDERR "   -l logfile Log file to record a summary of packet/byte\n";
    print STDERR "              counts for all nodes at every gather interval\n";
    print STDERR "   -1         Run data gathering once and print summary report to STDOUT (for debugging gathering)\n";
73 74
}

75
my $optlist = "adhl:I:A:M1";
76 77 78
my $doall = 0;
my $debug = 0;
my $interval = 60;
79
my $alertinterval = (5 * 60);
80 81
my $reportlog = "";
my $sendmail = 0;
82
my $runonce = 0;
83 84 85 86 87 88 89

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOG	= "@TBLOGFACIL@";
90 91
my $TBBASE      = "@TBBASE@";
my $PGENISUPPORT= @PROTOGENI_SUPPORT@;
92 93
my $LOGFILE     = "$TB/log/cnetwatch.log";

94 95 96 97
# For Geni slices: do this early so that we talk to the right DB.
use vars qw($GENI_DBNAME);
$GENI_DBNAME = "geni-cm";

98 99 100 101
#
# E-mail config
#

102
my $MAILTO	= $TBOPS;
103
# Do not send mail more often than this (0 == any time)
104
my $MAIL_IV	= (10 * 60);
105
# Do not send more than this many total messages (0 == no limit)
106
my $MAIL_MAX	= 1000;
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

# Protos
sub getnodeinfo($);
sub gather($);
sub diffem($$$);
sub reportevents($);
sub report($);
sub logit($);
sub fatal($);

#
# Turn off line buffering on output
#
$| = 1; 

my $portstats	= "$TB/bin/portstats";
127 128
my $wap         = "$TB/sbin/withadminprivs";
my $sudo        = "/usr/local/bin/sudo";
129 130 131 132 133 134 135 136 137
my @nodes       = ();
my %switches	= ();
my %pcs		= ();
my %rates	= ();
my $rateivs	= 1;

my $maillast = 0;
my $mailsent = 0;
my @mailbody = ();
138
my @maildetails = ();
139

140 141 142 143 144 145 146 147 148
# Set this to turn off tblog in libraries.
$ENV{'TBLOG_OFF'} = "yep";

# "Inline" the withadminprivs command.
# Note that caller must be admin in DB too for TBAdmin() check to pass.
$ENV{'WITH_TB_ADMIN_PRIVS'} = 1;

# Load the Testbed support stuff.
use lib "@prefix@/lib";
149
use EmulabConstants;
150 151
use libdb;
use libtestbed;
152 153 154 155 156
use Experiment;
if ($PGENISUPPORT) {
    require GeniSlice;
    require GeniHRN;
}
157 158 159 160

#
# Read sitevars to establish defaults:
#
161 162 163
# cnetwatch/enable
#   Zero means don't run cnetwatch (exit immediately).
#   
164 165 166 167
# cnetwatch/reportlog
#   If set, a file in which to log the port counts for all nodes (-l).
#   Unset means do not log.
#
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
# cnetwatch/check_interval
#   Interval at which to collect info.
#   Zero means don't run cnetwatch (exit immediately).
#   
# cnetwatch/alert_interval
#   Interval over which to calculate packet/bit rates and to log alerts.
#   Should be an integer multiple of the check_interval.
#
# cnetwatch/pps_threshold
#   Packet rate (packets/sec) in excess of which to log an alert.
#   Zero means don't generate packet rate alerts.
#
# cnetwatch/bps_threshold
#   Data rate (bits/sec) in excess of which to log an alert.
#   Zero means don't generate data rate alerts.
#
# cnetwatch/mail_interval
#   Interval at which to send email for all alerts logged during the interval.
#   Zero means don't ever send email.
187
#
188 189 190 191 192
# cnetwatch/mail_max
#   Maximum number of alert emails to send; after this alerts are only logged.
#   Zero means no limit to the emails.
#
my $tmp;
193 194 195 196 197 198 199
my $svar = "cnetwatch/enable";
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp == 0) {
	print STDERR "WARNING: cnetwatch disabled by sitevar\n";
	exit(0);
    }
}
200 201 202 203 204 205 206 207
$svar = "cnetwatch/reportlog";
if (TBGetSiteVar($svar, \$tmp) && $tmp ne "") {
    if ($tmp =~ /^([-\w\.\/\+]*[-\w\.\+])$/) {
	$reportlog = $1;
    } else {
	print STDERR "WARNING: invalid path: '$tmp', ignored.\n";	
    }
}
208
$svar = "cnetwatch/check_interval";
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp == 0 || $tmp >= 10) {
	$interval = $tmp;
    } else {
	print STDERR "WARNING: invalid value for $svar sitevar, ignored.\n";
    }
}
$svar = "cnetwatch/alert_interval";
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp >= 0) {
	$alertinterval = $tmp;
    } else {
	print STDERR "WARNING: invalid value for $svar sitevar, ignored.\n";
    }
}
$svar = "cnetwatch/pps_threshold";
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp >= 0) {
	$MAX_PPS = $tmp;
    } else {
	print STDERR "WARNING: invalid value for $svar sitevar, ignored.\n";
    }

}
$svar = "cnetwatch/bps_threshold";
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp >= 0) {
	$MAX_BPS = $tmp;
    } else {
	print STDERR "WARNING: invalid value for $svar sitevar, ignored.\n";
    }

}
$svar = "cnetwatch/mail_interval";
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp >= 0) {
	$MAIL_IV = $tmp;
246 247 248
	if ($MAIL_IV > 0) {
	    $sendmail = 1;
	}
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    } else {
	print STDERR "WARNING: invalid value for $svar sitevar, ignored.\n";
    }

}
$svar = "cnetwatch/mail_max";
if (TBGetSiteVar($svar, \$tmp)) {
    if ($tmp >= 0) {
	$MAIL_MAX = $tmp;
    } else {
	print STDERR "WARNING: invalid value for $svar sitevar, ignored.\n";
    }

}

264 265 266 267 268 269 270 271 272
# XXX testing
if (0) {
    $interval = 30;
    $alertinterval = (2 * $interval);
    $MAIL_IV = 30;
    $MAIL_MAX = 10;
    $MAX_PPS = 10;
}

273 274
#
# Process command line options. Some will override sitevars.
275 276 277 278 279 280 281 282 283 284
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{'h'})) {
    usage();
    exit(0);
}
if (defined($options{'d'})) {
285
    $debug = 1;
286 287 288 289 290 291 292 293 294 295
}
if (defined($options{"a"})) {
    $doall = 1;
}
if (defined($options{"l"})) {
    $reportlog = $options{"l"};
}
if (defined($options{'I'})) {
    if ($options{'I'} =~ /^(\d+)$/) {
	$interval = $1;
296 297
	if ($interval && $interval < 10) {
	    print STDERR "Interval must be zero or at least 10 seconds.\n";
298 299 300 301 302 303 304 305
	    usage();
	    exit(1);
	}
    } else {
	print STDERR "Interval must be a number.\n";
	usage();
    }
}
306 307 308 309 310 311 312 313
if (defined($options{'A'})) {
    if ($options{'A'} =~ /^(\d+)$/) {
	$alertinterval = $1;
    } else {
	print STDERR "Alert interval must be a number.\n";
	usage();
    }
}
314 315 316
if (defined($options{"M"})) {
    $sendmail = 1;
}
317 318
if (defined($options{"1"})) {
    $runonce = 1;
319
    $interval = 1;
320 321 322
    $debug = 2;
    $reportlog = "-";
}
323 324
@nodes = @ARGV;

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
#
# Sanity checks.
#
if ($interval == 0) {
    print STDERR "WARNING: cnetwatch disabled by command line or sitevar\n";
    exit(0);
}
if ($alertinterval < $interval) {
    $alertinterval = $interval;
}
if ($MAIL_IV == 0) {
    if ($sendmail) {
	print STDERR "WARNING: -M option overrides sitevar mail disable\n";
	$MAIL_IV = $alertinterval;
    }
} elsif ($MAIL_IV < $alertinterval) {
    $MAIL_IV = $alertinterval;
}
343 344

# Go to ground.
345 346 347 348 349
if (! ($debug || $runonce)) {
    if (CheckDaemonRunning("cnetwatch")) {
	fatal("Not starting another cnetwatch, use debug/runonce mode!");
    }
    # Go to ground.
350 351 352
    if (TBBackGround($LOGFILE)) {
	exit(0);
    }
353 354 355
    if (MarkDaemonRunning("cnetwatch")) {
	fatal("Could not mark daemon as running!");
    }
356 357 358 359 360 361 362 363 364
}

# Set up syslog
openlog("cnetwatch", "pid", $TBLOG);

# and traffic report log
if ($reportlog) {
    if ($reportlog eq "-") {
	*RL = STDOUT;
365 366 367
    } elsif (open(RL, ">>$reportlog")) {
	RL->autoflush(1);
    } else {
368
	fatal("Could not open report log '$reportlog'");
369 370 371
    }
}

372
if ($interval >= $alertinterval) {
373 374
    $rateivs = 1;
} else {
375
    $rateivs = int($alertinterval / $interval + 0.5);
376 377
}

378 379 380 381 382 383 384 385 386 387
logit("cnetwatch starting:");
logit("  check=${interval}s, alert=${alertinterval}s, ".
      "pps=$MAX_PPS, bps=$MAX_BPS");
if ($sendmail) {
    logit("  mail=${MAIL_IV}s, mailmax=$MAIL_MAX messages");
}
if ($reportlog) {
    logit("  reportlog=$reportlog");
}

388 389 390 391 392
getnodeinfo(0);
my %before = ();
if (!gather(\%before)) {
    die("Could not get initial portstats\n");
}
393 394 395 396
if ($runonce) {
    report(\%before);
    exit(0);
}
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

while (1) {
    logit("Waiting $interval seconds.");
    sleep($interval);

    getnodeinfo(1);
    my %after = ();
    if (!gather(\%after)) {
	next;
    }

    my %delta = ();
    diffem(\%before, \%after, \%delta);

    reportevents(\%delta);
    if ($reportlog) {
	report(\%delta);
    }

    %before = %after;
}
exit(0);

sub diffem($$$)
{
    my ($bref, $aref, $dref) = @_;

    if (!exists($bref->{'tstamp'}) || !exists($aref->{'tstamp'})) {
425
	$dref->{'start'} = time() - $interval;
426 427
	$dref->{'tstamp'} = $interval;
    } else {
428
	$dref->{'start'} = $bref->{'tstamp'};
429 430 431 432 433 434
	$dref->{'tstamp'} = $aref->{'tstamp'} - $bref->{'tstamp'};
    }
    print STDERR "interval: ".
	"before=", $bref->{'tstamp'}, ", ".
	"after=", $aref->{'tstamp'}, ", ".
	"diff=", $dref->{'tstamp'}, "\n"
435
	if ($debug && 0);
436 437 438

    foreach my $node (keys %pcs) {
	if (!exists($aref->{$node}{'counts'})) {
439
	    logit("*** $node: got no portstats, ignored");
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
	    next;
	}

	if (!exists($bref->{$node})) {
	    $bref->{$node}{'counts'} = [0, 0, 0, 0, 0, 0, 0, 0];
	    $dref->{$node}{'first'} = 1;
	} else {
	    delete $dref->{$node}{'first'};
	}
	if (!exists($aref->{$node})) {
	    my @copy = @{$bref->{$node}{'counts'}};
	    $aref->{$node}{'counts'} = \@copy;
	}

	#
	# Calculate totals, taking into account wrap around of counters...
	# XXX now that we are getting 64-bit counters, should not see wrap.
	#
	my @counts = ();
	my $bcs = $bref->{$node}{'counts'};
	my $acs = $aref->{$node}{'counts'};
	foreach my $i (0..7) {
Mike Hibler's avatar
Mike Hibler committed
462 463 464 465
	    if (!defined($acs->[$i]) || !defined($bcs->[$i])) {
		logit("$node: WARNING: undefined counter value ($i)");
		$counts[$i] = 0;
	    } elsif ($acs->[$i] < $bcs->[$i]) {
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
		print STDERR "$node: counter wrap: ".
		    "b=", $bcs->[$i], ", ".
		    "a=", $acs->[$i], "!\n"
		    if ($debug);
	    } else {
		$counts[$i] = $acs->[$i] - $bcs->[$i];
	    }
	}
	$dref->{$node}{'counts'} = \@counts;
	print STDERR "$node: ".
	    "before=(", join(',', @{$bref->{$node}{'counts'}}), "), ".
	    "after=(", join(',', @{$aref->{$node}{'counts'}}), "), ".
	    "diff=(", join(',', @{$dref->{$node}{'counts'}}), ")\n"
	    if ($debug && 0);
    }
}

sub sortem($$)
{
    my ($a, $b) = @_;

    my $atot = $pcs{$a}{'total'};
    my $btot = $pcs{$b}{'total'};
    return $btot <=> $atot;
}

#
# Check for prolonged high traffic volumes from nodes.
494 495
# Counts: 0==s-bytes, 1==s-uni, 2==s-multi, 3==s-broad
#         4==r-bytes, 5==r-uni, 6==r-multi, 7==r-broad
496 497 498 499 500 501
#
sub reportevents($)
{
    my ($ref) = @_;

    my $warned = 0;
502
    foreach my $node (sort keys %pcs) {
503 504 505 506
	# XXX don't know the interval, cannot compute
	if ($ref->{$node}{'first'}) {
	    next;
	}
507 508 509
	if (!exists($ref->{$node}{'counts'})) {
	    next;
	}
510 511
	my $secs = $ref->{'tstamp'};
	my @counts = @{$ref->{$node}{'counts'}};
512 513 514 515 516

	my $spkts = $counts[1] + $counts[2] + $counts[3];
	my $rpkts = $counts[5] + $counts[6] + $counts[7];
	my $sbytes = $counts[0];
	my $rbytes = $counts[4];
517 518

	$secs += $rates{$node}{'elapsed'};
519 520 521 522 523 524 525
	$spkts += $rates{$node}{'spkts'};
	$rpkts += $rates{$node}{'rpkts'};
	$sbytes += $rates{$node}{'sbytes'};
	$rbytes += $rates{$node}{'rbytes'};

	my $pkts = $spkts + $rpkts;
	my $bytes = $sbytes + $rbytes;
526 527 528 529 530 531 532 533 534 535 536 537

	#
	# XXX right now we do discrete intervals, we could do a sliding 
	# window instead.
	#
	my $iv = $rates{$node}{'iv'} + 1;
	if ($iv >= $rateivs) {
	    my $sec = $secs;
	    if ($debug && $sec != ($rateivs * $interval)) {
		my $ideal = ($rateivs * $interval);
		logit("elapsed: actual=$sec, ideal=$ideal");
	    }
538 539
	    my $pps = int($pkts / $sec);
	    my $bps = int($bytes * 8 / $sec);
540 541
	    if (($MAX_PPS && $pps > $MAX_PPS) ||
		($MAX_BPS && $bps > $MAX_BPS)) {
542 543 544 545 546 547 548 549
		my $spps = int($spkts / $sec);
		my $sbps = int($sbytes * 8 / $sec);
		my $rpps = int($rpkts / $sec);
		my $rbps = int($rbytes * 8 / $sec);

		logit("$node: WARNING: pkts/sec=$pps (send=$spps, recv=$rpps)".
		      ", bits/sec=$bps (send=$sbps, recv=$rbps)".
		      " over $sec seconds");
550
		if ($sendmail) {
551 552 553 554 555
		    my $exp = $pcs{$node}{'exp'};
		    my $expname = $pcs{$node}{'expname'};
		    my $url = $pcs{$node}{'url'};
		    my $portalurl = $pcs{$node}{'portalurl'};
		    
556
		    if (@mailbody == 0) {
557 558 559 560 561 562 563 564
			my $pth = $bth = "no limit on";
			if ($MAX_PPS) {
			    $pth = "$MAX_PPS";
			}
			if ($MAX_BPS) {
			    my $mbps = int($MAX_BPS / 1000000);
			    $bth = "$mbps";
			}
565
			push(@mailbody,
566
			     "Thresholds: $pth pkts/sec, $bth Mbits/sec\n");
567
			push(@mailbody,
568 569
			     sprintf("%20s %30s %8s %8s %s",
				     "Node:port", "Expt", "Pkts/sec", "Mb/sec", "When"));
570
		    }
571 572 573 574 575 576 577
		    if (@maildetails == 0) {
			push(@maildetails,
			     "\nDetails:");
			push(@maildetails,
			     sprintf("%20s %17s %17s %s",
				     "Node:port", "Send/Recv pps", "Send/Recv Mbs", "Duration"));
		    }
578 579
		    my $stamp = POSIX::strftime("20%y-%m-%d %H:%M:%S",
						localtime($ref->{'start'}));
580
		    push(@mailbody,
581
			 sprintf("%20s %30s %8d %8d %s for %d sec",
582
				 $node, $expname, $pps,
583
				 int($bps/1000000), $stamp, $secs));
584 585 586 587 588
		    push(@mailbody, sprintf("%30s %s", "", $url))
			if (defined($url));
		    push(@mailbody, sprintf("%30s %s", "", $portalurl))
			if (defined($portalurl));

589 590 591 592 593
		    push(@maildetails,
			 sprintf("%20s %8d/%-8d %8d/%-8d %d sec",
				 $node, $spps, $rpps,
				 int($sbps/1000000), int($rbps/1000000),
				 $secs));
594 595
		}
	    }
596 597 598 599
	    $rates{$node}{'spkts'} = 0; 
	    $rates{$node}{'rpkts'} = 0; 
	    $rates{$node}{'sbytes'} = 0;
	    $rates{$node}{'rbytes'} = 0;
600 601 602
	    $rates{$node}{'iv'} = 0;
	    $rates{$node}{'elapsed'} = 0;
	} else {
603 604 605 606
	    $rates{$node}{'spkts'} = $spkts;
	    $rates{$node}{'rpkts'} = $rpkts;
	    $rates{$node}{'sbytes'} = $sbytes;
	    $rates{$node}{'rbytes'} = $rbytes;
607 608 609 610
	    $rates{$node}{'iv'} = $iv;
	    $rates{$node}{'elapsed'} = $secs;
	}
    }
611 612
    if ($sendmail && (time() - $maillast) > $MAIL_IV && @mailbody > 0) {
	if ($MAIL_MAX > 0 && ++$mailsent > $MAIL_MAX) {
613 614 615 616 617 618 619 620 621
	    $sendmail = 0;

	    my $msg = "*** WARNING: max mail messages exceeded!";
	    push(@mailbody,
		 "\n$msg Not sending anymore, restart cnetwatch to reenable");
	    logit($msg);
	}
	SENDMAIL($MAILTO,
		 "Excessive traffic on control network",
622
		 join("\n", @mailbody, @maildetails),
623 624 625
		 $TBOPS);
	$maillast = time();
	@mailbody = ();
626
	@maildetails = ();
627 628 629
    }
}

630 631 632 633 634
#
# Make a periodic report.
# Counts: 0==s-bytes, 1==s-uni, 2==s-multi, 3==s-broad
#         4==r-bytes, 5==r-uni, 6==r-multi, 7==r-broad
#
635 636 637 638
sub report($)
{
    my ($ref) = @_;

639
    # XXX allow for differentiation down the road
640 641 642 643 644
    my $send = 1;
    my $recv = 1;

    my @list = ();
    foreach my $node (keys %pcs) {
645 646
	next if (!exists($ref->{$node}{'counts'}));

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
	my @counts = @{$ref->{$node}{'counts'}};

	my $oct = 0;
	my $upkts = 0;
	my $mpkts = 0;
	my $bpkts = 0;
	if ($send) {
	    $oct += $counts[0];
	    $upkts += $counts[1];
	    $mpkts += $counts[2];
	    $bpkts += $counts[3];
	}
	if ($recv) {
	    $oct += $counts[4];
	    $upkts += $counts[5];
	    $mpkts += $counts[6];
	    $bpkts += $counts[7];
	}
	$ref->{$node}{'totals'} =
666
	    [ $oct, $upkts, $mpkts, $upkts + $mpkts + $bpkts ];
667 668 669 670 671 672 673 674
	$pcs{$node}{'total'} = $upkts + $mpkts + $bpkts;
	push(@list, $node);
    }
    @list = sort sortem @list;

    my $now = time();
    my $dstr = POSIX::strftime("%+", localtime());
    print RL "========== $dstr: timestamp is $now\n";
675
    printf RL "%20s %30s %12s %12s %12s %14s\n",
676 677 678
        "Node", "Experiment", "Tot Pkts", "Unicast", "Multicast", "Tot Bytes";
    foreach my $node (@list) {
	my $name = $pcs{$node}{'name'};
679
	my $expname = $pcs{$node}{'expname'};
680 681
	my $tot = $ref->{$node}{'totals'};

682
	printf RL "%20s %30s %12d %12d %12d %14d\n",
683
	    $name, $expname, $tot->[3], $tot->[1], $tot->[2], $tot->[0];
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    }
}

sub getnodeinfo($)
{
    my ($whine) = @_;

    #
    # No nodes specified, get stats for all nodes that are in an experiment.
    #
    my $nclause = "";
    if (@nodes > 0) {
	$nclause = "and n.node_id in ('" . join("','", @nodes) . "')";
    }

    #
    # Find the names of all the control net switches.
    # Note that shared switches will have role==testswitch, so include those.
    #
    my $query_result = DBQueryWarn("select node_id from nodes where".
				   "  role='ctrlswitch' or role='testswitch'");
    if (! $query_result || $query_result->numrows == 0) {
	print STDERR "No control net switches found!?\n";
	exit(0);
    }
    my @cswitches = ();
    while (my ($sw) = $query_result->fetchrow_array()) {
	push(@cswitches, $sw);
    }
    my $sclause = "and node_id2 in ('" . join("','", @cswitches) . "')";

    print STDERR "Switches: ", join(" ", @cswitches), "\n"
	if ($debug && 0);

    $query_result =
719
	DBQueryWarn("select r.pid,r.eid,node_id1,eventstate,iface1,node_id2,attrvalue".
720 721
		    " from wires as w,nodes as n".
		    " left join reserved as r on n.node_id=r.node_id".
722 723
		    " left join node_attributes as a on".
		    "  n.node_id=a.node_id and attrkey='cnetwatch_disable'".
724 725 726 727
		    " where w.node_id1=n.node_id".
		    "  $sclause".
		    "  and w.type='Control'".
		    "  and n.role='testnode' $nclause".
728
		    " order by node_id1");
729 730 731 732 733 734 735 736 737 738 739 740 741
    if (! $query_result || $query_result->numrows == 0) {
	print STDERR "Node(s) not found.\n";
	exit(0);
    }

    print STDERR "Nodes: "
	if ($debug && 0);

    %switches = ();
    my %newpcs = ();
    while (my %row = $query_result->fetchhash()) {
	my $switch = $row{'node_id2'};
	my $pc = $row{'node_id1'};
742
	my $pciface = $row{'iface1'};
743 744 745 746 747 748 749 750
	my $disable = $row{'attrvalue'};

	# XXX if cnetwatch is disabled for the node, just skip it.
	if ($disable) {
	    print STDERR "*** $pc administratively ignored!\n" if ($debug);
	    next;
	}

751
	my ($exp,$expname,$url,$portalurl);
752
	if (defined($row{'pid'})) {
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
	    $exp = Experiment->Lookup($row{'pid'}, $row{'eid'});
	}
	if (defined($exp)) {
	    $expname = $exp->pideid();
	    if ($exp->geniflags) {
		my $slice = GeniSlice->LookupByExperiment($exp);
		if (defined($slice)) {
		    $portalurl = $slice->GetPortalURL();
		}
	    }
	    my $pid = $exp->pid();
	    my $eid = $exp->eid();
	    $url = "$TBBASE/showexp.php3?pid=$pid&eid=$eid";
	}
	else {
	    $expname = "<NONE>";
769
	}
770
	# portstats now accepts node:iface, and spits out in that format (-i).
771
	#
772
	my $cnet = "$pc:$pciface";
773 774 775

	push(@{$switches{$switch}}, $cnet);
	$newpcs{$cnet}{'exp'} = $exp;
776 777 778
	$newpcs{$cnet}{'expname'} = $expname;
	$newpcs{$cnet}{'url'} = $url;
	$newpcs{$cnet}{'portalurl'} = $portalurl;
779 780 781 782
	$newpcs{$cnet}{'state'} = $row{'eventstate'};
	$newpcs{$cnet}{'name'} = $pc;

	if (!exists($pcs{$cnet})) {
783 784 785 786
	    $rates{$cnet}{'spkts'} = 0;
	    $rates{$cnet}{'rpkts'} = 0;
	    $rates{$cnet}{'sbytes'} = 0;
	    $rates{$cnet}{'rbytes'} = 0;
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
	    $rates{$cnet}{'iv'} = 0;
	    $rates{$cnet}{'elapsed'} = 0;
	    if ($whine) {
		logit("$pc: new node!");
	    }
	} else {
	    $pcs{$cnet}{'mark'} = 1;
	}
	
	print "$pc "
	    if ($debug && 0);
    }
    print "\n"
	if ($debug && 0);

    foreach my $node (keys %pcs) {
	if (!exists($pcs{$node}{'mark'})) {
	    delete $rates{$node};
	    if ($whine) {
		my $pc = $pcs{$node}{'name'};
		logit("$pc: node disappeared!");
	    }
	}
    }

    %pcs = %newpcs;
}

#
# Returns a reference to a hash, indexed by node, with the eight counters
# (in octets, in ucast packets, in mcast packets, in bcast packets,
#  out octets, out ucast packets, out mcast packets, out bcast packets)
# for each node
#
# We use the new -H option to return the high capacity counters and hopefully
# avoid any wrap problems.
#
sub gather($)
{
    my ($resref) = @_;

    foreach my $switch (keys %switches) {
	my $slist = join(' ', @{$switches{$switch}});
830
	print STDERR "$switch: invoking '$portstats -i -H -r -l -c -p $slist':\n"
831
	    if ($debug > 1);
832 833
	if (!open(PS, "$sudo -u ". PROTOUSER() . " $wap ".
		  "$portstats -i -H -r -l -c -p $slist 2>&1 |")) {
834
	    print STDERR "*** $switch: portstats failed on open, ignored\n";
835 836
	    next;
	}
837
	my $erroutput = "";
838
	while (<PS>) {
839 840
	    print STDERR "  $_"
		if ($debug > 1);
841
	    chomp;
842 843 844 845 846 847 848 849 850 851 852

	    # XXX ignore warnings from snmpit and other unrecognized lines
	    if ($_ =~ /^WARNING:/) {
		$erroutput .= "  $_\n";
		next;
	    }
	    if ($_ !~ /^[-\w]+:[^,]+,/) {
		$erroutput .= "  $_\n";
		next;
	    }

853 854
	    my ($node, @counts) = split ',';
	    if (@counts != 8) {
855
		$erroutput .= "  $_\n";
856 857 858 859 860
		print STDERR "*** $node: invalid portstats!?\n"; 
		next;
	    }

	    #
861
	    # XXX portstats returns nodes in the format: pcXXX:ethN
862 863 864 865 866 867 868
	    #
	    if (!exists($pcs{$node})) {
		print STDERR "*** $node: no stats returned!?\n"; 
		next;
	    }
	    $resref->{$node}{'counts'} = \@counts;
	}
869
	if (!close(PS)) {
870 871
	    print STDERR "*** $switch: portstats failed on close, output:\n";
	    print STDERR $erroutput;
872
	}
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    }
    $resref->{'tstamp'} = time();

    return 1;
}

sub fatal($)
{
    my ($msg) = @_;

    die("*** $0:\n".
	"    $msg\n");
}

#
# XXX we use syslog for now.
#
sub logit($)
{
    my ($msg) = @_;

    if ($debug) {
	my $stamp = POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime());
	print STDERR "$stamp: $msg\n";
    } else {
	syslog(LOG_INFO, $msg);
    }
}