portal_monitor.in 21.6 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
use Data::Dumper;
use File::Basename;
use Compress::Zlib;
use MIME::Base64;
use Date::Parse;

#
# Contact all clusters and get status.
#
sub usage()
{
    print "Usage: portal_monitor [-d] [-s] [-n]\n";
    exit(1);
}
my $optlist   = "dns";
my $debug     = 0;
my $impotent  = 0;
my $oneshot   = 0;
51 52
my %status    = ();
my $lastdaily = 0;
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

# Debugging
my $usemydevtree  = 0;
sub devurl($)
{
    my ($cmurl) = @_;

    if ($usemydevtree) {
	$cmurl =~ s/protogeni/protogeni\/stoller/;
#	$cmurl =~ s/12369/12396/;
    }
    return $cmurl;
}

#
# Configure variables
#
my $TB		     = "@prefix@";
my $TBOPS            = "@TBOPSEMAIL@";
my $TBLOGS           = "@TBLOGSEMAIL@";
my $MAINSITE         = @TBMAINSITE@;
my $LOGFILE          = "$TB/log/portal_monitor.log";
75 76 77 78
my $DIG              = "/usr/local/bin/dig";
my $PING             = "/sbin/ping";
my $FPING            = "/usr/local/sbin/fping";
my $CURL             = "/usr/local/bin/curl";
79
my $SLEEP_INTERVAL   = 60;
80
my $AGGDOWN_THRESHOLD= 180;
81
my $DAILY_INTERVAL   = 24 * 3600;
82 83 84 85 86 87 88 89 90 91 92 93 94 95
my $SLACK	     = "https://hooks.slack.com/services";
my $SLACKURL         = "$SLACK/T0D79QFGC/B9V105D99/kTE1wzm0binEIsBsQFuCkqfK";

#
# Mothership extra node definitions, which will go into the database
# at some point.
#
my %mothershipnodes = (
    "emulab.net"          => ["dbox1", "dbox2"],
    "apt.emulab.net"      => ["dbox2"],
    "utah.cloudlab.us"    => ["dbox1"],
    "wisc.cloudlab.us"    => ["dbox"],
    "clemson.cloudlab.us" => ["dbox"],
);
96 97 98 99 100 101 102

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

# Protos
sub fatal($);
103
sub doPing($$);
104 105 106 107 108 109 110 111 112
	  
#
# Turn off line buffering on output
#
$| = 1; 

if ($UID != 0) {
    fatal("Must be root to run this script\n");
}
113 114 115 116
# Silently exit if not the Mothership, this currently is specific to Utah.
if (!$MAINSITE) {
    exit(0);
}
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

