lease_daemon.in 19.8 KB
Newer Older
1 2 3
#!/usr/bin/perl -w

#
4
# Copyright (c) 2013-2017 University of Utah and the Flux Group.
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
# 
# {{{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/>.
# 
# }}}
#

use English;
use Getopt::Std;
use POSIX qw(strftime);

#
# The lease monitor.
#
# Periodically examines all lease objects in the system and:
#
# * For 'unapproved' leases, periodically (low frequency) ping testbed-ops
#   and let them know there are leases that need approving.
#
38 39
# * Ditto for 'failed' leases.
#
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
# * For 'locked' leases, ignore them. Maybe periodically tell testbed-ops
#   about them.
#
# * For 'valid' leases, determine which are currently "in use" and update
#   the last_used time. Not sure if there is a lease-type independent way
#   to determine this. For datasets, if it is mapped into some experiment
#   (i.e., exported by a storage server), it is "in use".
#
# * For 'valid' leases, check for those that have not been used for more
#   than the "max idle" time, put them into the 'grace' state, and warn the
#   owner.
#
# * For 'valid' leases, check for those that have passed their expiration
#   date and likewise mark them as 'grace' and warn the owner.
#
# * For 'grace' leases, check for those that are past the grace period
#   and mark them as 'locked' or 'expired' (depending on whether we allow
#   auto-destruction of that type of lease).
#
# * For 'expired' leases, destroy them!
#
Mike Hibler's avatar
Mike Hibler committed
61 62 63 64 65 66 67 68 69 70 71 72 73
# We alter our behavior if we are starting up after having not run for
# "a long time". This is because we want to ensure that a lease gets the
# full benefit of its grace period. We don't want a user to miss their only
# notification about the grace period because it came and went while we were
# not running.
#
# So what exactly is "a long time"? Since our granularity for most actions
# is one day, we choose that. If we have not checked a lease in 24 hours,
# we do the following:
#
# If a lease would have entered the grace period while we were not running
# then 
#
74

Mike Hibler's avatar
Mike Hibler committed
75 76
my $CHECK		= (15 * 60);
my $REPORT_UNAPPROVED	= ( 1 * 24 * 60 * 60);
77
my $REPORT_FAILED	= ( 1 * 24 * 60 * 60);
Mike Hibler's avatar
Mike Hibler committed
78 79
my $REPORT_LOCKED	= (30 * 24 * 60 * 60);
my $REPORT_EXPIRED	= ( 1 * 24 * 60 * 60);
80

Mike Hibler's avatar
Mike Hibler committed
81 82 83
## debugging
#my $CHECK		= (1 * 60);
#my $REPORT_UNAPPROVED	= (2 * 60);
84
#my $REPORT_FAILED	= (2 * 60);
Mike Hibler's avatar
Mike Hibler committed
85 86
#my $REPORT_LOCKED	= (3 * 60);
#my $REPORT_EXPIRED	= (2 * 60);
87 88 89 90 91 92

sub usage()
{
    print STDOUT "Usage: reload_daemon [-d]\n" .
	"    -d     Prevent daemonization\n" .
	"    -n     Just state what would be done without doing it\n" .
93
	"    -D     Disable auto-destruction of expired leases, locking them instead\n" .
Mike Hibler's avatar
Mike Hibler committed
94
	"    -1     Run a single pass and then quit\n" .
95 96 97
	"    -I int Time between checks (in minutes)\n";
    exit(-1);
}
98
my  $optlist = "dnDI:1";
99 100 101 102 103 104

#
# Configure variables
#
my $TB       = "@prefix@";
my $TBOPS    = "@TBOPSEMAIL@";
105
my $OPSNODE  = "@USERNODE@";
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

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

# Testbed Support library
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use Lease;
use User;

# Protos
sub fatal($);
sub logit($);
sub notify($);
sub notifyuser($$);
sub get_vars();
sub lease_list(@);
sub changestate($$);
sub graceify($$);
sub destroy($);
sub lockify($);

