libtestbed.pm.in 19.8 KB
Newer Older
1
#!/usr/bin/perl -w
Leigh Stoller's avatar
Leigh Stoller committed
2 3 4

#
# EMULAB-COPYRIGHT
5
# Copyright (c) 2000-2010 University of Utah and the Flux Group.
Leigh Stoller's avatar
Leigh Stoller committed
6 7 8
# All rights reserved.
#

9 10 11 12 13
package libtestbed;
use Exporter;

@ISA = "Exporter";
@EXPORT =
14
    qw ( SENDMAIL AnonSENDMAIL OPENMAIL TBTimeStamp TBBackGround TBDateTimeFSSafe
15 16
	 TBMakeLogname TB_BOSSNODE TB_OPSEMAIL TB_WWWEMAIL TB_AUDITEMAIL
	 TBMAIL_OPS TBMAIL_WWW TBMAIL_AUDIT TBGenSecretKey TBDebugTimeStamp
17
	 TBDebugTimeStampsOn TBForkCmd TB_BOSSEVENTPORT TB_EVENTSERVER
18
	 TBScriptLock TBScriptUnlock TBTimeStampWithDate
19
	 TBSCRIPTLOCK_OKAY TBSCRIPTLOCK_TIMEDOUT
20 21
	 TBSCRIPTLOCK_IGNORE TBSCRIPTLOCK_FAILED
	 PROJROOT GROUPROOT USERROOT SCRATCHROOT SHAREROOT
22
	 TBValidUserDir TBValidUserDirList TBMakeTempFile NewUUID System
23 24
	 SendProjAdminMail ReOpenLog
	 CheckDaemonRunning MarkDaemonRunning MarkDaemonStopped);
25 26 27
@EXPORT_OK =
    qw ( TBMAIL_PROJADMIN);

28

29 30 31 32 33
# After package decl.
use English;
use POSIX qw(strftime);
use POSIX qw(setsid);
use Fcntl;
34
use Fcntl ':flock';
35
use File::Basename;
36
use Time::HiRes qw(gettimeofday);
37
use vars qw(@EXPORT_OK);
38

39
my $TB           = "@prefix@";
40 41 42 43 44 45 46
#my $MAILTAG	 = "@OURDOMAIN@";
my $MAILTAG	 = "@THISHOMEBASE@";
my $BOSSNODE	 = "@BOSSNODE@";
my $TIMESTAMPS	 = "@TIMESTAMPS@";
my $TBOPSEMAIL	 = "@TBOPSEMAIL@";
my $TBWWWEMAIL	 = "@TBWWWEMAIL@";
my $TBAUDITEMAIL = "@TBAUDITEMAIL@";
47
my $UUIDGEN	 = "@UUIDGEN@";
48
my $NOREPLY      = "no-reply\@@OURDOMAIN@";
49
my $SCRIPTNAME	 = "Unknown";
50

51 52 53 54
# Exported.
$SYSTEM_DEBUG = 0;
@EXPORT_OK    = qw($SYSTEM_DEBUG);

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#
# Real mount points (on the fileserver) for exported directories.
# At the moment, we have no reason to export these via functions.
#
my $FSDIR_USER = "@FSDIR_USERS@";
my $FSDIR_PROJ = "@FSDIR_PROJ@";
my $FSDIR_GROUPS = "@FSDIR_GROUPS@";
my $FSDIR_SHARE = "@FSDIR_SHARE@";
my $FSDIR_SCRATCH = "@FSDIR_SCRATCH@";

#
# Standard mountpoints for exported directories.
# The scratch directory is optional, hence the FSDIR_SCRATCH check.
#
my $PROJROOT    = "@PROJROOT_DIR@";
my $GROUPROOT   = "@GROUPSROOT_DIR@";
my $USERROOT    = "@USERSROOT_DIR@";
my $SCRATCHROOT	= "@SCRATCHROOT_DIR@";
my $SHAREROOT	= "@SHAREROOT_DIR@";
sub PROJROOT()	  { $PROJROOT; }
sub GROUPROOT()	  { $GROUPROOT; }
sub USERROOT()	  { $USERROOT; }
sub SHAREROOT()   { $SHAREROOT; }
sub SCRATCHROOT() { $FSDIR_SCRATCH ? $SCRATCHROOT : ""; }