#
# Check args early so we get the right DB.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
if (defined($options{"s"})) {
    $oneshot = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use emdb;
use libtestbed;
use emutil;
use libEmulab;
use APT_Aggregate;
use APT_Geni;
use Genixmlrpc;
use GeniResponse;
use GeniCredential;
use GeniXML;
147
use GeniHRN;
148 149
use POSIX qw(strftime ceil);

150
if (! ($oneshot || $impotent)) {
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    if (CheckDaemonRunning("portal_monitor")) {
	fatal("Not starting another portal_monitor daemon!");
    }
    # Go to ground.
    if (! $debug) {
	if (TBBackGround($LOGFILE)) {
	    exit(0);
	}
    }
    if (MarkDaemonRunning("portal_monitor")) {
	fatal("Could not mark daemon as running!");
    }
}
my $context = APT_Geni::GeniContext();
fatal("Could not load our XMLRPC context")
    if (!defined($context));

168 169 170 171 172 173
my $credential = APT_Geni::GenAuthCredential($context->certificate());
if (!defined($credential)) {
    print STDERR "Could not generate credential!\n";
    return -1;
}

174 175 176
#
# We want this to be a quick test, not a long timeout.
#
177
Genixmlrpc->SetTimeout(15);
178

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
#
# Setup a signal handler for newsyslog.
#
sub handler()
{
    my $SAVEEUID = $EUID;
    
    $EUID = 0;
    ReOpenLog($LOGFILE);
    $EUID = $SAVEEUID;
}
$SIG{HUP} = \&handler
    if (! ($debug || $oneshot));

#
# Request an advertisement.
#
sub CheckAggregates()
{
198 199 200
    my %aggregates = ();
    my %pingchecks = ();
    
201 202
    my $query_result =
	DBQueryWarn("select urn from apt_aggregates ".
203
		    "where nomonitor=0 and disabled=0");
204 205 206 207 208 209 210 211 212
    return 0
	if (!$query_result->numrows);

    while (my ($urn) = $query_result->fetchrow_array()) {
	my $aggregate = APT_Aggregate->Lookup($urn);
	if (!defined($aggregate)) {
	    print STDERR "Could not lookup aggregate: $urn\n";
	    next;
	}
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	# Convert URN into a boss/ops hostnames for the ping/DNS tests.
	#
	my $hrn  = GeniHRN->new($urn);
	my $boss = "boss." . $hrn->domain();
	
	$aggregates{$urn} = {
	    "aggregate" => $aggregate,
	    "alive"     => 1,
	    "domain"    => $hrn->domain(),
	    "boss"      => "boss." . $hrn->domain(),
	    "status"    => undef,
	    "dns"       => undef,
	    "nodes"     => {},
	};
	#
	# Hack alert; we have a gross test in for powderwireless until
	# DB is updated; the ops nodes do not have public IPs.
	#
	if ($hrn->domain() !~ /powderwireless\.net$/) {
	    $aggregates{$urn}->{"nodes"}->{"ops." . $hrn->domain()} = undef;
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
	#
	# Another hacky check for other nodes that need to be checked.
	#
	if ($MAINSITE) {
	    if (exists($mothershipnodes{$hrn->domain()})) {
		foreach my $hostname (@{$mothershipnodes{$hrn->domain()}}) {
		    my $host = "${hostname}." . $hrn->domain();
		    
		    $aggregates{$urn}->{"nodes"}->{$host} = undef;
		}
	    }
	}

	# Add new history entries since last loop. 
	if (!exists($status{$urn})) {
	    $status{$urn} = {
		"alive"     => "up",
		"stamp"     => time(),
		"status"    => {"status" => "up", "stamp" => time()},
		"dns"       => {"status" => "up", "stamp" => time()},
		"nodes"     => {},
	    };
	    foreach my $node (keys(%{$aggregates{$urn}->{"nodes"}})) {
		$status{$urn}->{"nodes"}->{$node} = {
		    "status" => "up", "stamp" => time()
		};
	    }
262
	}
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    }
    # Cull out status entries that are gone from the DB since last loop.
    foreach my $urn (keys(%status)) {
	delete $status{$urn} if (!exists($aggregates{$urn}));
    }

    #
    # Generate a list to check with fping. First check all the boss nodes.
    # If we cannot ping boss, then we can skip everything else, marking
    # the aggregate down.
    #
    foreach my $urn (keys(%aggregates)) {
	my $aggregate = $aggregates{$urn}->{"aggregate"};
	my $boss      = $aggregates{$urn}->{"boss"};

278
	#
279 280
	# Do not do this on the local host, no point and it will often
	# fail if we are in a VM.
281
	#
282 283
	next
	    if ($aggregate->IsLocalCluster());
284

285 286 287 288
	$pingchecks{$boss} = $urn;
    }
    my %pingresults = ();
    doPing(\%pingchecks, \%pingresults);
289

290 291 292 293 294 295 296
    #
    # Go through the results, mark any that failed as down.
    #
    foreach my $boss (keys(%pingchecks)) {
	my $urn       = $pingchecks{$boss};
	my $alive     = $pingresults{$boss};
	my $aggregate = $aggregates{$urn}->{"aggregate"};
297

298 299
	next
	    if ($alive);
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
	print STDERR "Ping $boss failed\n";
	$aggregates{$urn}->{"alive"} = 0;
    }

    #
    # Check the nodes, skipping any aggregates that failed boss fping, with
    # boss unreachable the status of anything else at the aggregate is
    # suspect and likely to generate needless noise.
    #
    %pingchecks = ();
    
    foreach my $urn (keys(%aggregates)) {
	my $aggregate = $aggregates{$urn}->{"aggregate"};
	my $nodelist  = $aggregates{$urn}->{"nodes"};
	foreach my $hostname (keys(%{$nodelist})) {
	    $pingchecks{$hostname} = $urn;
	}
    }
    %pingresults = ();
    doPing(\%pingchecks, \%pingresults);

    #
    # Mark down nodes, process below. 
    #
    foreach my $hostname (keys(%pingchecks)) {
	my $urn       = $pingchecks{$hostname};
	my $alive     = $pingresults{$hostname};

	if ($alive) {
	    $aggregates{$urn}->{"nodes"}->{$hostname} = "up";
331 332
	    next;
	}
333 334 335 336 337 338 339 340 341 342 343 344 345
	print STDERR "Ping $hostname failed\n";
	$aggregates{$urn}->{"nodes"}->{$hostname} = "down";
    }

    #
    # DNS checks on boss nodes. If just named is dead the test below will
    # still likely work cause of secondaries answering, but we want to know
    # if named dies and report it separately.
    #
    foreach my $urn (keys(%aggregates)) {
	my $aggregate = $aggregates{$urn}->{"aggregate"};
	my $boss      = $aggregates{$urn}->{"boss"};

346
	#
347
	# Do not do this if boss ping failed.
348
	#
349 350 351 352 353 354 355 356 357 358
	next
	    if (!$aggregates{$urn}->{"alive"});

	if ($debug) {
	    print "Doing DNS test on $boss\n";
	}
	system("$DIG $boss \@${boss} +norecurse +short +noanswer +time=3");
	if ($?) {
	    print STDERR "DNS $boss failed\n";
	    $aggregates{$urn}->{"dns"} = "down";
359 360
	}
	else {
361
	    $aggregates{$urn}->{"dns"} = "up";
362 363
	}
    }
364 365 366 367 368 369
    # Not yet sure what to do if this fails.
    if (GetVersion(\%aggregates)) {
	next;
    }
    # Process the results and send email.
    ProcessResults(\%aggregates);
370 371
}

372
#
373 374
# Process the results, updating ongoing status info for next time,
# and sending email.
375
#
376
sub ProcessResults($)
377
{
378 379 380 381 382 383 384 385 386 387
    my ($aggregates) = @_;
    my %downbosses  = ();
    my %upbosses    = ();
    my %downaggs    = ();
    my %upaggs      = ();
    my %downnodes   = ();
    my %upnodes     = ();
    my %downdns     = ();
    my %updns       = ();
    my $dailymail   = 0;
388 389 390

    #
    # We send a summary email once every 24 hours. Maybe do this at a
391
    # set time of day?
392
    #
393
    if (time() - $lastdaily >= $DAILY_INTERVAL) {
394 395 396 397
	$dailymail = 1;
	$lastdaily = time();
    }

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
    #
    # First check for ping failures to boss nodes; these aggregates
    # are clearly down, but wait till a second loop to mark them and
    # send email. 
    #
    foreach my $urn (keys(%{$aggregates})) {
	my $ref       = $aggregates->{$urn};
	my $aggregate = $ref->{"aggregate"};
	my $nickname  = $aggregate->nickname();

	if ($aggregate->IsLocalCluster()) {
	    # We skipped the ping test on the local host.
	}
	elsif (!$ref->{'alive'}) {
	    if ($status{$urn}->{'alive'} eq "down") {
		# Down last time too, mark as dead, send email.
		if ($impotent) {
		    print STDERR "Would mark $nickname as down\n";
		}
		else {
		    if ($aggregate->status() ne "down") {
			$aggregate->status("down");
			$aggregate->StatusEvent("down");
		    }
		    $aggregate->last_error("Ping failed");
		}
		$downbosses{$urn} = $status{$urn}->{'stamp'};

		# Mark that we have sent email
		$status{$urn}->{'alive'} = "dead";
	    }
	    elsif ($dailymail && $status{$urn}->{'alive'} eq "dead") {
		$downbosses{$urn} = $status{$urn}->{'stamp'};
	    }
	    elsif ($status{$urn}->{'alive'} eq "up") {
		# Remember for next time, we need to send email.
		$status{$urn}->{'alive'} = "down";
		$status{$urn}->{'stamp'} = time();
	    }
	}
	elsif ($status{$urn}->{'alive'} ne "up") {
	    #
	    # Dead last time, up this time. Mark as up and send email.
	    #
	    if ($status{$urn}->{'alive'} eq "dead") {
		if ($impotent) {
		    print STDERR "Would mark $nickname as up\n";
		}
		else {
		    $aggregate->last_error("");
		    if ($aggregate->status() ne "up") {
			$aggregate->status("up");
			$aggregate->StatusEvent("up");
		    }
		}
		$upbosses{$urn} = $status{$urn}->{'stamp'};
	    }
	    $status{$urn}->{'alive'} = "up";
	    $status{$urn}->{'stamp'} = undef;
457 458
	}
	#
459
	# Check the nodes associated this aggregate.
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
	foreach my $host (keys(%{$ref->{'nodes'}})) {
	    my $thisstatus = $ref->{'nodes'}->{$host};
	    my $laststatus = $status{$urn}->{'nodes'}->{$host}->{'status'};

	    if ($thisstatus eq "down") {
		if ($laststatus eq "up") {
		    # Mark as down, record time.
		    $status{$urn}->{'nodes'}->{$host}->{'status'} = "down";
		    $status{$urn}->{'nodes'}->{$host}->{'stamp'}  = time();
		}
		elsif ($dailymail && $laststatus eq "dead") {
		    # Mark for email
		    $downnodes{$urn}->{$host} =
			$status{$urn}->{'nodes'}->{$host}->{'stamp'};
		}
		elsif ($laststatus ne "dead") {
		    # Mark for email
		    $downnodes{$urn}->{$host} =
			$status{$urn}->{'nodes'}->{$host}->{'stamp'};
		    # Mark as dead so we know we sent email.
		    $status{$urn}->{'nodes'}->{$host}->{'status'} = "dead";
		}
	    }
	    elsif ($laststatus ne "up") {
		# Node is back, mark for email and clear previous status.
		if ($laststatus eq "dead") {
		    $upnodes{$urn}->{$host} =
			$status{$urn}->{'nodes'}->{$host}->{'stamp'};
		}
		$status{$urn}->{'nodes'}->{$host}->{'status'} = "up";
		$status{$urn}->{'nodes'}->{$host}->{'stamp'}  = undef;
	    }
	}
	#
	# Check DNS. These rate seperate email. But if boss did not
	# ping, then we skip since we do not know anything about DNS.
	#
	if ($ref->{'alive'}) {
	    if ($ref->{'dns'} eq "down") {
		if ($status{$urn}->{'dns'}->{'status'} eq "down") {
		    # Dead last time too, mark as dead, send email.
		    $downdns{$urn} = $status{$urn}->{'dns'}->{'stamp'};

		    # Mark that we have sent email
		    $status{$urn}->{'dns'}->{'status'} = "dead";
		}
		elsif ($dailymail &&
		       $status{$urn}->{'dns'}->{'status'} eq "dead") {
		    # Mark for email
		    $downdns{$urn} = $status{$urn}->{'dns'}->{'stamp'};
		}
		elsif ($status{$urn}->{'dns'}->{'status'} eq "up") {
		    # Remember for next time, we need to send email.
		    $status{$urn}->{'dns'}->{'status'} = "down";
		    $status{$urn}->{'dns'}->{'stamp'}  = time();
		}
	    }
	    elsif ($status{$urn}->{'dns'}->{'status'} ne "up") {
		# DNS is back, mark for email and clear previous status.
		if ($status{$urn}->{'dns'}->{'status'} eq "dead") {
		    $updns{$urn} = $status{$urn}->{'dns'}->{'stamp'};
		}
		$status{$urn}->{'dns'}->{'status'} = "up";
		$status{$urn}->{'dns'}->{'stamp'}  = undef;
	    }
	}
	#
	# Check Aggregate status. These also rate seperate email. But if
	# boss did not ping, then we skip since we do not know anything
	# about the aggregate.
	#
	if ($ref->{'alive'}) {
	    if ($ref->{'status'} eq "down") {
		if ($status{$urn}->{'status'}->{'status'} eq "down") {
		    # Dead last time too, mark as dead, send email.
		    $downaggs{$urn} = $status{$urn}->{'status'}->{'stamp'};

		    # Mark that we have sent email
		    $status{$urn}->{'status'}->{'status'} = "dead";
		}
		elsif ($dailymail &&
		       $status{$urn}->{'status'}->{'status'} eq "dead") {
		    # Mark for email.
		    $downaggs{$urn} = $status{$urn}->{'status'}->{'stamp'};
		}
		elsif ($status{$urn}->{'status'}->{'status'} eq "up") {
		    # Remember for next time, we need to send email.
		    $status{$urn}->{'status'}->{'status'} = "down";
		    $status{$urn}->{'status'}->{'stamp'}  = time();
		}
	    }
	    elsif ($status{$urn}->{'status'}->{'status'} ne "up") {
		# Aggregate is back, mark for email and clear previous status.
		if ($status{$urn}->{'status'}->{'status'} eq "dead") {
		    $upaggs{$urn} = $status{$urn}->{'status'}->{'stamp'};
		}
		$status{$urn}->{'status'}->{'status'} = "up";
		$status{$urn}->{'status'}->{'stamp'}  = undef;
	    }
	}
    }
    
    #
    # And send email.
    #
    if (keys(%downbosses)) {
	my $subject = "Portal Boss Nodes are " .
	    ($dailymail ? "still " : "") . "unreachable";
	my $body = "";

	foreach my $urn (keys(%downbosses)) {
	    my $when = $downbosses{$urn};
	    my $boss = $aggregates->{$urn}->{'boss'};
574
	    
575 576 577 578 579 580 581 582 583
	    $body .= "${boss}: is unreachable since ".
		TBDateStringLocal($when) . "\n";
	}
	NotifySlack($body);
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
    if (keys(%upbosses)) {
	my $subject = "Portal Boss Nodes are back online";
	my $body = "";
584

585 586 587
	foreach my $urn (keys(%upbosses)) {
	    my $when = $upbosses{$urn};
	    my $boss = $aggregates->{$urn}->{'boss'};
588

589
	    $body .= "${boss}: is now online " . "\n";
590
	}
591 592 593 594 595 596 597 598 599 600 601 602 603 604
	NotifySlack($body);
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
    if (keys(%downaggs)) {
	my $subject = "Portal Aggregates are " .
	    ($dailymail ? "still " : "") . "offlne";
	my $body = "";

	foreach my $urn (keys(%downaggs)) {
	    my $when = $downaggs{$urn};
	    my $boss = $aggregates->{$urn}->{'boss'};
	    
	    $body .= "${boss}: CM is offline since ".
		TBDateStringLocal($when) . "\n";
605
	}
606 607
	NotifySlack($body);
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
608
    }
609 610 611 612 613 614 615
    if (keys(%upaggs)) {
	my $subject = "Portal Aggregates are back online";
	my $body = "";

	foreach my $urn (keys(%upaggs)) {
	    my $when = $upaggs{$urn};
	    my $boss = $aggregates->{$urn}->{'boss'};
616

617
	    $body .= "${boss}: CM is now online " . "\n";
618
	}
619
	NotifySlack($body);
620 621
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
622 623
    if (keys(%downdns)) {
	my $subject = "Portal DNS servers are " .
624
	    ($dailymail ? "still " : "") . "offline";
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
	my $body = "";

	foreach my $urn (keys(%downdns)) {
	    my $when = $downdns{$urn};
	    my $boss = $aggregates->{$urn}->{'boss'};
	    
	    $body .= "${boss}: DNS is offline since ".
		TBDateStringLocal($when) . "\n";
	}
	NotifySlack($body);
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
    if (keys(%updns)) {
	my $subject = "Portal DNS servers are back online";
	my $body = "";
640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	foreach my $urn (keys(%updns)) {
	    my $when = $updns{$urn};
	    my $boss = $aggregates->{$urn}->{'boss'};

	    $body .= "${boss}: DNS is now online " . "\n";
	}
	NotifySlack($body);
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
    if (keys(%downnodes)) {
	my $subject = "Portal Nodes are " .
	    ($dailymail ? "still " : "") . "unreachable";
	my $body = "";

	foreach my $urn (keys(%downnodes)) {
	    foreach my $hostname (keys(%{$downnodes{$urn}})) {
		my $when = $downnodes{$urn}->{$hostname};
658
	    
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
		$body .= "${hostname}: is unreachable since ".
		    TBDateStringLocal($when) . "\n";
	    }
	    $body .= "\n";
	}
	NotifySlack($body);
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
    if (keys(%upnodes)) {
	my $subject = "Portal Nodes are back online";
	my $body = "";

	foreach my $urn (keys(%upnodes)) {
	    foreach my $hostname (keys(%{$upnodes{$urn}})) {
		my $when = $upnodes{$urn}->{$hostname};
	    
		$body .= "${hostname}: is now online\n";
	    }
	    $body .= "\n";
678
	}
679
	NotifySlack($body);
680 681
	SENDMAIL($TBOPS, $subject, $body, $TBOPS);
    }
682 683
}

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 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
#
# Do a Getversion on all aggregates in parallel.
#
sub GetVersion($)
{
    my ($aggregates) = @_;
    my @return_codes = ();
    my @agglist      = ();

    # Only check if we could ping boss.
    foreach my $urn (keys(%{$aggregates})) {
	push(@agglist, $aggregates->{$urn}->{"aggregate"})
	    if ($aggregates->{$urn}->{"alive"});
    }
    if ($debug) {
	print "GetVersion: @agglist\n";
    }
    my $coderef = sub {
	my ($aggregate) = @_;
	my $error;

	if ($debug) {
	    print "Checking status: $aggregate\n";
	}
	# Ping test using GetVersion. We want the actual error message
	# back so use this directly instead of $aggregate->CheckStatus()
	# Also want to change the default timeout to be more robust on 
	# very busy aggregates. 
	my $retval = APT_Geni::PingAggregate($aggregate, \$error, undef, 20);
	if ($retval) {
	    $aggregate->last_error($error);
	    return -1;
	}
	return 0;
    };
    if (ParRun({"maxwaittime" => 600,
		"maxchildren" => 10}, \@return_codes, $coderef, @agglist)) {
	print STDERR "ParRun failed";
	return -1;
    }
    #
    # Process return codes and update status since work done in fork.
    #
    foreach my $aggregate (@agglist) {
	my $code = shift(@return_codes);
	my $urn  = $aggregate->urn();
	$aggregate->Refresh();

	if ($code) {
	    my $nickname = $aggregate->nickname();
	    my $error    = $aggregate->last_error();
	    print "Aggregate $nickname is down: $error\n";
	    # Mark for processing.
	    $aggregates->{$urn}->{"status"} = "down";
	}
	else {
	    $aggregates->{$urn}->{"status"} = "up";
	}
    }
    return 0;
}

#
# Run fping on a set of nodes and store results for caller
#
sub doPing($$)
{
    my ($hosts, $results) = @_;
    my @hostnames = keys(%{$hosts});

    if (! -f "$FPING") {
        fatal("$FPING is not installed\n");
    }
    if (! -x "$FPING") {
        fatal("$FPING is not executable\n");
    }
    if ($debug) {
	print "Running fping on @hostnames\n";
    }
    open(FPING, "$FPING -B 1.1 -r 10 -i 250 -p 250 -t 250 @hostnames|") ||
	fatal("Could not fork fping: $!\n");

    while (<FPING>) {
	chomp;
	if ($_ =~ /^([^\ ]+) is alive/) {
	    $results->{$1} = 1;
	}
	elsif ($_ =~ /^([^\ ]+) is/) {
	    $results->{$1} = 0;
	}
    }
    close(FPING);
}
    
778
while (1) {
779
    if (NoLogins()) {
780 781 782 783 784 785
	sleep(5);
	next;
    }
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";

786 787 788 789 790 791 792 793 794 795 796 797 798
    #
    # At the MotherShip, skip this round if our uplink is down since
    # that will generate a blizzard of down email, and we already get
    # enough email. Test this with a check if we can resolve at
    # Google's DNS. 
    #
    if ($MAINSITE) {
	system("$DIG google.com \@8.8.8.8 +short +noanswer");
	if ($?) {
	    print "Cannot contact 8.8.8.8, skipping this round\n";
	    goto loop;
	}
    }
799
    CheckAggregates();
800 801 802
    
    print "Done at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";
803 804 805

    exit(0)
	if ($oneshot);
806 807

  loop:
808 809 810 811
    sleep($SLEEP_INTERVAL);
}
exit(0);

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
#
# Notify Slack.
#
sub NotifySlack($)
{
    my ($message) = @_;

    return
	if (0 && $debug);

    if (open(PIPE, "| $CURL -s -X POST -H ".
	     "'Content-type: application/json' --data \@- $SLACKURL")){

	$message = join("\\n", split(/\n/, $message));
	print PIPE '{"text" : "' . $message . '"}';
	if (!close(PIPE)) {
	    print STDERR "$CURL exited with status $?\n";
	}
    }
    else {
	print STDERR "Could not start $CURL\n";
    }
}

836 837 838 839
sub fatal($)
{
    my ($msg) = @_;

840
    if (! ($oneshot || $debug || $impotent)) {
841 842 843 844 845 846 847 848 849
	#
	# Send a message to the testbed list. 
	#
	SENDMAIL($TBOPS,
		 "portal_monitor died",
		 $msg,
		 $TBOPS);
    }
    MarkDaemonStopped("portal_monitor")
850
	if (! ($oneshot || $impotent));
851 852 853 854

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