my %vars	= ();
my $logfile	= "$TB/log/lease_daemon.log";
my $debug	= 0;
my $impotent	= 0;
133
my $autodestroy = 1;
134
my $checkint	= $CHECK;
Mike Hibler's avatar
Mike Hibler committed
135
my $onceonly	= 0;
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

#
# Turn off line buffering on output (dots ...).
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/usr/bin:";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 0) {
    usage();
}
if (defined($options{"d"})) {
    $debug = $options{"d"};
}
if (defined($options{"n"})) {
    $impotent = 1;
}
165 166
if (defined($options{"D"})) {
    $autodestroy = 0;
167 168 169 170
}
if (defined($options{"I"})) {
    $checkint = $options{"I"} * 60;
}
Mike Hibler's avatar
Mike Hibler committed
171 172 173
if (defined($options{"1"})) {
    $onceonly = 1;
}
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 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

# This should always run as root.
if ($UID != 0) {
    die("*** $0:\n".
	"    Only root can run this script!\n");
}

# Only one please.
if (CheckDaemonRunning("lease_daemon")) {
    fatal("Not starting another lease daemon!");
}

# Go to ground.
if (!$debug) {
    if (TBBackGround($logfile)) {
	exit(0);
    }
}
if (MarkDaemonRunning("lease_daemon")) {
    fatal("Could not mark daemon as running!");
}

#
# Figure out what happened while we were away.
# Read all the current leases and find the lastest check stamp.
#

#
# Setup a signal handler for newsyslog.
#
sub handler()
{
    ReOpenLog($logfile);
}
$SIG{HUP} = \&handler
    if (!$debug);

#
# Let the show begin!
#
logit("Lease monitoring daemon starting... pid $$");

my $started = 0;
while (1) {
    if ($started) {
Mike Hibler's avatar
Mike Hibler committed
219 220
	exit(0)
	    if ($onceonly);
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 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
	Lease->FlushAll();
	sleep($checkint);
    } else {
	$started = 1;
    }
    logit("=== Starting pass.");
    my $now = time();

    #
    # Get the current values of the site variables.
    # XXX Maybe we should only do this once or on explicit HUP?
    #
    if (get_vars()) {
	logit("Could not get lease-related site variables, waiting awhile...");
	next;
    }

    #
    # Read all the leases and catagorize them by state.
    #
    my @allleases = Lease->AllLeases();
    my %leases = ();
    foreach my $lease (@allleases) {
	my $state = $lease->state();
	if (!exists($leases{$state})) {
	    $leases{$state} = ();
	}
	push(@{$leases{$state}}, $lease);
    }

    #
    # 1. Unapproved leases.
    #    Check for unapproved leases that have not been reported on in
    #    the last day and report them.
    #
    logit("Checking unapproved leases...");
    my @report = ();
    foreach my $lease (@{$leases{LEASE_STATE_UNAPPROVED()}}) {
	logit("  $lease")
	    if ($debug);

	# If we are in the first interval of the reporting period, we report.
	my $delta = $now - $lease->statestamp();
	if (($delta % $REPORT_UNAPPROVED) < $checkint) {
	    push(@report, $lease);
	}
	$lease->BumpLastChecked();
    }
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would report unapproved leases: " . join(' ', @report));
	} else {
	    if ($debug) {
		logit("  Reporting unapproved leases: " . join(' ', @report));
	    }
	    notify("Leases awaiting approval:\n" . lease_list(@report));
	}
	@report = ();
    }

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
    #
    # 1b. Failed leases.
    #    Check for failed leases that have not been reported on in
    #    the last day and report them.
    #
    logit("Checking failed leases...");
    foreach my $lease (@{$leases{LEASE_STATE_FAILED()}}) {
	logit("  $lease")
	    if ($debug);

	# If we are in the first interval of the reporting period, we report.
	my $delta = $now - $lease->statestamp();
	if (($delta % $REPORT_FAILED) < $checkint) {
	    push(@report, $lease);
	}
	$lease->BumpLastChecked();
    }
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would report failed leases: " . join(' ', @report));
	} else {
	    if ($debug) {
		logit("  Reporting failed leases: " . join(' ', @report));
	    }
	    notify("Failed leases awaiting handling:\n" . lease_list(@report));
	}
	@report = ();
    }

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 337 338 339 340 341 342 343 344 345 346 347 348
    #
    # 2. Locked leases.
    #    Locked leases are ones that have been made administratively
    #    unavailable. We just report them once in a blue moon.
    #
    logit("Checking locked leases...");
    foreach my $lease (@{$leases{LEASE_STATE_LOCKED()}}) {
	logit("  $lease")
	    if ($debug);

	# If we are in the first interval of the reporting period, we report.
	my $delta = $now - $lease->statestamp();
	if (($delta % $REPORT_LOCKED) < $checkint) {
	    push(@report, $lease);
	}
	$lease->BumpLastChecked();
    }
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would report locked leases: " . join(' ', @report));
	} else {
	    if ($debug) {
		logit("  Reporting locked leases: " . join(' ', @report));
	    }
	    notify("Leases administratively locked:\n" . lease_list(@report));
	}
	@report = ();
    }

    #
    # 3. Valid leases.
    #    Update last_used time for leases that are currently in use.
    #
    logit("Updating last_used time for active leases...");
    foreach my $lease (@{$leases{LEASE_STATE_VALID()}}) {
	logit("  $lease")
	    if ($debug);

	if ($lease->InUse() > 0) {
Mike Hibler's avatar
Mike Hibler committed
349
	    push(@report, $lease);
350
	    if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
351
		next;
352
	    }
Mike Hibler's avatar
Mike Hibler committed
353 354 355 356 357 358 359 360
	    $lease->SetLastUsedTime($now);
	}
    }
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would update last_used for: " . join(' ', @report));
	} else {
	    logit("  Updated last_used for: " . join(' ', @report));
361
	}
