audit.in 20.6 KB
Newer Older
1
#!/usr/bin/perl -w
2
#
3
# Copyright (c) 2000-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
# 
# {{{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/>.
# 
# }}}
23 24
#
use English;
25
use Getopt::Std;
26
use POSIX qw(strftime);
27 28 29

#
# Audit the DB, looking for things we want to catch. Run once a day from cron.
30 31 32 33 34 35
#
sub usage() {
    print STDOUT "Usage: audit [-d]\n".
	"Use the -d option to see debugging output instead of emailing it.\n";
    exit(-1);
}
36
sub fatal($);
37
my $optlist = "dn";
38
my $debug   = 0;
39
my $impotent= 0;
40 41 42 43 44 45

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
46
my $ISOLATEADMINS = @ISOLATEADMINS@;
47 48
my $TBBASE      = "@TBBASE@";
my $MKCERT      = "$TB/sbin/mkusercert";
49
my $CHECKQUOTA  = "$TB/sbin/checkquota";
50 51
my $SUDO	= "/usr/local/bin/sudo";
my $PROTOUSER   = "elabman";
52
my $MAINSITE    = @TBMAINSITE@;
53 54 55 56 57 58 59 60 61 62 63 64 65 66

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

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

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use libdb;
use libtestbed;
67
use Project;
68
use User;
69

70 71 72 73 74 75 76 77 78 79 80 81 82 83
#
# Parse command arguments. Once we return from getopts, all that should
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV) {
    usage();
}
if (defined($options{"d"})) {
    $debug++;
}
84 85 86
if (defined($options{"n"})) {
    $impotent++;
}
87

88 89 90 91 92 93 94 95
#
# Only real root can call this, unless we are impotent.
#
if (!$impotent && $UID != 0) {
    print STDERR "You must be root to run this script (unless impotent)!\n";
    exit(-1);
}

96 97 98 99 100 101 102 103 104
#
# Form a temp name.
#
my $logname = TBMakeLogname("audit");
my $query_result;

#
# Reopen both stdout and stderr so that we can record all the output for
# later mailing.
105
#
106
if (! $debug && !$impotent) {
107 108 109
    open(STDERR, ">> $logname") or die("opening $logname for STDERR: $!");
    open(STDOUT, ">> $logname") or die("opening $logname for STDOUT: $!");
}
110 111 112 113 114 115

