libtestbed.pm.in 20.9 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 41
	 SendProjAdminMail ReOpenLog
	 CheckDaemonRunning MarkDaemonRunning MarkDaemonStopped);
42

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return(*MAIL);
}

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

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

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

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

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 348 349 350 351 352 353 354
#
# 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;
}
355

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

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

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

411 412 413
    #
    # Turn off line buffering on output
    #
414 415 416 417
    select STDERR;
    $OUTPUT_AUTOFLUSH = 1;
    select STDOUT;
    $OUTPUT_AUTOFLUSH = 1;
418

419 420 421
    return 0;
}

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

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

439 440 441 442 443 444 445 446 447
    return $fname;
}

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

    return TBMakeTempFile($prefix);
448 449
}

450 451 452 453 454
#
# Get me a secret key!
#
sub TBGenSecretKey()
{
455
    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
456 457
    return undef
	if ($?);
458
    chomp($key);
459 460 461
    return $key;
}

Kirk Webb's avatar
 
Kirk Webb committed
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 506 507 508 509 510
#
# 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);
}

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
#
# 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;
	}
535 536 537 538 539 540 541
    } elsif ($WITHAMD) {
	$uroot = $AMDROOT/$USERROOT;
	$proot = $AMDROOT/$PROJROOT;
	$groot = $AMDROOT/$GROUPROOT;
	if ($FSDIR_SCRATCH) {
	    $sroot = $AMDROOT/$SCRATCHROOT;
	}
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 657 658 659 660 661 662 663 664 665 666 667 668
    } 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;
}

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

696
    $waittime = 120
697 698 699 700 701
	if (!defined($waittime));
    $global = 0
	if (!defined($global));
    $lockname = "/var/tmp/testbed_${token}_lockfile";

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

704 705
    if (! open(LOCK, ">>$lockname")) {
	print STDERR "Could not open $lockname!\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
706
	umask($oldmask);
707 708
	return TBSCRIPTLOCK_FAILED();
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
709
    umask($oldmask);
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 797 798 799 800 801 802 803 804 805 806 807 808

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

809 810 811 812 813 814 815 816
#
# 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
817
    my $uuid = `$UUIDGEN`;
818 819 820 821 822 823 824

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

825 826 827 828 829
sub System($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
830
	if ($SYSTEM_DEBUG);
831 832 833 834 835 836 837 838

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

    return $retval;
}

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 876 877 878 879 880 881 882 883 884 885 886 887
#
# 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;
}

888
1;