Mike Hibler's avatar
Mike Hibler committed
362
	@report = ();
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    }

    #
    # 4. Valid leases.
    #    Check for idle datasets. If there is a max_idle time associated
    #    with the lease type and a lease is over that, put the lease into
    #    the grace state and inform the owner. Ditto if the lease has
    #    past its expiration time.
    #
    logit("Checking for idle and expired leases...");
    foreach my $lease (@{$leases{LEASE_STATE_VALID()}}) {
	my $ltype = $lease->type();
	logit("  $lease")
	    if ($debug);

Mike Hibler's avatar
Mike Hibler committed
378 379
	my $delta = $now -
	    ($lease->last_used() ? $lease->last_used() : $lease->inception());
380 381 382 383
	my $limit = $vars{$ltype}->{'maxidle'};
	if ($limit > 0 && $delta > $limit) {
	    logit("    idle ($delta > $limit)...")
		if ($debug);
Mike Hibler's avatar
Mike Hibler committed
384

385
	    if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
386
		push(@report, $lease);
387 388 389 390 391
		next;
	    }
	    if (graceify($lease, 0)) {
		logit("  WARNING: $lease: could not change state, skipping");
	    } else {
Mike Hibler's avatar
Mike Hibler committed
392
		push(@report, $lease);
393 394 395 396 397 398 399 400 401 402
		push(@{$leases{LEASE_STATE_GRACE()}}, $lease);
	    }
	    $lease->BumpLastChecked();
	    next;
	}

	my $expire = $lease->expiration();
	if ($now >= $expire) {
	    logit("    expired ($now > $expire)...")
		if ($debug);
Mike Hibler's avatar
Mike Hibler committed
403

404
	    if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
405
		push(@report, $lease);
406 407 408 409 410
		next;
	    }
	    if (graceify($lease, 1)) {
		logit("  WARNING: $lease: could not change state, skipping");
	    } else {
Mike Hibler's avatar
Mike Hibler committed
411
		push(@report, $lease);
412 413 414 415 416 417 418 419
		push(@{$leases{LEASE_STATE_GRACE()}}, $lease);
	    }
	    $lease->BumpLastChecked();
	    next;
	}

	$lease->BumpLastChecked();
    }
