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

#
4
# Copyright (c) 2000-2010 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
# 
# {{{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/>.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
24 25
#

26 27 28 29 30
package libtestbed;
use Exporter;

@ISA = "Exporter";
@EXPORT =
31
    qw ( SENDMAIL AnonSENDMAIL OPENMAIL TBTimeStamp TBBackGround TBDateTimeFSSafe
32 33
	 TBMakeLogname TB_BOSSNODE TB_OPSEMAIL TB_WWWEMAIL TB_AUDITEMAIL
	 TBMAIL_OPS TBMAIL_WWW TBMAIL_AUDIT TBGenSecretKey TBDebugTimeStamp
34
	 TBDebugTimeStampsOn TBForkCmd TB_BOSSEVENTPORT TB_EVENTSERVER
35
	 TBScriptLock TBScriptUnlock TBTimeStampWithDate
36
	 TBSCRIPTLOCK_OKAY TBSCRIPTLOCK_TIMEDOUT
37 38
	 TBSCRIPTLOCK_IGNORE TBSCRIPTLOCK_FAILED
	 PROJROOT GROUPROOT USERROOT SCRATCHROOT SHAREROOT
39
	 TBValidUserDir TBValidUserDirList TBMakeTempFile NewUUID System
40 41
	 SendProjAdminMail ReOpenLog
	 CheckDaemonRunning MarkDaemonRunning MarkDaemonStopped);
42 43 44
@EXPORT_OK =
    qw ( TBMAIL_PROJADMIN);

45

46 47 48 49 50
# After package decl.
use English;
use POSIX qw(strftime);
use POSIX qw(setsid);
use Fcntl;
51
use Fcntl ':flock';
52
use File::Basename;
53
use Time::HiRes qw(gettimeofday);
54
use vars qw(@EXPORT_OK);
55

56
my $TB           = "@prefix@";
57 58 59 60 61 62 63
#my $MAILTAG	 = "@OURDOMAIN@";
my $MAILTAG	 = "@THISHOMEBASE@";
my $BOSSNODE	 = "@BOSSNODE@";
my $TIMESTAMPS	 = "@TIMESTAMPS@";
my $TBOPSEMAIL	 = "@TBOPSEMAIL@";
my $TBWWWEMAIL	 = "@TBWWWEMAIL@";
my $TBAUDITEMAIL = "@TBAUDITEMAIL@";
64
my $UUIDGEN	 = "@UUIDGEN@";
65
my $NOREPLY      = "no-reply\@@OURDOMAIN@";
66
my $SCRIPTNAME	 = "Unknown";
67

68 69 70 71
# Exported.
$SYSTEM_DEBUG = 0;
@EXPORT_OK    = qw($SYSTEM_DEBUG);

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
#
# 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 : ""; }

97 98
# Hostname of our boss node
sub TB_BOSSNODE()	{ $BOSSNODE; }
99

100 101 102 103 104 105 106
# 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>" }
107

108 109 110 111 112
# TBMAIL_PROJADMIN should, in general, not be used directly, use
# SendProjAdminMail
sub TBMAIL_PROJADMIN($) {
    @MAILMANSUPPORT@ ? "$_[0]-admin\@@OURDOMAIN@" : "@TBAPPROVALEMAIL@";
}
113 114 115
sub TBMAIL_APPROVAL() {
    "@TBAPPROVALEMAIL@";
}
116

117 118
# This is for the swigged event library which includes this file.
sub TB_BOSSEVENTPORT()  { "@BOSSEVENTPORT@"; }
119
sub TB_EVENTSERVER()    { "@EVENTSERVER@" . "." . "@OURDOMAIN@"; }
120

121 122 123
# Untainted scriptname for email below.
if ($PROGRAM_NAME =~ /^([-\w\.\/]+)$/) {
    $SCRIPTNAME = basename($1);
124
    $PROGRAM_NAME = $SCRIPTNAME;
125 126 127 128 129
}
else {
    $SCRIPTNAME = "Tainted";
}

130 131 132
#
# Turn off line buffering on output
#
133 134 135 136
select STDERR;
$OUTPUT_AUTOFLUSH = 1;
select STDOUT;
$OUTPUT_AUTOFLUSH = 1;
137 138 139 140 141 142 143

# 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!).
#
144 145 146
# 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
147
#
148 149 150 151 152 153 154 155 156
sub SENDMAILWith($$$$;$$@);

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

sub AnonSENDMAIL($$$;$$@)
157
{
158
    my($To, $Subject, $Message, $From, $Headers, @Files) = @_;
159 160 161 162 163 164 165 166 167 168 169 170 171
    $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) = @_;
172
    my $tag = uc($MAILTAG);
173

174
    #
175
    # Untaint the path locally. Note that using a "local" fails on older perl!
176
    # 
177 178
    my $SAVE_PATH = $ENV{'PATH'};
    $ENV{'PATH'} = "/bin:/usr/bin";
179 180
    delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

181
    if (! open(MAIL, "| $Command")) {
182
	print STDERR "SENDMAIL: Could not start sendmail: $!\n";
183
	goto bad;
184 185 186 187 188 189 190 191
    }

    #
    # Sendmail will figure this out if not given.
    # 
    if (defined($From) && $From) {
	print MAIL "From: $From\n";
    }