80 81
# Hostname of our boss node
sub TB_BOSSNODE()	{ $BOSSNODE; }
82

83 84 85 86 87 88 89
# Testbed email addresses.
sub TB_OPSEMAIL()   { $TBOPSEMAIL; }
sub TB_WWWEMAIL()   { $TBWWWEMAIL; }
sub TB_AUDITEMAIL() { $TBAUDITEMAIL; }
sub TBMAIL_OPS()    { "Testbed Ops <$TBOPSEMAIL>"; }
sub TBMAIL_WWW()    { "Testbed WWW <$TBWWWEMAIL>"; }
sub TBMAIL_AUDIT()  { "Testbed Audit <$TBAUDITEMAIL>" }
90

91 92 93 94 95
# TBMAIL_PROJADMIN should, in general, not be used directly, use
# SendProjAdminMail
sub TBMAIL_PROJADMIN($) {
    @MAILMANSUPPORT@ ? "$_[0]-admin\@@OURDOMAIN@" : "@TBAPPROVALEMAIL@";
}
96 97 98
sub TBMAIL_APPROVAL() {
    "@TBAPPROVALEMAIL@";
}
99

100 101
# This is for the swigged event library which includes this file.
sub TB_BOSSEVENTPORT()  { "@BOSSEVENTPORT@"; }
102
sub TB_EVENTSERVER()    { "@EVENTSERVER@" . "." . "@OURDOMAIN@"; }
103

104 105 106
# Untainted scriptname for email below.
if ($PROGRAM_NAME =~ /^([-\w\.\/]+)$/) {
    $SCRIPTNAME = basename($1);
107
    $PROGRAM_NAME = $SCRIPTNAME;
108 109 110 111 112
}
else {
    $SCRIPTNAME = "Tainted";
}

113 114 115
#
# Turn off line buffering on output
#
116 117 118 119
select STDERR;
$OUTPUT_AUTOFLUSH = 1;
select STDOUT;
$OUTPUT_AUTOFLUSH = 1;
120 121 122 123 124 125 126

# Send an email message via sendmail -t.
#
# I am mimicking the PHP mail interface, only because I'm old and its
# hard to remember new things. I did add a From arg since thats basically
# required to make the mail look nice (not generated by root or daemon!).
#
127 128 129
# SENDMAIL(Command, To, Subject, Message, [From], [More Headers], [files to append])
# AnonSENDMAIL is like SENDMAIL except that the envelope sender is from root rather
#   than who the script is being ran as
130
#
131 132 133 134 135 136 137 138 139
sub SENDMAILWith($$$$;$$@);

sub SENDMAIL($$$;$$@) 
{
    my($To, $Subject, $Message, $From, $Headers, @Files) = @_;
    SENDMAILWith("/usr/sbin/sendmail -t", $To, $Subject, $Message, $From, $Headers, @Files);
}

sub AnonSENDMAIL($$$;$$@)
140
{
141
    my($To, $Subject, $Message, $From, $Headers, @Files) = @_;
142 143 144 145 146 147 148 149 150 151 152 153 154
    $From = $NOREPLY unless $From;

    # To get around perl's annoying "YOU HAVEN'T DISABLED SET-ID
    # SCRIPTS IN THE KERNEL YET!" when one SUID script executes another
    # SUID script
    local $UID = $EUID;

    SENDMAILWith("$TB/sbin/anonsendmail", $To, $Subject, $Message, $From, $Headers, @Files);
}

