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

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

9 10 11 12 13
package libtestbed;
use Exporter;

@ISA = "Exporter";
@EXPORT =
14
    qw ( SENDMAIL OPENMAIL TBTimeStamp TBBackGround TBDateTimeFSSafe
15
	 TBMakeLogname TB_BOSSNODE TB_OPSEMAIL TBGenSecretKey TBDebugTimeStamp
16
	 TBDebugTimeStampsOn TBForkCmd TB_BOSSEVENTPORT TB_EVENTSERVER
17
	 TBScriptLock TBScriptUnlock TBTimeStampWithDate
18 19
	 TBSCRIPTLOCK_OKAY TBSCRIPTLOCK_TIMEDOUT
	 TBSCRIPTLOCK_IGNORE TBSCRIPTLOCK_FAILED);
20

21 22 23 24 25
# After package decl.
use English;
use POSIX qw(strftime);
use POSIX qw(setsid);
use Fcntl;
26
use Fcntl ':flock';
27 28
use IO::Handle;
use File::Basename;
29
use Time::HiRes qw(gettimeofday);
30

31 32
#my $MAILTAG  = "@OURDOMAIN@";
my $MAILTAG  = "@THISHOMEBASE@";
33
my $BOSSNODE = "@BOSSNODE@";
34
my $TIMESTAMPS = "@TIMESTAMPS@";
35
my $TBOPSEMAIL = "@TBOPSEMAIL@";
36
my $SCRIPTNAME = "Unknown";
37 38 39

# Hostname of our boss node
sub TB_BOSSNODE()	{ $BOSSNODE; }
40

41 42 43
# Testbed ops email address
sub TB_OPSEMAIL()	{ $TBOPSEMAIL; }

44 45
# This is for the swigged event library which includes this file.
sub TB_BOSSEVENTPORT()  { "@BOSSEVENTPORT@"; }
46
sub TB_EVENTSERVER()    { "@EVENTSERVER@" . "." . "@OURDOMAIN@"; }
47

48 49 50 51 52 53 54 55
# Untainted scriptname for email below.
if ($PROGRAM_NAME =~ /^([-\w\.\/]+)$/) {
    $SCRIPTNAME = basename($1);
}
else {
    $SCRIPTNAME = "Tainted";
}

56 57 58 59 60 61
#
# Turn off line buffering on output
#
STDOUT->autoflush(1);
STDERR->autoflush(1);

62 63 64 65 66 67 68 69
# A library of useful stuff.

# 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!).
#
Leigh Stoller's avatar
Leigh Stoller committed
70
# SENDMAIL(To, Subject, Message, [From], [More Headers], [files to append])
71
#
Leigh Stoller's avatar
Leigh Stoller committed
72
sub SENDMAIL($$$;$$@)
73
{
74
    my($To, $Subject, $Message, $From, $Headers, @Files) = @_;
75
    my $tag = uc($MAILTAG);
76

77 78 79 80 81 82 83
    #
    # Untaint the path locally
    # 
    local %ENV = %ENV;
    $ENV{PATH} = "/bin:/usr/bin";
    delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

84 85 86 87 88 89 90 91 92 93 94
    if (! open(MAIL, "|/usr/sbin/sendmail -t")) {
	print STDERR "SENDMAIL: Could not start sendmail: $!\n";
	return 0;
    }

    #
    # Sendmail will figure this out if not given.
    # 
    if (defined($From) && $From) {
	print MAIL "From: $From\n";
    }
95
    if (defined($Headers) && length($Headers) > 0) {
96 97
	print MAIL "$Headers\n";
    }
98
    print MAIL "X-NetBed: $SCRIPTNAME\n";
99 100
    print MAIL "To: $To\n";
    print MAIL "Subject: $tag: $Subject\n";
101 102
    print MAIL "\n";
    print MAIL "$Message\n";
Leigh Stoller's avatar
Leigh Stoller committed
103 104
    print MAIL "\n";

105
    if (@Files) {
Leigh Stoller's avatar
Leigh Stoller committed
106 107
	foreach my $file ( @Files ) {
	    if (open(IN, "$file")) {
108
		print MAIL "\n--------- $file --------\n";
Leigh Stoller's avatar
Leigh Stoller committed
109 110 111 112 113 114 115 116 117

		while (<IN>) {
		    print MAIL "$_";
		}
		close(IN);
	    }
	}
    }
    
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    print MAIL "\n";
    if (! close(MAIL)) {
	print STDERR "SENDMAIL: Could not finish sendmail: $!\n";
	return 0;
    }
    return 1;
}

#
# 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";
149
    print MAIL "Subject: $tag: $Subject\n";
150 151 152
    if (defined($Headers)) {
	print MAIL "$Headers\n";
    }
153
    print MAIL "X-NetBed: $SCRIPTNAME\n";
154 155 156 157 158
    print MAIL "\n";

    return(*MAIL);
}

159 160 161 162 163 164 165
#
# Return a timestamp. We don't care about day/date/year. Just the time mam.
# 
# TBTimeStamp()
#
sub TBTimeStamp()
{
166 167 168
    my ($seconds, $microseconds) = gettimeofday();
    
    return POSIX::strftime("%H:%M:%S", localtime($seconds)) . ":$microseconds";
169 170
}

171 172 173 174 175
sub TBTimeStampWithDate()
{
    return POSIX::strftime("%m/%d/20%y %H:%M:%S", localtime());
}

176 177 178 179 180 181 182 183 184
#
# 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());
185 186
}

187 188 189 190 191 192 193 194 195 196 197 198 199
#
# 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";
    }
}

200 201 202 203 204 205 206 207
#
# 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;
}
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
#
# 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($)
{
    my($logname) = @_;
    
    my $mypid = fork();
    if ($mypid) {
	return $mypid;
    }
Leigh Stoller's avatar
Leigh Stoller committed
224 225
    select(undef, undef, undef, 0.2);
    
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    #
    # 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: $!");

    # Note different taint check (allow /).
    if ($logname =~ /^([-\@\w.\/]+)$/) {
	$logname = $1;
    } else {
	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: $!");

244 245 246 247 248 249
    #
    # Turn off line buffering on output
    #
    STDOUT->autoflush(1);
    STDERR->autoflush(1);

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

256 257 258
    return 0;
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
#
# Create a logname and untaint it!
#
sub TBMakeLogname($)
{
    my($prefix) = @_;
    my $logname;
    
    $logname = `mktemp /tmp/${prefix}.XXXXXX`;

    if ($logname =~ /^([-\@\w\.\/]+)$/) {
	$logname = $1;
    }
    else {
	die("Bad data in logfile name: $logname");
    }

    return $logname;
}

279 280 281 282 283
#
# Get me a secret key!
#
sub TBGenSecretKey()
{
284 285
    my $key=`/bin/dd if=/dev/urandom count=128 bs=1 2> /dev/null | /sbin/md5`;
    chomp($key);
286 287 288
    return $key;
}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
#
# 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);
}

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 363 364 365 366 367 368 369 370
#
# 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;

    $waittime = 30
	if (!defined($waittime));
    $global = 0
	if (!defined($global));
    $lockname = "/var/tmp/testbed_${token}_lockfile";

371 372
    my $oldmask = umask(0000);

373 374
    if (! open(LOCK, ">>$lockname")) {
	print STDERR "Could not open $lockname!\n";
375
	umask($oldmask);
376 377
	return TBSCRIPTLOCK_FAILED();
    }
378
    umask($oldmask);
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

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

478
1;