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

#
4
# Copyright (c) 2013-2016 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
# 
# {{{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.
#
# * 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
59 60 61 62 63 64 65 66 67 68 69 70 71
# 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 
#
72

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

Mike Hibler's avatar
Mike Hibler committed
78 79 80 81 82
## debugging
#my $CHECK		= (1 * 60);
#my $REPORT_UNAPPROVED	= (2 * 60);
#my $REPORT_LOCKED	= (3 * 60);
#my $REPORT_EXPIRED	= (2 * 60);
83 84 85 86 87 88

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

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

# 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;
129
my $autodestroy = 1;
130
my $checkint	= $CHECK;
Mike Hibler's avatar
Mike Hibler committed
131
my $onceonly	= 0;
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

#
# 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;
}
161 162
if (defined($options{"D"})) {
    $autodestroy = 0;
163 164 165 166
}
if (defined($options{"I"})) {
    $checkint = $options{"I"} * 60;
}
Mike Hibler's avatar
Mike Hibler committed
167 168 169
if (defined($options{"1"})) {
    $onceonly = 1;
}
170 171 172 173 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

# 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
215 216
	exit(0)
	    if ($onceonly);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 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 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
	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 = ();
    }

    #
    # 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
316
	    push(@report, $lease);
317
	    if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
318
		next;
319
	    }
Mike Hibler's avatar
Mike Hibler committed
320 321 322 323 324 325 326 327
	    $lease->SetLastUsedTime($now);
	}
    }
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would update last_used for: " . join(' ', @report));
	} else {
	    logit("  Updated last_used for: " . join(' ', @report));
328
	}
Mike Hibler's avatar
Mike Hibler committed
329
	@report = ();
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    }

    #
    # 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
345 346
	my $delta = $now -
	    ($lease->last_used() ? $lease->last_used() : $lease->inception());
347 348 349 350
	my $limit = $vars{$ltype}->{'maxidle'};
	if ($limit > 0 && $delta > $limit) {
	    logit("    idle ($delta > $limit)...")
		if ($debug);
Mike Hibler's avatar
Mike Hibler committed
351

352
	    if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
353
		push(@report, $lease);
354 355 356 357 358
		next;
	    }
	    if (graceify($lease, 0)) {
		logit("  WARNING: $lease: could not change state, skipping");
	    } else {
Mike Hibler's avatar
Mike Hibler committed
359
		push(@report, $lease);
360 361 362 363 364 365 366 367 368 369
		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
370

371
	    if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
372
		push(@report, $lease);
373 374 375 376 377
		next;
	    }
	    if (graceify($lease, 1)) {
		logit("  WARNING: $lease: could not change state, skipping");
	    } else {
Mike Hibler's avatar
Mike Hibler committed
378
		push(@report, $lease);
379 380 381 382 383 384 385 386
		push(@{$leases{LEASE_STATE_GRACE()}}, $lease);
	    }
	    $lease->BumpLastChecked();
	    next;
	}

	$lease->BumpLastChecked();
    }
Mike Hibler's avatar
Mike Hibler committed
387 388 389 390 391 392 393 394
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would move to grace: " . join(' ', @report));
	} else {
	    logit("  Moved to grace: " . join(' ', @report));
	}
	@report = ();
    }
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

    #
    # 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
416
		    push(@report, $lease);
417 418 419 420 421
		    next;
		}
		if (changestate($lease, LEASE_STATE_EXPIRED())) {
		    logit("  WARNING: $lease: could not expire, skipping");
		} else {
Mike Hibler's avatar
Mike Hibler committed
422
		    push(@report, $lease);
423 424 425 426
		    push(@{$leases{LEASE_STATE_EXPIRED()}}, $lease);
		}
	    } else {
		if ($impotent) {
Mike Hibler's avatar
Mike Hibler committed
427
		    push(@report, $lease);
428 429 430 431
		    next;
		}
		if (lockify($lease)) {
		    logit("  WARNING: $lease: could not lockdown, skipping");
432
		} else {
Mike Hibler's avatar
Mike Hibler committed
433
		    push(@report, $lease);
434 435
		    # XXX make a note of why it is locked
		    $lease->SetAttribute("why", "lease_daemon_no_autodestroy");
436 437 438 439 440
		}
	    }
	    $lease->BumpLastChecked();
	}
    }
