cnetwatch.in 15.4 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
#!/usr/bin/perl -w
#
# Copyright (c) 2017 University of Utah and the Flux Group.
# 
# {{{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
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
# TODO:
#  - Use sitevars for the thresholds and intervals.
#
#    cnetwatch/check_interval interval at which to perform checks,
#        should be at least 5 seconds, zero means don't run
#    cnetwatch/pps_threshold  packet rate at which to alarm,
#        zero means don't check
#    cnetwatch/bps_threshold  bit rate at which to alarm,
#        zero means don't check
#    cnetwatch/rate_period    time period over which to calculate rates,
#        if less than interval, set to interval
#    cnetwatch/mail_interval  interval at which to send email reports of problems,
#        zero means don't send email
#    cnetwatch/mail_max       maximum number of emails to send,
#        zero means no limit
#
#    Maybe node_type/node attributes as well for thresholds since some node
#    types or nodes may have fatter cnets than others.
#
#  - 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
#
61
62
63
use English;
use Getopt::Std;
use Sys::Syslog;
64
use IO::Handle;
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
155
156
157
158
159
160
161
162
163
164
165
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

#
# Arbitrary thresholds: 50Kp/s or 500Mb/s for at least 5 minutes.
#
my $MAX_PPS =     50000;
my $MAX_BPS = 500000000;
my $MIN_SEC =       300;

sub usage()
{
    print STDERR "Usage: cnetwatch [-ahd] [-l logfile] [-I interval] [node ...]\n";
    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";
    print STDERR "   -d         Run in debug (foreground) mode\n";
    print STDERR "   -l logfile Also log periodic counts for all nodes\n";
    print STDERR "   -I	num     Report every <num> seconds\n";
    print STDERR "   -M         Send email about incidents in addition to logging,\n";
}

my $optlist = "adhl:I:M";
my $doall = 0;
my $debug = 0;
my $interval = 60;
my $reportlog = "";
my $sendmail = 0;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOG	= "@TBLOGFACIL@";
my $LOGFILE     = "$TB/log/cnetwatch.log";

#
# E-mail config
#

# XXX should be $TBOPS
my $MAILTO	= "mike\@flux.utah.edu";
# Do not send mail more often than this (0 == any time)
my $MAILIV	= (10 * 60);
# Do not send more than this many total messages (0 == no limit)
my $MAILMAX	= 1000;

# XXX testing
if (0) {
    $MIN_SEC = 60;
    $MAILIV = 60;
    $MAILMAX = 10;
}

# 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";
my @nodes       = ();
my %switches	= ();
my %pcs		= ();
my %rates	= ();
my $rateivs	= 1;

my $maillast = 0;
my $mailsent = 0;
my @mailbody = ();

#
# Check args early so we get the right DB.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{'h'})) {
    usage();
    exit(0);
}
if (defined($options{'d'})) {
    $debug++;
}
if (defined($options{"a"})) {
    $doall = 1;
}
if (defined($options{"l"})) {
    $reportlog = $options{"l"};
}
if (defined($options{'I'})) {
    if ($options{'I'} =~ /^(\d+)$/) {
	$interval = $1;
	if ($interval && $interval < 5) {
	    print STDERR "Interval must be zero or at least 5 seconds.\n";
	    usage();
	    exit(1);
	}
    } else {
	print STDERR "Interval must be a number.\n";
	usage();
    }
}
if (defined($options{"M"})) {
    $sendmail = 1;
}
@nodes = @ARGV;

# Set this to turn off tblog in libraries.
$ENV{'TBLOG_OFF'} = "yep";

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use libdb;
use libtestbed;

194
195
196
197
198
199
200
201
202
203
#
# Check user id?
#
if ($UID == 0) {
    fatal("Do not run as root or portstats will fail!");
}
if (!TBAdmin()) {
    fatal("Must run as admin or portstats will fail!");
}

204
205
206
207
208
209
210
211
212
213
214
215
216
217
# Go to ground.
if (!$debug) {
    if (TBBackGround($LOGFILE)) {
	exit(0);
    }
}

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

# and traffic report log
if ($reportlog) {
    if ($reportlog eq "-") {
	*RL = STDOUT;
218
219
220
    } elsif (open(RL, ">>$reportlog")) {
	RL->autoflush(1);
    } else {
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
	print STDERR "Could not open report log '$reportlog'\n";
	exit(1);
    }
}

if ($interval >= $MIN_SEC) {
    $rateivs = 1;
} else {
    $rateivs = int($MIN_SEC / $interval + 0.5);
}

getnodeinfo(0);
my %before = ();
if (!gather(\%before)) {
    die("Could not get initial portstats\n");
}

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'})) {
265
	$dref->{'start'} = time() - $interval;
266
267
	$dref->{'tstamp'} = $interval;
    } else {
268
	$dref->{'start'} = $bref->{'tstamp'};
269
270
271
272
273
274
	$dref->{'tstamp'} = $aref->{'tstamp'} - $bref->{'tstamp'};
    }
    print STDERR "interval: ".
	"before=", $bref->{'tstamp'}, ", ".
	"after=", $aref->{'tstamp'}, ", ".
	"diff=", $dref->{'tstamp'}, "\n"