Mike Hibler's avatar
Mike Hibler committed
420 421 422 423 424 425 426 427
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would move to grace: " . join(' ', @report));
	} else {
	    logit("  Moved to grace: " . join(' ', @report));
	}
	@report = ();
    }
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

    #
    # 5. En-graced leases.
    #    Check for those that are past the grace period and mark them as
    #    locked or expired (depending on whether we allow auto-destruction
    #    of that type of lease).
    #
    logit("Checking leases with expired grace time...");
    foreach my $lease (@{$leases{LEASE_STATE_GRACE()}}) {
	my $ltype = $lease->type();
	logit("  $lease")
	    if ($debug);

	my $delta = $now - $lease->statestamp();
	# XXX this can happen due to putting lease in grace state above
	$delta = 0
	    if ($delta < 0);
	my $limit = $vars{$ltype}->{'graceperiod'};
	if ($delta >= $limit) {
	    if ($vars{$ltype}->{'autodestroy'} && $autodestroy) {
		if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
449
		    push(@report, $lease);
450 451 452 453 454
		    next;
		}
		if (changestate($lease, LEASE_STATE_EXPIRED())) {
		    logit("  WARNING: $lease: could not expire, skipping");
		} else {
Mike Hibler's avatar
Mike Hibler committed
455
		    push(@report, $lease);
456 457 458 459
		    push(@{$leases{LEASE_STATE_EXPIRED()}}, $lease);
		}
	    } else {
		if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
460
		    push(@report, $lease);
461 462 463 464
		    next;
		}
		if (lockify($lease)) {
		    logit("  WARNING: $lease: could not lockdown, skipping");
465
		} else {
Mike Hibler's avatar
Mike Hibler committed
466
		    push(@report, $lease);
467 468
		    # XXX make a note of why it is locked
		    $lease->SetAttribute("why", "lease_daemon_no_autodestroy");
469 470 471 472 473
		}
	    }
	    $lease->BumpLastChecked();
	}
    }
Mike Hibler's avatar
Mike Hibler committed
474 475 476 477 478 479 480 481
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would move to expired: " . join(' ', @report));
	} else {
	    logit("  Moved to expired: " . join(' ', @report));
	}
	@report = ();
    }
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

    #
    # 6. Expired leases.
    #    Nuke em!
    #
    logit("Checking for leases to destroy...");
    foreach my $lease (@{$leases{LEASE_STATE_EXPIRED()}}) {
	my $ltype = $lease->type();
	logit("  $lease")
	    if ($debug);

	if ($impotent) {
	    logit("  Would destroy");
	    next;
	}
	if (!$autodestroy) {
	    logit("  WARNING: $lease: not destroyed due to no 'autodestroy'");

	    # If we are in the first interval of the reporting period, do it.
	    my $delta = $now - $lease->statestamp();
	    if (($delta % $REPORT_EXPIRED) < $checkint) {
		push(@report, $lease);
	    }
	} else {
	    if (destroy($lease)) {
		logit("  WARNING: $lease: could not destroy, skipping");
	    } else {
Mike Hibler's avatar
Mike Hibler committed
509
		logit("  $lease: destroyed!");
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
		$lease = undef;
	    }
	}
	$lease->BumpLastChecked()
	    if ($lease);
	next;
    }
    if (@report > 0) {
	if ($debug) {
	    logit("  Reporting expired leases: " . join(' ', @report));
	}
	notify("Leases in expired state needing cleanup:\n" . lease_list(@report));
	@report = ();
    }

    logit("=== Finished pass");
}
fatal("forever just ended!");

#
# Atomically change the state of a lease.
# Returns 0 on success, non-zero otherwise.
#
sub changestate($$)
{
    my ($lease,$nstate) = @_;
    my $ostate = $lease->state();

    if ($lease->WaitLock(1)) {
	logit("$lease: could not get lock");
	return 1;
    }
    # See if the state changed while locking
    if ($ostate ne $lease->state()) {
	logit("$lease: changed state while acquiring lock ($ostate -> " . $lease->state() . ")");
	$lease->Unlock();
	return 2;
    }

    $lease->UpdateState($nstate);
    $lease->Unlock();
    return 0;
}

