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

#
4
# Copyright (c) 2000-2014 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 B. Stoller's avatar
Leigh B. 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 TBDateStringGMT TBDateStringLocal
41
	 CheckDaemonRunning MarkDaemonRunning MarkDaemonStopped);
42

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

54
my $TB           = "@prefix@";
55 56 57 58 59
my $BOSSNODE	 = "@BOSSNODE@";
my $TIMESTAMPS	 = "@TIMESTAMPS@";
my $TBOPSEMAIL	 = "@TBOPSEMAIL@";
my $TBWWWEMAIL	 = "@TBWWWEMAIL@";
my $TBAUDITEMAIL = "@TBAUDITEMAIL@";
Mike Hibler's avatar
Mike Hibler committed
60
my $UUIDGEN	 = "@UUIDGEN@";
61
my $NOREPLY      = "no-reply\@@OURDOMAIN@";
62
my $SCRIPTNAME	 = "Unknown";
63

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

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

72 73 74 75 76 77 78 79 80
#
# 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@";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return(*MAIL);
}

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

308 309 310 311 312 313 314
#
# Return a timestamp. We don't care about day/date/year. Just the time mam.
# 
# TBTimeStamp()
#
sub TBTimeStamp()
{
315 316 317
    my ($seconds, $microseconds) = gettimeofday();
    
    return POSIX::strftime("%H:%M:%S", localtime($seconds)) . ":$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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
# Convert date to GMT
sub TBDateStringGMT($)
{
    my ($date) = @_;

    return ""
	if (!defined($date) || "$date" eq "");

    if ($date !~ /^\d$/) {
	$date = str2time($date);
    }
    return POSIX::strftime("20%y-%m-%dT%H:%M:%SZ", gmtime($date));
}
# Convert date to Local
sub TBDateStringLocal($)
{
    my ($date) = @_;

    return ""
	if (!defined($date) || "$date" eq "");

    if ($date !~ /^\d*$/) {
	$date = timelocal(strptime($date));
    }
    return POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime($date));
}

363 364 365 366 367 368 369 370 371 372 373 374 375
#
# 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";
    }
}

376 377 378 379 380 381 382 383
#
# 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;
}
384

385 386 387 388 389 390 391 392 393
#
# 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($)
{
394
    my ($logname) = @_;
395

396 397 398 399
    my $mypid = fork();
    if ($mypid) {
	return $mypid;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
400 401
    select(undef, undef, undef, 0.2);
    
402 403 404 405 406 407 408 409
    #
    # 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: $!");

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    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) = @_;
    
429 430 431
    # Note different taint check (allow /).
    if ($logname =~ /^([-\@\w.\/]+)$/) {
	$logname = $1;
432 433
    }
    else {
434 435 436 437 438 439
	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: $!");

440 441 442
    #
    # Turn off line buffering on output
    #
443 444 445 446
    select STDERR;
    $OUTPUT_AUTOFLUSH = 1;
    select STDOUT;
    $OUTPUT_AUTOFLUSH = 1;
447

448 449 450
    return 0;
}

451
#
452
# Create a temporary file, untaint the name, return it. 
453
#
454
sub TBMakeTempFile($)
455 456
{
    my($prefix) = @_;
457
    my $fname;
458
    
459
    $fname = `/usr/bin/mktemp /tmp/${prefix}.XXXXXX`;
460

461 462
    if ($fname =~ /^([-\@\w\.\/]+)$/) {
	$fname = $1;
463 464
    }
    else {
465
	die("Bad data in filename: $fname");
466 467
    }

468 469 470 471 472 473 474 475 476
    return $fname;
}

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

    return TBMakeTempFile($prefix);
477 478
}

479 480 481 482 483
#
# Get me a secret key!
#
sub TBGenSecretKey()
{
484
    my $key=`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
Leigh B Stoller's avatar
Leigh B Stoller committed
485 486
    return undef
	if ($?);
487
    chomp($key);
488 489 490
    return $key;
}

Kirk Webb's avatar
 
Kirk Webb committed
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
#
# 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);
}

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
#
# 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;
	}
564
    } elsif ($WITHAMD) {
565 566 567
	$uroot = "${AMDROOT}$USERROOT";
	$proot = "${AMDROOT}$PROJROOT";
	$groot = "${AMDROOT}$GROUPROOT";
568
	if ($FSDIR_SCRATCH) {
569
	    $sroot = "${AMDROOT}$SCRATCHROOT";
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 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    } 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;
}

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

725
    $waittime = 120
726 727 728 729 730
	if (!defined($waittime));
    $global = 0
	if (!defined($global));
    $lockname = "/var/tmp/testbed_${token}_lockfile";

Leigh B. Stoller's avatar
Leigh B. Stoller committed
731 732
    my $oldmask = umask(0000);

733 734
    if (! open(LOCK, ">>$lockname")) {
	print STDERR "Could not open $lockname!\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
735
	umask($oldmask);
736 737
	return TBSCRIPTLOCK_FAILED();
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
738
    umask($oldmask);
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 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

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

838 839 840 841 842 843 844 845
#
# 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()
{
Mike Hibler's avatar
Mike Hibler committed
846
    my $uuid = `$UUIDGEN`;
847 848 849 850 851 852 853

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

854 855 856 857 858
sub System($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
859
	if ($SYSTEM_DEBUG);
860 861 862 863 864 865 866 867

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

    return $retval;
}

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 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
#
# 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;
}

917
1;