275
	if ($debug && 0);
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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

    foreach my $node (keys %pcs) {
	if (!exists($aref->{$node}{'counts'})) {
	    logit("*** $node: got no portstats, not an admin?");
	    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) {
	    if ($acs->[$i] < $bcs->[$i]) {
		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.
#
sub reportevents($)
{
    my ($ref) = @_;

    my $warned = 0;
337
    foreach my $node (sort keys %pcs) {
338
339
340
341
	# XXX don't know the interval, cannot compute
	if ($ref->{$node}{'first'}) {
	    next;
	}
342
343
344
	if (!exists($ref->{$node}{'counts'})) {
	    next;
	}
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
	my $secs = $ref->{'tstamp'};
	my @counts = @{$ref->{$node}{'counts'}};
	my $pps = $counts[1] + $counts[2] + $counts[3] +
	    $counts[5] + $counts[6] + $counts[7];
	my $bps = $counts[0] + $counts[4];

	$secs += $rates{$node}{'elapsed'};
	$pps += $rates{$node}{'pkts'};
	$bps += $rates{$node}{'bytes'};

	#
	# 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");
	    }
	    $pps = int($pps / $sec);
	    $bps = int($bps * 8 / $sec);
	    if ($pps > $MAX_PPS || $bps > $MAX_BPS) {
		logit("$node: WARNING: pkts/sec=$pps, bits/sec=$bps over $sec seconds");
		if ($sendmail) {
		    if (@mailbody == 0) {
			my $mbps = int($MAX_BPS / 1000000);
			push(@mailbody,
374
			     "Thresholds: $MAX_PPS pkts/sec, $mbps Mbits/sec\n");
375
			push(@mailbody,
376
377
			     sprintf("%10s %20s %8s %8s %s",
				     "Node", "Expt", "Pkts/sec", "Mb/sec", "When"));
378
		    }
379
380
		    my $stamp = POSIX::strftime("20%y-%m-%d %H:%M:%S",
						localtime($ref->{'start'}));
381
		    push(@mailbody,
382
383
384
			 sprintf("%10s %20s %8d %8d %s for %d sec",
				 $node, $pcs{$node}{'exp'}, $pps,
				 int($bps/1000000), $stamp, $secs));
385
386
387
388
389
390
391
392
393
394
395
396
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
		}
	    }
	    $rates{$node}{'pkts'} = 0; 
	    $rates{$node}{'bytes'} = 0;
	    $rates{$node}{'iv'} = 0;
	    $rates{$node}{'elapsed'} = 0;
	} else {
	    $rates{$node}{'pkts'} = $pps;
	    $rates{$node}{'bytes'} = $bps;
	    $rates{$node}{'iv'} = $iv;
	    $rates{$node}{'elapsed'} = $secs;
	}
    }
    if ($sendmail && (time() - $maillast) > $MAILIV && @mailbody > 0) {
	if ($MAILMAX > 0 && ++$mailsent > $MAILMAX) {
	    $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",
		 join("\n", @mailbody),
		 $TBOPS);
	$maillast = time();
	@mailbody = ();
    }
}

sub report($)
{
    my ($ref) = @_;

    my $send = 1;
    my $recv = 1;

    my @list = ();
    foreach my $node (keys %pcs) {
	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'} =
	    [ $oct, $upkts, $mpkts, $upkts + $mpkts + $bpkts];
	$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";
    printf RL "%12s %25s %12s %12s %12s %14s\n",
        "Node", "Experiment", "Tot Pkts", "Unicast", "Multicast", "Tot Bytes";
    foreach my $node (@list) {
	my $name = $pcs{$node}{'name'};
	my $exp = $pcs{$node}{'exp'};
	my $tot = $ref->{$node}{'totals'};

	printf RL "%12s %25s %12d %12d %12d %14d\n",
	    $name, $exp, $tot->[3], $tot->[1], $tot->[2], $tot->[0];
    }
}

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 =
	DBQueryWarn("select r.pid,r.eid,node_id1,eventstate,card1,port1,node_id2".
		    " from wires as w,nodes as n".
		    " left join reserved as r on n.node_id=r.node_id".
		    " where w.node_id1=n.node_id".
		    "  $sclause".
		    "  and w.type='Control'".
		    "  and n.role='testnode' $nclause".
		    " order by node_id2,card2,port2");
    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'};
	my $pceth = $row{'card1'};
	my $pcport = $row{'port1'};
	my $exp;
	if (defined($row{'pid'})) {
	    $exp = $row{'pid'} . "/" . $row{'eid'};
	} else {
	    $exp = "<NONE>";
	}

	#
	# XXX ugh, portstats only takes node:card and not node:card.port,
	# so if the port is anything other than 1 (e.g., an allocable switch)
	# we cannot look it up.
	#
	next
	    if ($pcport != 1);

	my $cnet = "$pc:$pceth";

	push(@{$switches{$switch}}, $cnet);
	$newpcs{$cnet}{'exp'} = $exp;
	$newpcs{$cnet}{'state'} = $row{'eventstate'};
	$newpcs{$cnet}{'name'} = $pc;

	if (!exists($pcs{$cnet})) {
	    $rates{$cnet}{'pkts'} = 0;
	    $rates{$cnet}{'bytes'} = 0;
	    $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}});
	if (!open(PS, "$portstats -H -r -l -c -p $slist 2>&1 |")) {
	    print STDERR "*** $switch: portstats failed, ignored\n";
	    next;
	}
	while (<PS>) {
	    chomp;
	    # XXX ignore warnings from snmpit
	    next if ($_ =~ /^WARNING:/);
	    next if ($_ !~ /^[-\w]+:\d/);
	    my ($node, @counts) = split ',';
	    if (@counts != 8) {
		print STDERR "*** $node: invalid portstats!?\n"; 
		next;
	    }

	    #
	    # XXX portstats returns nodes in the format: pcXXX:N.N,
	    # even though it won't accept that format on the command line!
	    #
	    if ($node =~ /^(.*:\d+)\.\d$/) {
		$node = $1;
	    }

	    if (!exists($pcs{$node})) {
		print STDERR "*** $node: no stats returned!?\n"; 
		next;
	    }
	    $resref->{$node}{'counts'} = \@counts;
	}
	close(PS);
    }
    $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);
    }
}