192
    if (defined($Headers) && length($Headers) > 0) {
193 194
	print MAIL "$Headers\n";
    }
195
    print MAIL "X-NetBed: $SCRIPTNAME\n";
196 197 198
    if (defined($To)) {
	print MAIL "To: $To\n";
    }
199
    print MAIL "Subject: $tag: $Subject\n";
200 201
    print MAIL "\n";
    print MAIL "$Message\n";
Leigh Stoller's avatar
Leigh Stoller committed
202 203
    print MAIL "\n";

204
    if (@Files) {
Leigh Stoller's avatar
Leigh Stoller committed
205
	foreach my $file ( @Files ) {
206
	    if (defined($file) && open(IN, "$file")) {
207
		print MAIL "\n--------- $file --------\n";
Leigh Stoller's avatar
Leigh Stoller committed
208 209 210 211 212 213 214 215 216

		while (<IN>) {
		    print MAIL "$_";
		}
		close(IN);
	    }
	}
    }
    
217 218 219
    print MAIL "\n";
    if (! close(MAIL)) {
	print STDERR "SENDMAIL: Could not finish sendmail: $!\n";
220
	goto bad;
221
    }
222
    $ENV{'PATH'} = $SAVE_PATH;
223
    return 1;
224 225

  bad:
226
    $ENV{'PATH'} = $SAVE_PATH;
227
    return 0;
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
}

#
# 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";
253
    print MAIL "Subject: $tag: $Subject\n";
254 255 256
    if (defined($Headers)) {
	print MAIL "$Headers\n";
    }
257
    print MAIL "X-NetBed: $SCRIPTNAME\n";
258 259 260 261 262
    print MAIL "\n";

    return(*MAIL);
}

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
#
# 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;
282 283 284 285 286
	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";
	}
287 288 289 290 291 292 293 294 295 296 297 298 299
	$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;
300
    AnonSENDMAIL($to, $subject, $message, $from, $headers);
301 302
}

303 304 305 306 307 308 309
#
# Return a timestamp. We don't care about day/date/year. Just the time mam.
# 
# TBTimeStamp()
#
sub TBTimeStamp()
{
310 311 312
    my ($seconds, $microseconds) = gettimeofday();
    
    return POSIX::strftime("%H:%M:%S", localtime($seconds)) . ":$microseconds";
313 314
}

315 316 317 318 319
sub TBTimeStampWithDate()
{
    return POSIX::strftime("%m/%d/20%y %H:%M:%S", localtime());
}

320 321 322 323 324 325 326 327 328
#
# 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());
329 330
}

331 332 333 334 335 336 337 338 339 340 341 342 343
#
# 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";
    }
}

344 345 346 347 348 349 350 351
#
# 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;
}
352

353 354 355 356 357 358 359 360 361
#
# 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($)
{
362
    my ($logname) = @_;
363

364 365 366 367
    my $mypid = fork();
    if ($mypid) {
	return $mypid;
    }
Leigh Stoller's avatar
Leigh Stoller committed
368 369
    select(undef, undef, undef, 0.2);
    
370 371 372 373 374 375 376 377
    #
    # 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: $!");

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    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) = @_;
    
397 398 399
    # Note different taint check (allow /).
    if ($logname =~ /^([-\@\w.\/]+)$/) {
	$logname = $1;
400 401
    }
    else {
402 403 404 405 406 407
	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: $!");

408 409 410
    #
    # Turn off line buffering on output
    #
411 412 413 414
    select STDERR;
    $OUTPUT_AUTOFLUSH = 1;
    select STDOUT;
    $OUTPUT_AUTOFLUSH = 1;
415

416 417 418
    return 0;
}

419
#
420
# Create a temporary file, untaint the name, return it. 
421
#
422
sub TBMakeTempFile($)
423 424
{
    my($prefix) = @_;
425
    my $fname;
426
    
427
    $fname = `mktemp /tmp/${prefix}.XXXXXX`;
428

429 430
    if ($fname =~ /^([-\@\w\.\/]+)$/) {
	$fname = $1;
431 432
    }
    else {
433
	die("Bad data in filename: $fname");
434 435
    }

436 437 438 439 440 441 442 443 444
    return $fname;
}

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

    return TBMakeTempFile($prefix);
445 446
}

447 448 449 450 451
#
# Get me a secret key!
#
sub TBGenSecretKey()
{
452 453
    my $key=`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
    chomp($key);
454 455 456
    return $key;
}

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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
#
# 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);
}

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 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
#
# 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;
}

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
#
# 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;

684
    $waittime = 120
685 686 687 688 689
	if (!defined($waittime));
    $global = 0
	if (!defined($global));
    $lockname = "/var/tmp/testbed_${token}_lockfile";

690 691
    my $oldmask = umask(0000);

692 693
    if (! open(LOCK, ">>$lockname")) {
	print STDERR "Could not open $lockname!\n";
694
	umask($oldmask);
695 696
	return TBSCRIPTLOCK_FAILED();
    }
697
    umask($oldmask);
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 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796

    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);
}

797 798 799 800 801 802 803 804
#
# 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()
{
805
    my $uuid = `$UUIDGEN`;
806 807 808 809 810 811 812

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

813 814 815 816 817
sub System($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
818
	if ($SYSTEM_DEBUG);
819 820 821 822 823 824 825 826

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

    return $retval;
}

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 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
#
# 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;
}

876
1;