Mike Hibler's avatar
Mike Hibler committed
441 442 443 444 445 446 447 448
    if (@report > 0) {
	if ($impotent) {
	    logit("  Would move to expired: " . join(' ', @report));
	} else {
	    logit("  Moved to expired: " . join(' ', @report));
	}
	@report = ();
    }
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

    #
    # 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
476
		logit("  $lease: destroyed!");
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
		$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
530
    my $grace = $vars{$ltype}->{'graceperiod'};
531
    my $extend = $vars{$ltype}->{'extendperiod'};
532 533 534 535 536

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

Mike Hibler's avatar
Mike Hibler committed
537 538
    if ($grace > 0) {
	my $ghours = sprintf("%.1f", $grace / (60 * 60));
539
	my $reason = ($expired ? "expired" : "been idle too long");
540 541
	my $name = $lease->pid() . "/" .
	    $lease->gid() . "/" . $lease->lease_id();
542
	my $msg =
Mike Hibler's avatar
Mike Hibler committed
543
	    "Your '$ltype' lease $name has $reason.\n".
544
	    "It has entered a $ghours hour grace period.\n\n";
Mike Hibler's avatar
Mike Hibler committed
545
	$msg .=
546
	    "You need to extend the dataset lifetime\n".
Mike Hibler's avatar
Mike Hibler committed
547 548
	    "or move your data out of Emulab within this time period.\n".
	    "If you do not, the dataset will be destroyed and\n".
549
	    "THE DATA WILL NOT BE RECOVERABLE.\n\n";
550 551 552 553 554 555 556 557 558 559
	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";
	}
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	notifyuser($lease->owner(), $msg);
    }

    return 0;
}

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

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

575 576
    my $name = $lease->pid() . "/" .
	$lease->gid() . "/" . $lease->lease_id();
577
    my $msg =
Mike Hibler's avatar
Mike Hibler committed
578 579
	"Your '$ltype' lease $name has expired.\n".
	"It has been administratively locked.\n";
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
    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;
    }
599
    # could not get the lock, leave expired so we will try again next pass
600
    if ($rv) {
601 602
	# XXX make a note of why it is left expired
	$lease->SetAttribute("why", "lease_daemon_cannot_lock");
603 604 605 606 607 608 609 610 611 612 613
	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()) {
614 615
	# XXX make a note of why it is left expired
	$lease->SetAttribute("why", "lease_daemon_in_use");
616 617 618 619 620 621
	$lease->Unlock();
	logit("$lease: in use, cannot be destroyed");
	return 3;
    }

    #
622 623 624
    # 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.
625 626 627 628 629
    #

    # If Dealloc fails, we put the lease in the locked state instead
    if ($lease->DeallocResources()) {
	$lease->UpdateState(LEASE_STATE_LOCKED());
630
	# XXX make a note of why it is left locked
631
	$lease->SetAttribute("why", "lease_daemon_dealloc_failed");
632 633 634 635 636
	$lease->Unlock();
	notify("$lease: resource dealloc failed during destruction. Manual cleanup required.");
	return 4;
    }

637 638
    my $name = $lease->pid() . "/" .
	$lease->gid() . "/" . $lease->lease_id();
639 640 641 642 643
    my $ltype = $lease->type();
    my $uid = $lease->owner();

    # If Delete fails, we are left in the unapproved state
    if ($lease->Delete()) {
644 645
	# XXX make a note of why it is here
	$lease->SetAttribute("why", "lease_daemon_delete_failed");
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 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
	$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 = ",";
	    }
	}

708 709
	my $lname = $lease->pid() . "/" .
	    $lease->gid() . "/" . $lease->lease_id();
710 711 712 713 714 715
	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()));
	}
716
	my $lusers = $lease->GetReservations();
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
	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);
    }
}