#
# Move a lease into the grace state. If there is a graceperiod, then we
# report to the user as well. Otherwise they will get an expiration notice
# instead. Return 0 on success, non-zero otherwise.
#
sub graceify($$)
{
    my ($lease,$expired) = @_;
    my $ltype = $lease->type();
Mike Hibler's avatar
Mike Hibler committed
563
    my $grace = $vars{$ltype}->{'graceperiod'};
564
    my $extend = $vars{$ltype}->{'extendperiod'};
565 566 567 568 569

    if (changestate($lease, LEASE_STATE_GRACE())) {
	return 1;
    }

Mike Hibler's avatar
Mike Hibler committed
570 571
    if ($grace > 0) {
	my $ghours = sprintf("%.1f", $grace / (60 * 60));
572
	my $reason = ($expired ? "expired" : "been idle too long");
573 574
	my $name = $lease->pid() . "/" .
	    $lease->gid() . "/" . $lease->lease_id();
575
	my $msg =
Mike Hibler's avatar
Mike Hibler committed
576
	    "Your '$ltype' lease $name has $reason.\n".
577
	    "It has entered a $ghours hour grace period.\n\n";
Mike Hibler's avatar
Mike Hibler committed
578
	$msg .=
579
	    "You need to extend the dataset lifetime\n".
Mike Hibler's avatar
Mike Hibler committed
580 581
	    "or move your data out of Emulab within this time period.\n".
	    "If you do not, the dataset will be destroyed and\n".
582
	    "THE DATA WILL NOT BE RECOVERABLE.\n\n";
583 584 585 586 587 588 589 590 591 592
	if ($extend) {
	    $msg .=
		"To extend the dataset, ssh into $OPSNODE and run:\n".
		"  $TB/bin/extenddataset $name\n".
		"If that fails, contact $TBOPS\n";
	} else {
	    $msg .=
		"To extend the dataset, you will need to contact $TBOPS\n".
		"and request an extension for $name.\n";
	}
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
	notifyuser($lease->owner(), $msg);
    }

    return 0;
}

sub lockify($)
{
    my ($lease) = @_;
    my $ltype = $lease->type();

    if (changestate($lease, LEASE_STATE_LOCKED())) {
	return 1;
    }

608 609
    my $name = $lease->pid() . "/" .
	$lease->gid() . "/" . $lease->lease_id();
610
    my $msg =
Mike Hibler's avatar
Mike Hibler committed
611 612
	"Your '$ltype' lease $name has expired.\n".
	"It has been administratively locked.\n";
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    notifyuser($lease->owner(), $msg);

    return 0;
}

#
# Destroy an expired lease.
# Returns 0 on success, non-zero otherwise.
#
sub destroy($)
{
    my ($lease) = @_;
    my $ostate = $lease->state();

    my $rv = $lease->WaitLock(1);
    if ($rv == LEASE_ERROR_GONE()) {
	logit("$lease: someone else deleted it");
	return 0;
    }
632
    # could not get the lock, leave expired so we will try again next pass
633
    if ($rv) {
634 635
	# XXX make a note of why it is left expired
	$lease->SetAttribute("why", "lease_daemon_cannot_lock");
636 637 638 639 640 641 642 643 644 645 646
	logit("$lease: could not get lock");
	return 1;
    }
    if ($ostate ne $lease->state()) {
	$lease->Unlock();
	logit("$lease: changed state while acquiring lock ($ostate -> " . $lease->state() . ")");
	return 2;
    }

    # if the lease is in use, disallow
    if ($lease->InUse()) {
647 648
	# XXX make a note of why it is left expired
	$lease->SetAttribute("why", "lease_daemon_in_use");
649 650 651 652 653 654
	$lease->Unlock();
	logit("$lease: in use, cannot be destroyed");
	return 3;
    }

    #
655 656 657
    # Failures after this will leave the lease in a weird way.
    # So we report failures to testbed-ops and make sure we are not left
    # in the expired state.
658 659 660 661 662
    #

    # If Dealloc fails, we put the lease in the locked state instead
    if ($lease->DeallocResources()) {
	$lease->UpdateState(LEASE_STATE_LOCKED());
663
	# XXX make a note of why it is left locked
664
	$lease->SetAttribute("why", "lease_daemon_dealloc_failed");
665 666 667 668 669
	$lease->Unlock();
	notify("$lease: resource dealloc failed during destruction. Manual cleanup required.");
	return 4;
    }

670 671
    my $name = $lease->pid() . "/" .
	$lease->gid() . "/" . $lease->lease_id();
672 673 674 675 676
    my $ltype = $lease->type();
    my $uid = $lease->owner();

    # If Delete fails, we are left in the unapproved state
    if ($lease->Delete()) {
677 678
	# XXX make a note of why it is here
	$lease->SetAttribute("why", "lease_daemon_delete_failed");
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 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
	$lease->Unlock();
	notify("$lease: could not destroy lease, left in unapproved state. Manual cleanup required.");
	return 5;
    }

    my $msg =
	"Your '$ltype' lease $name has expired and has been destroyed.\n";
    notifyuser($uid, $msg);

    return 0;
}