sub SENDMAILWith($$$$;$$@)
{
    my($Command, $To, $Subject, $Message, $From, $Headers, @Files) = @_;
155
    my $tag = uc($MAILTAG);
156

157
    #
158
    # Untaint the path locally. Note that using a "local" fails on older perl!
159
    # 
160 161
    my $SAVE_PATH = $ENV{'PATH'};
    $ENV{'PATH'} = "/bin:/usr/bin";
162 163
    delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

164
    if (! open(MAIL, "| $Command")) {
165
	print STDERR "SENDMAIL: Could not start sendmail: $!\n";
166
	goto bad;
167 168 169 170 171 172 173 174
    }

    #
    # Sendmail will figure this out if not given.
    # 
    if (defined($From) && $From) {
	print MAIL "From: $From\n";
    }
175
    if (defined($Headers) && length($Headers) > 0) {
176 177
	print MAIL "$Headers\n";
    }
178
    print MAIL "X-NetBed: $SCRIPTNAME\n";
179 180 181
    if (defined($To)) {
	print MAIL "To: $To\n";
    }
182
    print MAIL "Subject: $tag: $Subject\n";
183 184
    print MAIL "\n";
    print MAIL "$Message\n";
Leigh Stoller's avatar
Leigh Stoller committed
185 186
    print MAIL "\n";

187
    if (@Files) {
Leigh Stoller's avatar
Leigh Stoller committed
188
	foreach my $file ( @Files ) {
189
	    if (defined($file) && open(IN, "$file")) {
190
		print MAIL "\n--------- $file --------\n";
Leigh Stoller's avatar
Leigh Stoller committed
191 192 193 194 195 196 197 198 199

		while (<IN>) {
		    print MAIL "$_";
		}
		close(IN);
	    }
	}
    }
    
200 201 202
    print MAIL "\n";
    if (! close(MAIL)) {
	print STDERR "SENDMAIL: Could not finish sendmail: $!\n";
203
	goto bad;
204
    }
205
    $ENV{'PATH'} = $SAVE_PATH;
206
    return 1;
207 208

  bad:
209
    $ENV{'PATH'} = $SAVE_PATH;
210
    return 0;
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
}