#
# Look for experiments running longer than 1 day, using real nodes.
#
if (! ($query_result = 
       DBQueryWarn("select e.pid,e.eid,e.expt_head_uid,expt_swapped, ".
Leigh Stoller's avatar
Leigh Stoller committed
116 117 118 119
		   "       count(r.node_id) as ncount, ".
		   "       UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(expt_swapped)".
		   "         as swapsec ".
		   "  from experiments as e ".
120 121 122 123 124
		   "left join reserved as r on e.pid=r.pid and e.eid=r.eid ".
		   "left join nodes as n on n.node_id=r.node_id ".
		   "left join node_types as nt on nt.type=n.type ".
		   "where e.state='active' and ".
		   "      e.expt_swapped < date_sub(now(), interval 1 day) and ".
125 126
		   "      nt.isvirtnode=0 and nt.isremotenode=0 and ".
		   # Ignored shared hosts. 
Leigh Stoller's avatar
Leigh Stoller committed
127
		   "      r.sharing_mode is null ".
128 129 130 131 132 133 134 135 136
		   "group by e.pid,e.eid ".
		   "having ncount>0 ".
		   "order by expt_swapped desc"))) {
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "Experiments swapped in longer than 1 day.\n";
Leigh Stoller's avatar
Leigh Stoller committed
137 138 139 140
    printf("%-12s %-8s %-12s %-12s %-22s %s\n",
           "PID", "Hours", "EID", "Creator", "Swapped", "PCs");
    print "------------ -------- ------------ ------------ ".
	  "---------------------- ----\n";
141
    
Leigh Stoller's avatar
Leigh Stoller committed
142 143
    while (my ($pid,$eid,$creator,$swapped,$count,$seconds) =
	   $query_result->fetchrow()) {
144 145
	next
	    if ($count == 0);
Leigh Stoller's avatar
Leigh Stoller committed
146
	my $hours = int($seconds / (60 * 60));
147

Leigh Stoller's avatar
Leigh Stoller committed
148 149
	printf("%-12s %-8s %-12s %-12s %-22s %s\n",
	       $pid, $hours, $eid, $creator, $swapped, $count);
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
#
# Look for experiments stuck in transition
#
if (! ($query_result = 
       DBQueryWarn("select e.pid,e.eid,e.expt_head_uid,expt_locked, ".
		   "       count(r.node_id) as ncount, ".
		   "      UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(expt_locked)".
		   "         as locksec ".
		   "  from experiments as e ".
		   "left join reserved as r on e.pid=r.pid and e.eid=r.eid ".
		   "left join nodes as n on n.node_id=r.node_id ".
		   "left join node_types as nt on nt.type=n.type ".
		   "where e.expt_locked is not NULL and ".
		   "      e.expt_locked < date_sub(now(), interval 1 day) ".
#		   "      and nt.isvirtnode=0 and nt.isremotenode=0 ".
		   "group by e.pid,e.eid ".
		   "order by expt_locked desc"))) {
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
    print "Experiments stuck in transition for more than 1 day\n";
    printf("%-12s %-8s %-12s %-12s %-22s %s\n",
           "PID", "Hours", "EID", "Creator", "Started", "PCs");
    print "------------ -------- ------------ ------------ ".
	  "---------------------- ----\n";
    
    while (my ($pid,$eid,$creator,$locked,$count,$seconds) =
	   $query_result->fetchrow()) {
	next
	    if ($count == 0);
	my $hours = int($seconds / (60 * 60));

	printf("%-12s %-8s %-12s %-12s %-22s %s\n",
	       $pid, $hours, $eid, $creator, $locked, $count);
    }
}

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
#
# Once a week (Sunday) look for anyone that has used the wireless nodes.
#
my $today = POSIX::strftime("%u", localtime());
if ($today == 7) {
    my $query_result =
	DBQueryWarn("select e.exptidx,pid,eid,swapin_last,wirelesslans ".
		    "   from experiment_resources as r ".
		    "left join experiment_stats as e on e.exptidx=r.exptidx ".
		    "where wirelesslans!=0 and swapin_last is not null and ".
		    "UNIX_TIMESTAMP(swapin_last) > ".
		    "  UNIX_TIMESTAMP(now()) - (7 * 60 * 60 * 24) ".
		    "order by e.exptidx");
    fatal("Could not get wireless experiment stats")
	if (!$query_result);

    if ($query_result->numrows) {
	print "\n";
	print "Experiments that have used wireless nodes in the last week\n";
	printf("%-10s %-12s %-14s %-22s %-5s\n",
	       "ExptIDX", "PID", "EID", "Swapin Last", "Wlans");
	print "---------- ------------ -------------- ".
	    "---------------------- -----\n";
    
	while (my ($exptidx,$pid,$eid,$swapin_last,$wlans) =
	       $query_result->fetchrow()) {

	    printf("%-10s %-12s %-14s %-22s %-5s\n",
		   $exptidx, $pid, $eid, $swapin_last, $wlans);
	}
    }
}

227 228 229 230 231 232
#
# Look for free nodes in odd states.
#

if (! ($query_result = 
       DBQueryWarn("select n.node_id from nodes as n ".
233
		   "left join node_types as t on t.type=n.type ".
234 235 236 237 238
		   "left join reserved as r on r.node_id=n.node_id ".
		   "where (n.eventstate!='". TBDB_NODESTATE_ISUP ."' and ".
		   "       n.eventstate!='". TBDB_NODESTATE_PXEWAIT ."' and ".
		   "       n.eventstate!='". TBDB_NODESTATE_ALWAYSUP ."' and ".
		   "       n.eventstate!='". TBDB_NODESTATE_POWEROFF ."') ".
239 240
		   " and r.pid is null and n.role='testnode' and ".
		   "     t.isfednode=0"))) {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
    print "'Free' nodes in an unknown state:\n";
    
    while (my ($node_id) = $query_result->fetchrow()) {
	print "$node_id ";
    }
    print "\n";
}

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
#
# Look for real nodes in hwdown.
#
$DPID = NODEDEAD_PID();
$DEID = NODEDEAD_EID();

if (! ($query_result = 
       DBQueryWarn("select r.node_id,rsrv_time from reserved as r ".
		   "left join nodes as n on n.node_id=r.node_id ".
		   "left join node_types as nt on nt.type=n.type ".
		   "where r.pid='$DPID' and r.eid='$DEID' and ".
		   "      nt.isremotenode=0 ".
		   "order by rsrv_time desc"))) {
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
276
    print "Local nodes stuck in $DPID/$DEID:\n";
277 278 279 280 281 282 283
    
    while (my ($node_id) = $query_result->fetchrow()) {
	print "$node_id ";
    }
    print "\n";
}

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
#
# Look for pre-reserved nodes.
#

if (! ($query_result = 
       DBQueryWarn("select reserved_pid,type,count(*) from nodes ".
		   "where reserved_pid is not null ".
		   "group by reserved_pid,type"))) {
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
    print "Pre-reserved nodes:\n";
    
    printf("%-16s %-16s %-16s\n", "PID", "Type", "Count");
    print "---------------- ---------------- ---------------- \n";
    while (my ($pid,$type,$count) = $query_result->fetchrow()) {
	printf("%-16s %-16s %-16s\n", $pid, $type, $count);
    }
    print "\n";
}

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
#
# Look for stuck checkups.
#

if (! ($query_result = 
       DBQueryWarn("select object,type,state,start from active_checkups ".
		   "where start < DATE_SUB(NOW(), INTERVAL 1 DAY)"))) {
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
    print "Checkups running for more than a day:\n";
    
    printf("%-16s %-16s %-16s %-22s\n", "Object", "Type", "State", "Start");
    print "---------------- ---------------- ---------------- ".
	"--------------------\n";
    while (my ($object,$type,$state,$start) = $query_result->fetchrow()) {
	printf("%-16s %-16s %-16s %-20s\n", $object, $type, $state, $start);
    }
    print "\n";
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
#
# Look for inconsistent resource records.
#
if (! ($query_result =
       DBQueryWarn("select e.idx,r.idx,e.pid,e.eid,".
		   "    e.expt_head_uid,UNIX_TIMESTAMP(r.swapin_time) ".
		   " from experiment_resources as r ".
		   "left join experiments as e on e.idx=r.exptidx ".
		   "  where e.state='swapped' and swapin_time!=0 and ".
		   "        swapout_time=0 and swapmod_time=0 and pnodes>0"))){
    fatal("Error accessing the database.");
}

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
    print "Experiments with inconsistent experiment_resource records:\n";
    printf("%-12s %-12s %-8s %-12s %-22s %s\n",
           "PID", "EID", "IDX", "Creator", "Started", "RIDX");
    print "------------ ------------ -------- ------------ ------------ ".
	  "---------------------- -------\n";
    
    while (my ($exptidx,$idx,$pid,$eid,$creator,$swapin_time) =
	   $query_result->fetchrow()) {

	printf("%-12s %-12s %-8s %-12s %-22s %s\n",
	       $pid, $eid, $exptidx, $creator, $swapin_time, $idx);
    }
}

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
#
# Looks for admin/nonadmin mix users in projects.
#
if ($ISOLATEADMINS) {
    $query_result =
	DBQueryWarn("select pid_idx from projects where approved=1");

    fatal("Error accessing the database.")
	if (! $query_result);

    my @badlist = ();

    while (my ($pid_idx) = $query_result->fetchrow()) {
	my $project = Project->Lookup($pid_idx);
	fatal("Could not look up project $pid_idx in DB")
	    if (!defined($project));
	my @members;

	if ($project->GetProjectGroup()->MemberList(\@members,
				    $Group::MEMBERLIST_FLAGS_ALLUSERS)) {
	    fatal("Could not look up members for project $pid_idx")
	}
	next
	    if (@members == 0);
	
	$adminflag = $members[0]->admin();
	foreach my $user (@members) {
	    if ($user->admin() != $adminflag) {
		#
		# This gets special email.
		#
		if ($debug) {
		    print "Bad mix of admin AND non-admin users in $project\n";
		}
		else  {
		    push(@badlist, $project);
		}
		last;
	    }
	}
    }
    if (@badlist && !$debug) {
	my $msg = "The following projects have an unsafe mix of admin and ".
	    "non-admin users:\n\n@badlist\n";

410 411
	SENDMAIL($TBOPS, "Testbed Admin Users Check", $msg, $TBOPS)
	    if (!$impotent);
412 413 414
    }
}

415 416 417
#
# Age any login entries that have timed out.
#
418 419 420 421 422 423 424 425 426 427 428
if (!$impotent) {
    DBQueryWarn("delete from login ".
		"where (unix_timestamp(now()) - timeout) > (12 * 60 * 60)");
}
else {
    my $query_result =
	DBQueryWarn("delete from login ".
		    "where (unix_timestamp(now()) - timeout) > (12 * 60 * 60)");
    print "".$query_result->numrows()." stale logins would be deleted.\n";
}

429 430 431 432 433 434 435 436 437
my %overquota = ();

sub checkquota($) {
    if (!exists($overquota{$_[0]})) {
	$overquota{$_[0]} = system("$CHECKQUOTA $_[0]");
    }
    return $overquota{$_[0]};
}

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
#
# Generate any missing certs.  There was a time when nonlocal users did
# not automatically receive unencrypted certs, for instance.  Don't tell
# the user about this.
#
$query_result =
    DBQueryWarn("select u.uid,u.uid_idx,cu.created as unencrypted_created,".
		"  ce.created as encrypted_created ".
		" from users as u ".
		"left join user_stats as s on s.uid_idx=u.uid_idx ".
		"left outer join user_sslcerts as cu ".
		"  on (u.uid_idx=cu.uid_idx and cu.encrypted=0) ".
		"left outer join user_sslcerts as ce ".
		"  on (u.uid_idx=ce.uid_idx and ce.encrypted=1) ".
		"where u.status='active' ".
		"  and (cu.created is NULL or ce.created is NULL)");
my $count = 0;
while (my $row = $query_result->fetchrow_hashref()) {
    $count += 1;

    my $uid       = $row->{'uid'};
    my $uid_idx   = $row->{'uid_idx'};
    my $unenc_ctime = $row->{'unencrypted_created'};
    my $enc_ctime = $row->{'encrypted_created'};

    if (!defined($unenc_ctime) || $unenc_ctime eq '') {
	print STDERR
	    "Unencrypted Certificate for $uid missing. Regenerating.\n";
466 467 468 469 470 471

	if (checkquota($uid)) {
	    print STDERR "User $uid over quota, not generating certificate!\n";
	    next;
	}

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
	next
	    if ($impotent);

	system("$SUDO -u $PROTOUSER $MKCERT $uid_idx");
	if ($?) {
	    SENDMAIL($TBOPS, "Error generating missing certificate for $uid",
		     "Error generating missing unencrypted certificate for $uid",
		     $TBOPS)
	}

	# Poor-man's ratelimiting.
	if (!$impotent && $count > 32) {
	    sleep(1);
	}
    }

    if (!defined($enc_ctime) || $enc_ctime eq '') {
	print STDERR
	    "Encrypted Certificate for $uid missing. Regenerating.\n";
491 492 493 494 495 496

	if (checkquota($uid)) {
	    print STDERR "User $uid over quota, not generating certificate!\n";
	    next;
	}

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
	next
	    if ($impotent);

	# Since they don't actually have an encrypted cert (for whatever
	# reason), we have to gen a new passphrase for them (normally
	# tbacct does this)).
	my $pphrase = User::escapeshellarg(substr(TBGenSecretKey(), 0, 12));
	system("$SUDO -u $PROTOUSER $MKCERT -p $pphrase $uid_idx");
	if ($?) {
	    SENDMAIL($TBOPS, "Error generating missing certificate for $uid",
		     "Error generating missing encrypted certificate for $uid",
		     $TBOPS)
	}

	# Poor-man's ratelimiting.  As noted above, there may be large
	# one-time costs here, so be a little nice.
	if (!$impotent && $count > 32) {
	    sleep(1);
	}
    }
}
518

519
#
520
# Warn users of expiring certificates. Regenerate expired or
521
# expiring unencrypted certificates.
522 523 524
#
$query_result =
    DBQueryWarn("select u.uid,u.uid_idx,expires,encrypted,c.idx, ".
525 526 527
		"   UNIX_TIMESTAMP(expires) as stamp, ".
		"   UNIX_TIMESTAMP(s.last_activity) as last_activity ".
		" from user_sslcerts as c ".
528 529
		"left join users as u on u.uid_idx=c.uid_idx ".
		"left join user_stats as s on s.uid_idx=u.uid_idx ".
530
		"where u.status='active' and ".
531
		"     revoked is null and warned is null and ".
532
		"     s.last_activity is not null and ".
533 534
		"     (UNIX_TIMESTAMP(now()) > UNIX_TIMESTAMP(expires) || ".
		"      (UNIX_TIMESTAMP(expires) - ".
535 536
		"       UNIX_TIMESTAMP(now()) < (24 * 3600 * 8))) ".
		"order by expires desc limit 200");
537 538 539 540 541 542 543 544

while (my $row = $query_result->fetchrow_hashref()) {
    my $uid       = $row->{'uid'};
    my $uid_idx   = $row->{'uid_idx'};
    my $expires   = $row->{'expires'};
    my $stamp     = $row->{'stamp'};
    my $serial    = $row->{'idx'};
    my $encrypted = $row->{'encrypted'};
545
    my $lastactive= $row->{'last_activity'};
546 547 548 549 550
    
    if (!$encrypted) {
	print STDERR 
	"Unencrypted Certificate for $uid expires on $expires. Regenerating.\n";

551 552 553 554 555
	if (checkquota($uid)) {
	    print STDERR "User $uid over quota, not generating certificate!\n";
	    next;
	}

556 557 558 559 560 561 562 563 564 565 566
	next
	    if ($impotent);

	system("$SUDO -u $PROTOUSER $MKCERT $uid_idx");
	if ($?) {
	    SENDMAIL($TBOPS, "Error regenerating certificate for $uid",
		     "Error regenerating unencrypted certificate for $uid", 
		     $TBOPS)
	}
	next;
    }
567 568 569 570 571 572

    # Skip encrypted certificates that exprired more then 90 days ago.
    # User likely does not care.
    next
	if (time() - $lastactive > (24 * 3600 * 90));

573
    print STDERR
Leigh Stoller's avatar
Leigh Stoller committed
574
	"Encrypted Certificate for $uid expires on $expires. Regenerating\n";
575

576 577 578 579 580
    if (checkquota($uid)) {
	print STDERR "User $uid over quota, not generating certificate!\n";
	next;
    }

581
    if (!$impotent) {
582 583 584 585 586 587
	system("$SUDO -u $PROTOUSER $MKCERT -P $uid_idx");
	if ($?) {
	    SENDMAIL($TBOPS, "Error regenerating certificate for $uid",
		     "Error regenerating encrypted certificate for $uid", 
		     $TBOPS)
	}
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 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
#
# Looks for unapproved projects and unverified users. Do not do this in Utah,
# it would drive us nuts.
#
if (!$MAINSITE) {
    $query_result =
	DBQueryWarn("select pid_idx from projects where approved=0");

    fatal("Error accessing the database.")
	if (! $query_result);

    my @badlist = ();

    while (my ($pid_idx) = $query_result->fetchrow()) {
	my $project = Project->Lookup($pid_idx);
	fatal("Could not look up project $pid_idx in DB")
	    if (!defined($project));

	#
	# This gets special email.
	#
	if ($debug) {
	    print "Unapproved project: $project\n";
	}
	else  {
	    push(@badlist, $project);
	}
    }
    if (@badlist && !$debug) {
	my $msg = "The following projects are not approved yet:\n\n";
	foreach my $project (@badlist) {
	    my $idx   = $project->pid_idx();
	    my $url   = "$TBBASE/approveproject_form.php3?pid=$idx";

	    $msg .= "$project: $url\n";
	}
	SENDMAIL($TBOPS, "Testbed Unapproved Projects", $msg, $TBOPS)
	    if (!$impotent);
    }

    $query_result =
	DBQueryWarn("select uid_idx from users ".
		    "where status='" . $User::USERSTATUS_NEWUSER . "'");

    fatal("Error accessing the database.")
	if (! $query_result);

    @badlist = ();

    while (my ($uid_idx) = $query_result->fetchrow()) {
	my $user = User->Lookup($uid_idx);
	fatal("Could not look up user $uid_idx in DB")
	    if (!defined($user));

	#
	# This gets special email.
	#
	if ($debug) {
	    print "Unverified user: $user\n";
	}
	else  {
	    push(@badlist, $user);
	}
    }
    if (@badlist && !$debug) {
	my $msg = "The following users are not verified yet:\n\n";
	foreach my $user (@badlist) {
	    my $idx   = $user->uid_idx();
	    my $url   = "$TBBASE/showuser.php3?user=$idx";

	    $msg .= "$user: $url\n";
	}
	SENDMAIL($TBOPS, "Testbed Unverified Users", $msg, $TBOPS)
	    if (!$impotent);
    }
}

668 669 670 671 672 673 674 675 676 677 678 679 680 681 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
#
# Look for (and delete) reserved vlan tags that are no longer in use.
# We seem to be leaking these.
#
$query_result =
    DBQueryFatal("select v.pid,v.eid,v.vname,v.tag,v.lanid,e.state, ".
		 "  h.history_id,h.released ".
		 "  from reserved_vlantags as v ".
		 "left join lans as l on l.lanid=v.lanid ".
		 "left join experiments as e on e.idx=v.exptidx ".
		 "left join vlantag_history as h on ".
		 "     h.exptidx=v.exptidx and h.lanid=v.lanid and h.tag=v.tag ".
		 "where l.lanid is null and ".
		 "      (UNIX_TIMESTAMP(now()) - ".
		 "       UNIX_TIMESTAMP(reserve_time)) > (2 * 3600)");

if ($query_result->numrows) {
    print "\n";
    print "----------------------------------------------------------------\n";
    print "\n";
    print "Stale reserved vlan tags\n";
    print "----------------------------------------------------------------\n";
}

while (my ($pid,$eid,$lan,$tag,$lanid,$estate,$hid,$released) =
       $query_result->fetchrow_array()) {
    next
	if ($estate eq EXPTSTATE_ACTIVATING());

    if ($estate eq EXPTSTATE_ACTIVE()) {
	print "Active Experiment with reserved tag points to deleted lanid\n";
	print "  $pid,$eid,$lan,$tag,$lanid\n";
	next;
    }

    print "Deleting stale vlan tag reservation: $tag ($pid,$eid,$lan)\n";
    if ($hid && !defined($released)) {
	print "--> but leaving stale vlantag_history record $hid\n";
    }
    next
	if ($impotent);

    DBQueryWarn("delete from reserved_vlantags where tag='$tag'")
	or Fatal("Could not delete stale reserved vlan tag $tag");
}

714 715 716
#
# Send email if anything was reported.
#
717
if (!$debug && !$impotent && -s $logname) {
718 719 720 721
    SENDMAIL($TBOPS, "Testbed Audit Results", "Testbed Audit Results",
	     $TBOPS, undef, ($logname));
}

722
unlink("$logname")
723
    if (!$debug && !$impotent && -e $logname);
724 725 726 727 728 729 730
exit 0;

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

    print STDERR "$msg\n";
    SENDMAIL($TBOPS, "Testbed Audit Failed", $msg, undef, undef, ($logname));
731
    unlink("$logname")
732
	if (!$debug && !$impotent && -e $logname);
733 734
    exit(1);
}