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

#
4
# Copyright (c) 2000-2018 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
	 SendProjAdminMail ReOpenLog 
41
	 CheckDaemonRunning MarkDaemonRunning MarkDaemonStopped);
42

43 44 45 46
# After package decl.
use English;
use POSIX qw(strftime);
use POSIX qw(setsid);
47
use Time::Local;
48
use Fcntl;
49
use Fcntl ':flock';
50
use File::Basename;
51
use Time::HiRes qw(gettimeofday);
52

53
my $TB           = "@prefix@";
54 55 56 57 58
my $BOSSNODE	 = "@BOSSNODE@";
my $TIMESTAMPS	 = "@TIMESTAMPS@";
my $TBOPSEMAIL	 = "@TBOPSEMAIL@";
my $TBWWWEMAIL	 = "@TBWWWEMAIL@";
my $TBAUDITEMAIL = "@TBAUDITEMAIL@";
59
my $UUIDGEN	 = "@UUIDGEN@";
60
my $NOREPLY      = "no-reply\@@OURDOMAIN@";
61
my $SCRIPTNAME	 = "Unknown";
62

63 64 65 66
# So we can localize this variable.
use vars qw($MAILTAG);
$MAILTAG	 = "@THISHOMEBASE@";

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

71 72 73 74 75 76 77 78 79
#
# If AMD is used on boss (currently, only if ZFS is used to
# provide per-user and per-project filesystems), then we have to
# account for the AMD mount point (e.g., "/.amd_mnt") when determining
# if a path is valid or not.
#
my $WITHAMD	 = "@WITHAMD@";
my $AMDROOT	 = "@AMD_ROOT@";

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
#
# 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 : ""; }

105 106
# Hostname of our boss node
sub TB_BOSSNODE()	{ $BOSSNODE; }
107

108 109 110 111 112 113 114
# 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>" }
115 116 117
sub TBMAIL_APPROVAL() {
    "@TBAPPROVALEMAIL@";
}
118

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

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

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

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

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

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

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

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

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

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

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

  bad:
228
    $ENV{'PATH'} = $SAVE_PATH;
229
    return 0;
230 231 232 233 234 235 236 237 238 239 240 241
}

#
# 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;
242
    my $tag = uc($MAILTAG);
243

244
    if (! open(MAIL, "|/usr/sbin/sendmail -i -t")) {
245 246 247 248 249 250 251 252 253 254 255
	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";
256
    print MAIL "Subject: $tag: $Subject\n";
257 258 259
    if (defined($Headers)) {
	print MAIL "$Headers\n";
    }
260
    print MAIL "X-NetBed: $SCRIPTNAME\n";
261 262 263 264 265
    print MAIL "\n";

    return(*MAIL);
}

266 267 268 269 270 271 272 273 274 275 276
#
# 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($$$$$;$)
{
277 278 279
    my ($project, $from, $to, $subject, $message, $headers) = @_;
    my $projadminmail = $project->ApprovalEmailAddress();
    local $MAILTAG = $project->EmailTag();
280 281 282 283 284 285
    $headers .= "\n" if defined $headers;
    if ($from eq 'ADMIN') {
	$from = $projadminmail;
	$headers .= "Bcc: $projadminmail\n"; 
   } elsif ($to eq 'ADMIN') {
	$to = $projadminmail;
286 287 288 289 290
	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";
	}
291 292 293 294 295 296 297 298 299 300 301 302 303
	$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;
304
    AnonSENDMAIL($to, $subject, $message, $from, $headers);
305 306
}

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

320 321 322 323 324
sub TBTimeStampWithDate()
{
    return POSIX::strftime("%m/%d/20%y %H:%M:%S", localtime());
}

325 326 327 328 329 330 331 332 333
#
# 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());
334 335
}

336 337 338 339 340 341 342 343 344 345 346
#
# 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";
    }
347
    return 0;
348 349
}

350 351 352 353 354 355 356 357
#
# 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;
}
358

359 360 361 362 363 364 365 366 367
#
# 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($)
{
368
    my ($logname) = @_;
369

370 371 372 373
    my $mypid = fork();
    if ($mypid) {
	return $mypid;
    }
Leigh Stoller's avatar
Leigh Stoller committed
374 375
    select(undef, undef, undef, 0.2);
    
376 377 378 379 380 381 382 383
    #
    # 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: $!");

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

414 415 416
    #
    # Turn off line buffering on output
    #
417 418 419 420
    select STDERR;
    $OUTPUT_AUTOFLUSH = 1;
    select STDOUT;
    $OUTPUT_AUTOFLUSH = 1;
421

422 423 424
    return 0;
}

425
#
426
# Create a temporary file, untaint the name, return it. 
427
#
428
sub TBMakeTempFile($)
429 430
{
    my($prefix) = @_;
431
    my $fname;
Leigh Stoller's avatar
Leigh Stoller committed
432 433 434 435 436

    # Dumb and Dumber.
    if ($prefix =~ /^(.*)$/) {
	$prefix = $1;
    }
437
    $fname = `/usr/bin/mktemp /tmp/${prefix}.XXXXXX`;
438

439 440
    if ($fname =~ /^([-\@\w\.\/]+)$/) {
	$fname = $1;
441 442
    }
    else {
443
	die("Bad data in filename: $fname");
444 445
    }

446 447 448 449 450 451 452 453 454
    return $fname;
}

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

    return TBMakeTempFile($prefix);
455 456
}

457 458 459 460 461
#
# Get me a secret key!
#
sub TBGenSecretKey()
{
462
    my $key=`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
Leigh Stoller's avatar
Leigh Stoller committed
463 464
    return undef
	if ($?);
465 466 467 468
    # Silly taint check for caller.
    if ($key =~ /^(.*)$/) {
	$key = $1;
    }
469 470 471
    return $key;
}

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 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
#
# 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);
}

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
#
# 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;
	}
545
    } elsif ($WITHAMD) {
546 547 548
	$uroot = "${AMDROOT}$USERROOT";
	$proot = "${AMDROOT}$PROJROOT";
	$groot = "${AMDROOT}$GROUPROOT";
549
	if ($FSDIR_SCRATCH) {
550
	    $sroot = "${AMDROOT}$SCRATCHROOT";
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 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    } 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;
}

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

706
    $waittime = 120
707 708 709 710 711
	if (!defined($waittime));
    $global = 0
	if (!defined($global));
    $lockname = "/var/tmp/testbed_${token}_lockfile";

712 713
    my $oldmask = umask(0000);

714 715
    if (! open(LOCK, ">>$lockname")) {
	print STDERR "Could not open $lockname!\n";
716
	umask($oldmask);
717 718
	return TBSCRIPTLOCK_FAILED();
    }
719
    umask($oldmask);
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 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818

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

819 820 821 822 823 824 825 826
#
# 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()
{
827
    my $uuid = `$UUIDGEN`;
828 829 830 831 832 833 834

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

835 836 837 838 839
sub System($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
840
	if ($SYSTEM_DEBUG);
841 842 843 844 845 846 847 848

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

    return $retval;
}

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 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
#
# 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;
}

898
1;