#
# Fire up a sendmail process, and return the handle for the caller
# to print the body of the message into. This is easer in many places.
#
# OPENMAIL(To, Subject, [From], [More Headers])
#
sub OPENMAIL($$;$$)
{
    my($To, $Subject, $From, $Headers) = @_;
    local *MAIL;

    if (! open(MAIL, "|/usr/sbin/sendmail -t")) {
	print STDERR "OPENMAIL: Could not start sendmail: $!\n";
	return 0;
    }

    #
    # Sendmail will figure this out if not given.
    # 
    if (defined($From) && $From) {
	print MAIL "From: $From\n";
    }
    print MAIL "To: $To\n";
236
    print MAIL "Subject: $tag: $Subject\n";
237 238 239
    if (defined($Headers)) {
	print MAIL "$Headers\n";
    }
240
    print MAIL "X-NetBed: $SCRIPTNAME\n";
241 242 243 244 245
    print MAIL "\n";

    return(*MAIL);
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
#
# Send Admin related mail for a project
#
# SendProjAdminMail(Proj, From, To, Subject, Message, [More Headers]);
# One of From or To is expected to be "ADMIN", the other is expected to
# be a real email address or "AUDIT"....
# 
# the project admin mailing list.

sub SendProjAdminMail($$$$$;$)
{
    my ($proj, $from, $to, $subject, $message, $headers) = @_;
    my $projadminmail = TBMAIL_PROJADMIN($proj);
    $headers .= "\n" if defined $headers;
    if ($from eq 'ADMIN') {
	$from = $projadminmail;
	$headers .= "Bcc: $projadminmail\n"; 
   } elsif ($to eq 'ADMIN') {
	$to = $projadminmail;
265 266 267 268 269
	if ($projadminmail ne TBMAIL_APPROVAL) {
	    # to make sure the mail is sent, since sometimes the
	    # initial mail to the PROJ-admin doesn't, for some reason
	    $headers .= "Bcc: " . TBMAIL_APPROVAL . "\n";
	}
270 271 272 273 274 275 276 277 278 279 280 281 282
	$headers .= "Reply-To: $projadminmail\n";
    } else {
	$headers .= "Bcc: $projadminmail\n";
    }
    if ($from eq 'AUDIT') {
	$from = TB_AUDITEMAIL;
	$headers .= "Bcc: " . TB_AUDITEMAIL . "\n";
    } elsif ($to eq "AUDIT") {
	$to = TB_AUDITEMAIL;
    } else {
	$headers .= "Bcc: " . TB_AUDITEMAIL . "\n";
    }
    chop $headers;
283
    AnonSENDMAIL($to, $subject, $message, $from, $headers);
284 285
}

286 287 288 289 290 291 292
#
# Return a timestamp. We don't care about day/date/year. Just the time mam.
# 
# TBTimeStamp()
#
sub TBTimeStamp()
{
293 294 295
    my ($seconds, $microseconds) = gettimeofday();
    
    return POSIX::strftime("%H:%M:%S", localtime($seconds)) . ":$microseconds";
296 297
}

298 299 300 301 302
sub TBTimeStampWithDate()
{
    return POSIX::strftime("%m/%d/20%y %H:%M:%S", localtime());
}

303 304 305 306 307 308 309 310 311
#
# Another routine for creating a file name based on the current date and
# time. The format is slightly different so that it can be a proper filename.
#
# usage: char *TBDateTimeFSSafe()
#
sub TBDateTimeFSSafe()
{
    return POSIX::strftime("20%y%m%d-%H.%M.%S", localtime());
312 313
}

314 315 316 317 318 319 320 321 322 323 324 325 326
#
# Print out a timestamp if the TIMESTAMPS configure variable was set.
# 
# usage: void TBDebugTimeStamp(@)
#
sub TBDebugTimeStamp(@)
{
    my @strings = @_;
    if ($TIMESTAMPS) {
	print "TIMESTAMP: ", TBTimeStamp(), " ", join("",@strings), "\n";
    }
}

327 328 329 330 331 332 333 334
#
# Turn on timestamps locally. We could do this globally by using an
# env variable to pass it along, but lets see if we need that.
# 
sub TBDebugTimeStampsOn()
{
    $TIMESTAMPS = 1;
}
335

336 337 338 339 340 341 342 343 344
#
# Put ourselves into the background, directing output to the log file.
# The caller provides the logfile name, which should have been created
# with mktemp, just to be safe. Returns the usual return of fork. 
#
# usage int TBBackGround(char *filename).
# 
sub TBBackGround($)
{
345
    my ($logname) = @_;
346

347 348 349 350
    my $mypid = fork();
    if ($mypid) {
	return $mypid;
    }
Leigh Stoller's avatar
Leigh Stoller committed
351 352
    select(undef, undef, undef, 0.2);
    
353 354 355 356 357 358 359 360
    #
    # We have to disconnect from the caller by redirecting both STDIN and
    # STDOUT away from the pipe. Otherwise the caller (the web server) will
    # continue to wait even though the parent has exited. 
    #
    open(STDIN, "< /dev/null") or
	die("opening /dev/null for STDIN: $!");

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    ReOpenLog($logname);

    #
    # Create a new session to ensure we are clear of any process group
    #
    POSIX::setsid() or
	die("setsid failed: $!");

    return 0;
}

#
# As for newsyslog. Call this on signal. newsyslog will have renamed the
# the original file already.
#
sub ReOpenLog($)
{
    my ($logname) = @_;
    
380 381 382
    # Note different taint check (allow /).
    if ($logname =~ /^([-\@\w.\/]+)$/) {
	$logname = $1;
383 384
    }
    else {
385 386 387 388 389 390
	die "Bad data in logfile name: $logname";
    }

    open(STDERR, ">> $logname") or die("opening $logname for STDERR: $!");
    open(STDOUT, ">> $logname") or die("opening $logname for STDOUT: $!");

391 392 393
    #
    # Turn off line buffering on output
    #
394 395 396 397
    select STDERR;
    $OUTPUT_AUTOFLUSH = 1;
    select STDOUT;
    $OUTPUT_AUTOFLUSH = 1;
398

399 400 401
    return 0;
}

402
#
403
# Create a temporary file, untaint the name, return it. 
404
#
405
sub TBMakeTempFile($)
406 407
{
    my($prefix) = @_;
408
    my $fname;
409
    
410
    $fname = `mktemp /tmp/${prefix}.XXXXXX`;
411

412 413
    if ($fname =~ /^([-\@\w\.\/]+)$/) {
	$fname = $1;
414 415
    }
    else {
416
	die("Bad data in filename: $fname");
417 418
    }

419 420 421 422 423 424 425 426 427
    return $fname;
}

# Ditto for a temporary file.
sub TBMakeLogname($)
{
    my ($prefix) = @_;

    return TBMakeTempFile($prefix);
428 429
}

430 431 432 433 434
#
# Get me a secret key!
#
sub TBGenSecretKey()
{
435 436
    my $key=`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
    chomp($key);
437 438 439
    return $key;
}

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
#
# Fork+exec a command and return its exit value.  This is similar to
# system(), but does not use a shell to invoke the command.  The function
# exits with the return value from wait().
#
# If the second optional param is passed and true, then
# a signal handler for TERM will be installed, and the
# child process will be sent a SIGTERM if this (the calling)
# process gets one. The handler exits with the exit status returned by 
# wait() after sending the signal.
#
sub TBForkCmd($;$) {
    my ($cmd, $dokill) = @_;

    my $childpid = fork();
        
    if ($childpid) {
        my $handler = sub {
            kill("TERM", $childpid);
            my $exstat = wait();
            print STDERR "*** $0:\n".
                "    Command terminated: $cmd.\n"; 
            exit($exstat);
        };
        local $SIG{TERM} = \&$handler if (defined($dokill) && $dokill);

        my $waitpid = wait();
        my $exitstatus = $?;
        if ($waitpid < 0) {
            die("*** $0:\n".
                "    Uh oh, wait() returned a negative number");
        }
        elsif ($waitpid != $childpid) {
            warn("*** $0:\n".
                "    pid returned by wait() != pid ".
                "from fork(): $waitpid $childpid");
        }
        return $exitstatus;
    }
    else {
        exec($cmd);
        die("*** $0:\n".
            "    exec of $cmd failed!\n");
    }

    # NOTREACHED
    return(0);
}

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
#
# Determine if a user-specified path falls within the standard
# user-accessible directories.
#
# If $userealpath is non-zero this will use the real filesystem path on the
# fileserver (e.g., /q/proj) rather than the conventional mount point (/proj).
# Obviously, this option should only be used when run on the fileserver.
#
sub TBValidUserDir($$;$$$)
{
    my ($path, $userealpath, $uid, $pid, $gid, $eid) = @_;
    my ($uroot, $proot, $groot, $sroot);

    #
    # Decide whether to test against the "real" (server-side) path
    # or the user-visible mount point.
    #
    if ($userealpath) {
	$uroot = $FSDIR_USER;
	$proot = $FSDIR_PROJ;
	$groot = $FSDIR_GROUPS;
	if ($FSDIR_SCRATCH) {
	    $sroot = $FSDIR_SCRATCH;
	}
    } else {
	$uroot = $USERROOT;
	$proot = $PROJROOT;
	$groot = $GROUPROOT;
	if ($FSDIR_SCRATCH) {
	    $sroot = $SCRATCHROOT;
	}
    }

    #
    # No ids specified, just make sure it starts with an appropriate prefix.
    #
    if (!$uid && !$pid && !$gid && !$eid) {
	if ($path =~ /^$proot\// ||
	    $path =~ /^$uroot\// ||
	    $path =~ /^$groot\//) {
	    return 1;
	}
	if (defined($sroot) && $path =~ /^$sroot\//) {
	    return 1;
	}

	return 0;
    }
    #
    # Otherwise check for specific directories based on:
    #
    #	$uid		/users/$uid
    #
    #	$pid		/proj/$pid,
    #			/scratch/$pid (if present)
    #
    #	$pid+$gid	/proj/$pid,
    #			/groups/$pid/$gid,
    #			/scratch/$pid (if present)
    #
    #	$pid+$eid	/proj/$pid/exp/$eid
    #
    #	$pid+$gid+$eid	/groups/$pid/$gid/exp/$eid
    #
    if ($uid) {
	if ($path =~ /^$uroot\/$uid\//) {
	    return 1;
	}
    }
    if ($pid) {
	if ($eid) {
	    if ($gid) {
		if ($path =~ /^$groot\/$pid\/$gid\/exp\/$eid\//) {
		    return 1;
		}
	    } else {
		if ($path =~ /^$proot\/$pid\/exp\/$eid\//) {
		    return 1;
		}
	    }
	} else {
	    if ($path =~ /^$proot\/$pid\//) {
		return 1;
	    }
	    if ($gid) {
		if ($path =~ /^$groot\/$pid\/$gid\//) {
		    return 1;
		}
	    }

	    #
	    # XXX /scratch is currently just per-project
	    #
	    if (defined($sroot)) {
		if ($path =~ /^$sroot\/$pid\//) {
		    return 1;
		}
	    }
	}
    }

    return 0;
}

#
# Return a list of valid directories based on the specified
# $uid, $pid, $gid, $eid.  Used for error messages.
#
sub TBValidUserDirList(;$$$$)
{
    my ($uid, $pid, $gid, $eid) = @_;
    my @dirs;

    if (!$uid && !$pid && !$gid && !$eid) {
	@dirs = ($USERROOT, $PROJROOT, $GROUPROOT);
	if ($FSDIR_SCRATCH) {
	    push(@dirs, $SCRATCHROOT);
	}
	return join(", ", @dirs);
    }

    if ($uid) {
	push(@dirs, "$USERROOT/$uid");
    }

    if ($pid) {
	if ($eid) {
	    if ($gid) {
		push(@dirs, "$GROUPROOT/$pid/$gid/exp/$eid");
	    } else {
		push(@dirs, "$PROJROOT/$pid/exp/$eid");
	    }
	} else {
	    push(@dirs, "$PROJROOT/$pid");
	    # don't confuse for $pid==$gid (/groups/$pid/$gid is /proj/$pid)
	    if ($gid && $gid ne $pid) {
		push(@dirs, "$GROUPROOT/$pid/$gid");
	    }

	    #
	    # XXX /scratch is currently just per-project
	    #
	    if ($FSDIR_SCRATCH) {
		push(@dirs, "$SCRATCHROOT/$pid");
	    }
	}
    }

    return @dirs;
}

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
#
# Serialize an operation (script).
#
my $lockname;
my $lockhandle;

# Return Values.
sub TBSCRIPTLOCK_OKAY()		{ 0;  }
sub TBSCRIPTLOCK_TIMEDOUT()	{ 1;  }
sub TBSCRIPTLOCK_IGNORE()	{ 2;  }
sub TBSCRIPTLOCK_FAILED()	{ -1; }

# 
# There are two kinds of serialization.
#
#   * Usual Kind: Each party just waits for a chance to go.
#   * Other Kind: Only the first party really needs to run; the others just
#                 need to wait. For example; exports_setup operates globally,
#                 so there is no reason to run it more then once. We just
#                 need to make sure that everyone waits for the one that is
#		  running to finish. Use the global option for this.
#
sub TBScriptLock($;$$)
{
    my ($token, $global, $waittime) = @_;
    local *LOCK;

667
    $waittime = 120
668 669 670 671 672
	if (!defined($waittime));
    $global = 0
	if (!defined($global));
    $lockname = "/var/tmp/testbed_${token}_lockfile";

673 674
    my $oldmask = umask(0000);

675 676
    if (! open(LOCK, ">>$lockname")) {
	print STDERR "Could not open $lockname!\n";
677
	umask($oldmask);
678 679
	return TBSCRIPTLOCK_FAILED();
    }
680
    umask($oldmask);
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 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 778 779

    if (! $global) {
	#
	# A plain old serial lock.
	#
	while (flock(LOCK, LOCK_EX|LOCK_NB) == 0) {
	    print "Another $token is in progress. Waiting a moment ...\n";

	    $waittime--;
	    if ($waittime == 0) {
		print STDERR "Could not get the lock after a long time!\n";
		return TBSCRIPTLOCK_TIMEDOUT();
	    }
	    sleep(1);
	}
	# Okay, got the lock. Save the handle. We need it below.
	$lockhandle = *LOCK;
	return TBSCRIPTLOCK_OKAY();
    }

    #
    # Okay, a global lock.
    #
    # If we don't get it the first time, we wait for:
    # 1) The lock to become free, in which case we do our thing
    # 2) The time on the lock to change, in which case we wait for that 
    #    process to finish, and then we are done since there is no
    #    reason to duplicate what the just finished process did.
    #
    if (flock(LOCK, LOCK_EX|LOCK_NB) == 0) {
	my $oldlocktime = (stat(LOCK))[9];
	my $gotlock = 0;
	
	while (1) {
	    print "Another $token in progress. Waiting a moment ...\n";
	    
	    if (flock(LOCK, LOCK_EX|LOCK_NB) != 0) {
		# OK, got the lock
		$gotlock = 1;
		last;
	    }
	    my $locktime = (stat(LOCK))[9];
	    if ($locktime != $oldlocktime) {
		$oldlocktime = $locktime;
		last;
	    }
	    
	    $waittime--;
	    if ($waittime <= 0) {
		print STDERR "Could not get the lock after a long time!\n";
		return TBSCRIPTLOCK_TIMEDOUT();
	    }
	    sleep(1);
	}

	$count = 0;
	#
	# If we did not get the lock, wait for the process that did to finish.
	#
	if (!$gotlock) {
	    while (1) {
		if ((stat(LOCK))[9] != $oldlocktime) {
		    return TBSCRIPTLOCK_IGNORE();
		}
		if (flock(LOCK, LOCK_EX|LOCK_NB) != 0) {
		    close(LOCK);
		    return TBSCRIPTLOCK_IGNORE();
		}

		$waittime--;
		if ($waittime <= 0) {
		    print STDERR
			"Process with the lock did not finish after ".
			"a long time!\n";
		    return TBSCRIPTLOCK_TIMEDOUT();
		}
		sleep(1); 
	    }
	}
    }
    #
    # Perl-style touch(1)
    #
    my $now = time;
    utime $now, $now, $lockname;
    
    $lockhandle = *LOCK;
    return TBSCRIPTLOCK_OKAY();
}

#
# Unlock; Just need to close the file (releasing the lock).
#
sub TBScriptUnlock()
{
    close($lockhandle)
	if defined($lockhandle);
}

780 781 782 783 784 785 786 787
#
# Get me a UUID (universally unique identifier). Its really nice that there
# is a program that does this! They look like this:
#
#	047edb7b-d346-11db-96cb-001143e453fe
#
sub NewUUID()
{
788
    my $uuid = `$UUIDGEN`;
789 790 791 792 793 794 795

    if ($uuid =~ /^(\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12})$/) {
	return $1;
    }
    return undef;
}

796 797 798 799 800
sub System($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
801
	if ($SYSTEM_DEBUG);
802 803 804 805 806 807 808 809

    TBDebugTimeStamp($command);
    my $retval = system($command);
    TBDebugTimeStamp("Done");

    return $retval;
}

810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
#
# Check for the existence of a pid file and see if that file is
# running. Mostly cause of devel tree versions.
#
sub CheckDaemonRunning($)
{
    my ($name) = @_;
    my $pidfile = "/var/run/${name}.pid";

    if (-e $pidfile) {
	my $opid = `cat $pidfile`;
	if ($opid =~ /^(\d*)$/) {
	    $opid = $1;
	}
	else {
	    print STDERR "$pidfile exists, but $opid is malformed\n";
	    return 1;
	}
	if (kill(0, $opid)) {
	    print STDERR "$pidfile exists, and process $opid is running\n";
	    return 1;
	}
	unlink($pidfile);
    }
    return 0;
}
#
# Mark a daemon as running.
#
sub MarkDaemonRunning($)
{
    my ($name) = @_;
    my $pidfile = "/var/run/${name}.pid";

    if (system("echo '$PID' > $pidfile")) {
	print STDERR "Could not create $pidfile\n";
	return -1;
    }
    return 0;
}
sub MarkDaemonStopped($)
{
    my ($name) = @_;
    my $pidfile = "/var/run/${name}.pid";

    unlink($pidfile);
    return 0;
}

859
1;