sub get_vars()
{
    my $v;

    foreach my $lt ("stdataset", "ltdataset") {
	$v = Lease->SiteVars($lt);
	return -1
	    if (!defined($v));

	$vars{$lt} = $v;
    }

    return 0;
}

#
# Create a string, suitable for printing, with info about the given leases.
#
sub lease_list(@)
{
    my @leases = @_;

    return ""
	if (@leases == 0);

    my %states = (
	"valid" =>      'valid',
	"unapproved" => 'unappr',
	"grace" =>      'grace',
	"locked" =>     'locked',
	"expired" =>    'expire'
    );
    my $fmt = "%-24s %-8s %-10s %-6s %3s %-15s %-15s %-15s %s\n";

    my $str = sprintf($fmt, "Pid/Name", "Owner", "Type", "State", "Use",
		      "Inception", "End", "Last used", "Attrs");
    foreach my $lease (@leases) {
	# Attributes
	my $attrstr = "";
	my $attrs = $lease->GetAttributes();
	if ($attrs) {
	    my $del = "";
	    foreach my $k (keys %{$attrs}) {
		my $v = $attrs->{$k}->{'value'};
		$attrstr .= "$del$k=$v";
		$del = ",";
	    }
	}

741 742
	my $lname = $lease->pid() . "/" .
	    $lease->gid() . "/" . $lease->lease_id();
743 744 745 746 747 748
	my $stime = strftime("%D %R", localtime($lease->inception()));
	my $etime = strftime("%D %R", localtime($lease->lease_end()));
	my $ltime = "never";
	if ($lease->last_used()) {
	    $ltime = strftime("%D %R", localtime($lease->last_used()));
	}
749
	my $lusers = $lease->GetReservations();
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 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
	if (!$lusers) {
	    $lusers = ();
	}
	$str .= sprintf($fmt, $lname, $lease->owner(), $lease->type(),
			$states{$lease->state()}, int(@$lusers),
			$stime, $etime, $ltime, $attrstr);
    }

    return $str;
}

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

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "Lease Daemon died",
	     $msg,
	     $TBOPS)
	if (!$impotent);

    MarkDaemonStopped("lease_daemon");

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

sub logit($)
{
    my ($msg) = @_;
    my $stamp = POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime());

    print "$stamp: $msg\n";
}

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

    logit("sending mail to $TBOPS:\n$msg");
    SENDMAIL($TBOPS, "Lease Daemon Message",
	     "Lease Daemon Message:\n\n$msg", $TBOPS)
	if (!$impotent);
}

sub notifyuser($$)
{
    my ($uid,$msg) = @_;

    my $user = User->LookupByUid($uid);
    if ($user) {
	my $email = $user->email();
	logit("sending mail to $email:\n$msg");
	SENDMAIL($email, "Lease Daemon Message",
		 "Lease Daemon Message:\n\n$msg", $TBOPS)
	    if (!$impotent);
    }
}