batch_daemon.in 19.8 KB
Newer Older
1
#!/usr/bin/perl -wT
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
use English;
use Getopt::Std;
11 12
use Fcntl;
use IO::Handle;
13 14 15 16 17 18

#
# Create a batch experiment.
#
# usage: batch_daemon
#
Leigh Stoller's avatar
Leigh Stoller committed
19 20
# TODO: Use "logger" instead of writing a log file.
#
21 22
sub usage()
{
23 24
    print STDOUT "Usage: batch_daemon [-d]\n" .
	"Use the -d option to prevent daemonization\n";
25 26
    exit(-1);
}
27 28 29 30 31

sub dosomething($$);
sub isexpdone($);
sub TBBatchUnLockExp($$;$);

32
my  $optlist = "d";
33 34 35 36 37 38 39

#
# Configure variables
#
my $TB       = "@prefix@";
my $DBNAME   = "@TBDBNAME@";
my $TBOPS    = "@TBOPSEMAIL@";
40
my $TBLOGS   = "@TBLOGSEMAIL@";
41

42 43 44 45 46 47 48 49
#
# Only root can run this script.
#
if ($UID) {
    die("*** $0:\n".
	"    Only root can run this script!\n");
}

50 51 52 53 54 55
#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
56
use Template;
57
use Experiment;
58

59 60
# Be careful not to exit on transient error; 0 means infinite retry.
$libdb::DBQUERY_MAXTRIES = 0;
61

62
my $tbbindir = "$TB/bin/";
63
my $swapexp  = "$TB/bin/swapexp";
64
my $endexp   = "$TB/bin/endexp";
65
my $savelogs = "$TB/bin/savelogs";
66
my $avail    = "$TB/sbin/avail";
67
my $batchlog = "$TB/log/batchlog";
68
my $debug    = 0;
69

70 71 72
# New template stuff.
my $template_swapout  = "$TB/bin/template_swapout";

73 74 75 76 77 78 79
my $BSTATE_POSTED	= EXPTSTATE_QUEUED;
my $BSTATE_ACTIVATING	= EXPTSTATE_ACTIVATING;
my $BSTATE_RUNNING	= EXPTSTATE_ACTIVE;
my $BSTATE_TERMINATING	= EXPTSTATE_TERMINATING;
my $BSTATE_PAUSED	= EXPTSTATE_SWAPPED;
my $BSTATE_LOCKED       = BATCHSTATE_LOCKED;
my $BSTATE_UNLOCKED     = BATCHSTATE_UNLOCKED;
80
my $TBOPSPID            = TBOPSPID;
81

82 83 84 85 86 87
#
# These are valid in the children, not the parent. I suppose I could use
# dynamically scoped variables, but hardly worth it.
#
my $eid;
my $pid;
Leigh Stoller's avatar
Leigh Stoller committed
88
my $gid;
89
my $logname;
90
my $nsfile;
91 92
my $userdir;
my $workdir;
93
my $user_name  = "Testbed Operations";
94
my $user_email = "$TBOPS";
95
my $template;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

#
# Turn off line buffering on output
#
$| = 1;

#
# Untaint the path
# 
$ENV{'PATH'} = "/bin:/usr/bin:";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 0) {
    usage();
}
119
if (defined($options{"d"})) {
120
    $debug = 1;
121
}
122 123

# Go to ground.
124
if (! $debug) {
125 126 127
    if (TBBackGround($batchlog)) {
	exit(0);
    }
128
}
129 130 131 132 133

#
# Loop, looking for batch experiments that want to run.
# 
while (1) {
134
    my($count, $i, $query_result, $pending_result, $running_result);
135
    my(%pending_row);
136
    my $retry_wait = 60;
137
    my $disabled;
138

139 140 141 142 143 144 145 146 147
    if (! TBGetSiteVar("web/nologins", \$disabled)) {
	print "Error getting sitevar 'web/nologins'. Waiting a bit ...\n";
	goto pause;
    }
    if ($disabled) {
	print "Web interface is disabled; waiting a bit ...\n";
	sleep(60);
	goto pause;
    }
148 149 150 151
    if (! TBGetSiteVar("batch/retry_wait", \$retry_wait)) {
	print "Error getting sitevar 'batch/retry_wait'. Waiting a bit ...\n";
	goto pause;
    }
152 153 154
    # Do not allow zero!
    $retry_wait = 60
	if ($retry_wait == 0);
Leigh Stoller's avatar
Leigh Stoller committed
155

156
    #
157
    # Need to lock the table here because of cancelation in endexp.
158 159 160 161 162 163
    # See the comments in there. We need to atomically grab the next
    # batch experiment we want to try, and then change its state from
    # new to configuring. We want to grab just one experiment, since
    # it takes a while to configure an experiment, and grabbing a bunch and
    # locking them up might result in having to wait a really long time
    # to cancel a batch experiment that hasn't really tried to start yet!
164
    # Thats would ne annoying to users.
165
    #
166
    # So, now you're wondering what my selection criteria is? Well, its
167 168
    # damn simplistic. I set the "started" datetime field each attempt,
    # and I pick the batch_experiment with the oldest time, thereby cycling
169 170 171 172
    # through in a "least recently attempted" manner. In addition, we want
    # to throttle the number simultaneous batches that one person can
    # can have running at a time (curently to just one batch), so check to
    # to see if the person has another batch active (thats e2 below).
173 174
    #
    $query_result =
175 176
	DBQuery("lock tables experiments write, experiments as e1 write, ".
		"experiments as e2 write");
177 178
    if (! $query_result) {
	print "DB Error locking tables. Waiting a bit ...\n";
Leigh Stoller's avatar
Leigh Stoller committed
179
	goto pause;
180 181 182
    }
    
    $pending_result =
183 184 185
	DBQueryWarn("SELECT e1.* FROM experiments as e1 ".
		    "left join experiments as e2 on ".
		    " e2.expt_head_uid=e1.expt_head_uid and ".
186
		    " e2.batchmode=1 and e2.state='$BSTATE_RUNNING' and ".
187 188
		    " e1.pid=e2.pid and e1.eid!=e2.eid and ".
		    " e2.pid!='$TBOPSPID' ".
189 190
		    "WHERE e2.eid is null and ".
		    " e1.batchmode=1 and e1.canceled=0 and ".
191
		    " e1.expt_locked is null and ".
192
		    " e1.batchstate!='$BSTATE_LOCKED' and ".
193
		    " e1.state='$BSTATE_POSTED' and ".
194 195
		    "  (e1.attempts=0 or ".
		    "    ((UNIX_TIMESTAMP() - ".
196
		    "      UNIX_TIMESTAMP(e1.expt_start) > ($retry_wait)))) ".
197
		    "ORDER BY e1.expt_start LIMIT 1");
198

199
    $running_result =
200
	DBQuery("select * from experiments ".
201 202
		"where batchmode=1 and state='$BSTATE_RUNNING' and ".
		"      batchstate!='$BSTATE_LOCKED' ".
203
		"ORDER BY expt_start");
204 205 206

    if (!$pending_result || !$running_result) {
	print "DB Error getting batch info. Waiting a bit ...\n";
207
	DBQuery("unlock tables");
Leigh Stoller's avatar
Leigh Stoller committed
208
	goto pause;
209 210 211
    }

    if (!$pending_result->numrows && !$running_result->numrows) {
212
	DBQuery("unlock tables");
Leigh Stoller's avatar
Leigh Stoller committed
213
	goto pause;
214 215 216
    }

    #
217 218
    # If we have a pending experiment to run, the lock it right away,
    # while we have the tables locked. 
219
    #
220 221 222 223 224 225 226 227
    if ($pending_result->numrows) {
	%pending_row = $pending_result->fetchhash();

	# Local vars!
	my $eid = $pending_row{'eid'};
	my $pid = $pending_row{'pid'};

	$query_result = 
228
	    DBQuery("update experiments set ".
229
		    "       expt_locked=now(),expt_start=now(), ".
230
		    "       batchstate='$BSTATE_LOCKED' ".
231
		    "where eid='$eid' and pid='$pid'");
232 233 234

	if (! $query_result) {
	    print "DB error setting batch $pid/$eid to configuring.\n";
235
	    DBQuery("unlock tables");
Leigh Stoller's avatar
Leigh Stoller committed
236
	    goto pause;
237 238
	}
    }
239

240 241 242 243 244 245 246 247 248
    #
    # Okay, first we check the status of running batch mode experiments
    # since we want to end those before trying to start any new ones, cause
    # it would be nice to have as many nodes available as possible before
    # trying to add a new one. This can potentially delay startup, but thats
    # okay. Its a batch system.
    #
    # If you are wondering why I check for finished experiments in the main
    # loop instead of in the child that started the experiment, its so that
249
    # we fire up again and look for them in the event that boss goes down.
250
    #
251 252 253 254
    if (!$running_result->numrows) {
	DBQueryWarn("unlock tables");
    }
    else {
255 256 257 258 259 260
	my %canterm = ();
	
	while (my %running_row = $running_result->fetchhash()) {
	    # Local vars!
	    my $eid         = $running_row{'eid'};
	    my $pid         = $running_row{'pid'};
261

262 263 264 265 266 267 268 269 270 271 272
	    #
	    # Lock so user cannot mess with it.
	    # 
	    $query_result = 
		DBQuery("update experiments set ".
			"       expt_locked=now(), ".
			"       batchstate='$BSTATE_LOCKED' ".
			"where eid='$eid' and pid='$pid'");

	    $canterm{"$pid:$eid"} = ($query_result ? 1 : 0);
	}
273 274
	DBQueryWarn("unlock tables");

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
	#
	# Reset and go through again.
	#
	$running_result->dataseek(0);
	
	while (my %running_row = $running_result->fetchhash()) {
	    my $canceled    = $running_row{'canceled'};
	    # Local vars!
	    my $eid         = $running_row{'eid'};
	    my $pid         = $running_row{'pid'};
	    my $canterm     = $canterm{"$pid:$eid"};

	    next
		if (!$canterm);

290 291 292
	    if ($canceled) {
		# Look at the cancel flag.
		if ($canceled == EXPTCANCEL_TERM) {
293
		    dosomething("cancel", \%running_row);
294 295
		}
		elsif ($canceled == EXPTCANCEL_SWAP) {
296
		    dosomething("swap", \%running_row);
297 298 299 300
		}
		else {
		    print "Improper cancel flag: $canceled\n";
		}
301 302
	    }
	    else {
303
		if (isexpdone(\%running_row)) {
304 305 306
		    #
		    # Terminate the experiment. 
		    # 
307
		    dosomething("swap", \%running_row);
308 309 310 311 312 313 314
		}
		else {
		    #
		    # Unlock.
		    # 
		    TBBatchUnLockExp($pid, $eid);
		}
315
	    }
316 317 318 319 320 321
	}
    }
    #
    # Finally start an actual experiment!
    #
    if ($pending_result->numrows) {
322
	dosomething("start", \%pending_row);
323
    }
Leigh Stoller's avatar
Leigh Stoller committed
324
  pause:
325
    sleep(15);
326 327 328
}

#
329
# Do something as the user. Either, start, end, or cancel an experiment.
330
#
331
sub dosomething($$)
332
{
333
    my($dowhat,$exphash)   = @_;
334
    my($unix_uid, $unix_gid, $unix_gname, $row, $query_result);
335 336

    # Global vars
337 338 339 340
    $eid     = $exphash->{'eid'};
    $pid     = $exphash->{'pid'};
    $gid     = $exphash->{'gid'};
    $userdir = $exphash->{'path'};
341
    $workdir = TBExptWorkDir($pid, $eid);
342
    $nsfile  = "$eid.ns";
343
    $template= undef;
344 345
    
    # Locals
346
    my $creator = $exphash->{'expt_head_uid'};
347 348 349 350 351
    my $experiment = Experiment->Lookup($pid, $eid);
    if (! defined($experiment)) {
	print "Could not find experiment object! Skipping ...\n";
	return -1;
    }
352 353
    print "Doing a '$dowhat' to batch experiment $pid/$eid\n";

354 355 356
    # Clean before starting.
    $experiment->CleanLogFiles();

357 358 359 360 361
    #
    # Create a temporary name for a log file. We do this in the parent so
    # we can remove it when the child ends. The child could remove it, but
    # since it is open in the child, it has the tendency to stick around.
    #
362
    $logname = TBExptCreateLogFile($pid, $eid, "${dowhat}-batch");
363

364 365 366 367 368
    #
    # If this is a template instantiation, then do not set the logfile.
    # We still generate the log file, but it is not available via the
    # web interface. Needs more thought.
    #
369 370 371 372
    my $exptidx  = $exphash->{'idx'};
    my $instance = Template::Instance->LookupByExptidx($exptidx);
    if (defined($instance)) {
	$template = $instance->template();
373 374
    }

375 376 377
    #
    # Start up a child to run the guts. The parent waits. If the
    # experiment configures okay, the parent can return to try something
378
    # else.
379 380 381
    #
    $childpid = fork();
    if ($childpid) {
382

383
	print TBDateTimeFSSafe() . "\n";
384 385
	print "Child PID $childpid started to $dowhat $pid/$eid\n";

386
	waitpid($childpid, 0);
Leigh Stoller's avatar
Leigh Stoller committed
387
	my $status = $? >> 8;
388

389
	print TBDateTimeFSSafe() . "\n";
Leigh Stoller's avatar
Leigh Stoller committed
390
	print "Child PID $childpid exited with exit status $status\n";
391

392
        #
393
        # Close the log file.
394 395
	# The exp dir might be gone if the batch was killed/canceled.
        #
396
	if (-e $userdir) {
397 398
	    TBExptCloseLogFile($pid, $eid);
	}
Leigh Stoller's avatar
Leigh Stoller committed
399
	return $status;
400
    }
401
    openlog($logname);
402 403
    TBExptSetLogFile($pid, $eid, $logname);
    TBExptOpenLogFile($pid, $eid);
404

405 406 407
    #
    # Get some user information. 
    #
408
    if (!UserDBInfo($creator, \$user_name, \$user_email)) {
409
	fatal("DB Error getting user information for uid $creator");
410
    }
411
    
412 413
    chdir("$workdir") or
	fatal("Could not cd into $workdir!");
414 415 416 417 418

    #
    # Figure out the unix uid/gid that the experiment configuration is
    # going to run as. 
    #
Leigh Stoller's avatar
Leigh Stoller committed
419
    (undef,undef,$unix_uid) = getpwnam($creator) or
420
	fatal("No such user $creator");
421 422
    TBGroupUnixInfo($pid, $gid, \$unix_gid, \$unix_gname) or
	fatal("No such group $pid/$gid");
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    #
    # Need the entire group list for the user, cause of subgroups, and cause
    # thats the correct thing to do. Too bad perl does not have a getgrouplist
    # function like the C library.
    #
    my $glist = `id -G $creator`;
    if ($glist =~ /^([\d ]*)$/) {
	$glist = $1;
    }
    else {
	fatal("Unexpected results from 'id -G $creator': $glist");
    }
    #
    # Remove current group from glist, then add gid twice at the front
    # of the list. Order matters here, or we won't pick up all the
    # groups we need.
    #
    $glist =~ s/ ?\b$unix_gid\b ?//;
    $glist = $unix_gid . " " . $unix_gid . " " . $glist;

444 445 446
    #
    # Change the ownership of the log file before we flip.
    #
447 448
    chown($unix_uid, $unix_gid, $logname) or
	fatal("Could not chown $logname to $unix_uid/$unix_gid!");
449 450

    # Flip to the user. We never flip back.
451 452 453 454 455
    $GID            = $unix_gid;
    $EGID           = $glist;
    $EUID = $UID    = $unix_uid;
    $ENV{'USER'}    = $creator;
    $ENV{'LOGNAME'} = $creator;
456
    
457
    if ($dowhat eq "start") {
458
	startexp($exphash);
459
    }
460
    elsif ($dowhat eq "swap") {
461
	swapexp($exphash);
462 463
    }
    elsif ($dowhat eq "cancel") {
464
	cancelexp($exphash);
465 466 467 468 469 470 471 472 473
    }
    exit(0);
}

#
# Try to start an experiment. Never returns.
# 
sub startexp($)
{
474
    my($exphash)  = @_;
475
    my($exit_status, $running, $query_result);
476

477
    my $attempts  = $exphash->{'attempts'};
478

479
    #
480
    # Try to swap the experiment in. 
481
    #
482
    system("$swapexp -b -s in $pid $eid");
483 484
    $exit_status = $? >> 8;
    $running     = 1;
485 486 487 488 489
    if ($exit_status) {
	$running = 0;
    }
    
    #
490 491
    # Look for cancelation. If we get a DB error on this, just continue cause
    # we can pick up the cancelation later.
492 493
    #
    $query_result =
494
	DBQueryWarn("select canceled from experiments ".
495
		    "where eid='$eid' and pid='$pid'");
496

497
    if ($query_result) {
498
	my ($canceled) = $query_result->fetchrow_array();
499
	$exphash->{'canceled'} = $canceled;
500

501
	# Yuck: This is strictly for the benefit of swapexp() below.
502
	$exphash->{'state'} = EXPTSTATE_ACTIVE
503 504 505 506
	    if ($running);
	
	if ($canceled) {
	    # Look at the cancel flag.
507
	    if ($canceled == EXPTCANCEL_TERM) {
508
		cancelexp($exphash);
509
	    }
510
	    elsif ($canceled == EXPTCANCEL_SWAP) {
511
		swapexp($exphash);
512 513 514 515
	    }
	    else {
		print "Improper cancel flag: $canceled\n";
	    }
516 517 518
	    #
	    # Never returns, but just to be safe ...
	    #
519
	    exit(-1);
520 521
	}
    }
522 523 524 525

    #
    # If the configuration failed for lack of nodes, then don't send
    # email unless the number of attempts starts to get big.
526
    #
527 528 529
    # If the configuration failed for some other reason, then send email.
    # We have to reset the state to "new" so that it will be retried again
    # later. 
530 531
    #
    if (! $running) {
532 533 534 535
	#
	# XXX - What if this update fails?
	# 
	$query_result = 
536
	    DBQueryWarn("update experiments set attempts=attempts+1 ".
537
			"where eid='$eid' and pid='$pid'");
538

539
	#
540 541 542 543
	# The exit status does not tell us if the experiment can ever be
	# mapped. In fact, that is really hard to know at this level;
	# it depends on what resources the testbed actually has. So,
	# unless status is -1 (really really fatal) just keep going.
544 545
	# We leave it up the user to kill the batch if it looks like its
	# never going to work.
546
	#
547
	if ($exit_status == 255) {
548
	    TBBatchUnLockExp($pid, $eid, EXPTSTATE_SWAPPED());
549
	    
550
	    email_status("Experiment startup has failed with a fatal error!\n".
551 552
			 "Batch has been dequeued so that you may check it.");

553
	    exit($exit_status);
554
	}
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
	
	if (($attempts % 30) == 0) {
	    $attempts++;

	    my $msg =
		"Could not configure Batch Mode experiment $pid/$eid.\n".
		"\n".
		"There was an assignment violation (please check the log)\n".
		"that prevented it from being scheduled. The violation\n".
		"might result from not enough nodes or not enough link\n".
		"bandwidth. If you feel that the violation is in error,\n".
		"please cancel the batch and notify $TBOPS\n".
		"Otherwise, another attempt will be made in a little while.\n".
		"\n". 
		"There have been $attempts attempts to start this batch.";

	    email_status($msg);
	}
573
	TBBatchUnLockExp($pid, $eid, EXPTSTATE_QUEUED());
574
	exit($exit_status);
575 576 577
    }

    #
578
    # Well, it configured! We can now unlock it.
579
    #
580
    TBBatchUnLockExp($pid, $eid);
581
    
582
    email_status("Batch Mode experiment $pid/$eid is now running!\n".
583
		 "Please consult the Web interface to see how it is doing.");
Leigh Stoller's avatar
Leigh Stoller committed
584

585
    #
586
    # Done with this phase. Must exit.
587
    #
588 589
    exit(0);
}
590

591
#
592
# A batch has completed. Swap it out. 
593
#
594
sub swapexp($;$)
595
{
596 597 598
    my($exphash)  = @_;
    my $canceled  = $exphash->{'canceled'};
    my $running   = ($exphash->{'state'} eq EXPTSTATE_ACTIVE);
599

600
    if ($running) {
601 602 603 604 605
	if (defined($template)) {
	    my $guid = $template->guid();
	    my $vers = $template->vers();
	    
	    system("$template_swapout -b -e $eid $guid/$vers");
606 607 608 609
	}
	else {
	    system("$swapexp -b -s out $pid $eid");
	}
610 611 612 613 614 615
	if ($?) {
	    #
	    # TB admin is going to have to clean up. 
	    # 
	    fatal("Swapping out Batch Mode experiment $pid/$eid");
	}
616 617 618 619 620
    }
    #
    # Set the state to paused to ensure that it is not run again until
    # the user wants to.
    # 
621 622
    TBSetCancelFlag($pid, $eid, EXPTCANCEL_CLEAR);
    TBBatchUnLockExp($pid, $eid);
623
    
624 625 626 627 628
    if ($canceled) {
	email_status("Batch Mode experiment $pid/$eid has been stopped!");
    }
    else {
	email_status("Batch Mode experiment $pid/$eid has finished!");
629
    }
630
   
631
    #
632
    # Child must exit!
633
    #
634 635 636 637 638 639
    exit(0);
}

#
# Cancel an experiment. Never returns.
#
640
sub cancelexp($)
641
{
642
    my($exphash) = @_;
643
    
644 645 646 647
    #
    # It does not matter if the experiment is running; endexp does the
    # right thing.
    # 
648 649 650 651 652
    if (defined($template)) {
	my $guid = $template->guid();
	my $vers = $template->vers();
	
	system("$template_swapout -b -e $eid $guid/$vers");
653 654 655 656
    }
    else {
	system("$endexp -b $pid $eid");
    }
657 658 659 660 661
    if ($?) {
	#
	# TB admin is going to have to clean up. 
	# 
	fatal("Terminating Batch Mode experiment $pid/$eid");
662
    }
663
    donotify("Your Batch Mode experiment has been canceled!", "Canceled", 0);
664 665 666 667 668 669 670
   
    #
    # Child must exit!
    #
    exit(0);
}

671 672 673 674 675 676
#
# Check experiment status. Looks to see if all of the nodes in an
# experiment have reported in.
#
sub isexpdone($)
{
677
    my($exphash)  = @_;
678
    my($query_result, @row);
679 680
    
    # Global vars
681 682
    $eid = $exphash->{'eid'};
    $pid = $exphash->{'pid'};
683

684
    print TBDateTimeFSSafe() . "\n";
685 686 687 688 689 690
    print "Checking to see if $pid/$eid has finished up yet\n";

    #
    # Look to see if any nodes yet to report status. If so, spin again.
    #
    $query_result =
691 692 693
	DBQueryWarn("SELECT startstatus,bootstatus FROM nodes ".
		    "LEFT JOIN reserved ON nodes.node_id=reserved.node_id ".
		    "WHERE reserved.eid='$eid' and reserved.pid='$pid'");
694 695 696 697 698

    if (! $query_result) {
	return 0;
    }

699 700 701 702 703 704 705 706 707 708 709 710 711
    #
    # Well, right now a node is considered finished up only if its
    # boot did not fail, and it has reported start command status.
    # The idea being that if the boot failed, then its status will
    # never be reported anyway, and we might as well consider the node
    # done (else the experiment would never end).
    # 
    while (@row = $query_result->fetchrow_array()) {
	if ($row[1] eq NODEBOOTSTATUS_FAILED) {
	    next;
	}
	if ($row[0] eq NODESTARTSTATUS_NOSTATUS) {
	    return 0;
712 713
	}
    }
714
    return 1;
715 716 717 718
}

#
# Start up a child, and set its descriptors talking to a log file.
Leigh Stoller's avatar
Leigh Stoller committed
719
# The log file already exists, created with mktemp above.
720 721 722 723 724 725 726
# 
sub openlog($)
{
    my($logname) = $_[0];
	
    #
    # We have to disconnect from the caller by redirecting both STDIN and
Leigh Stoller's avatar
Leigh Stoller committed
727 728
    # STDOUT away from the pipe. Otherwise the caller will continue to wait
    # even though the parent has exited. 
729 730
    #
    open(STDIN, "< /dev/null") or
731
	fatal("opening /dev/null for STDIN: $!");
732 733 734 735 736 737

    open(STDERR, ">> $logname") or
	fatal("opening $logname for STDERR: $!");
    open(STDOUT, ">> $logname") or
	fatal("opening $logname for STDOUT: $!");

738 739 740
    STDOUT->autoflush(1);
    STDERR->autoflush(1);

741 742 743
    return 0;
}

744 745 746 747 748
#
# A fatal error is something that the user does not need to know about.
# Caused by a breakdown in the TB system. Generally speaking, once the
# experiment is running, this should not be used.
# 
749
sub fatal($)
750 751 752
{
    my($mesg) = $_[0];

753
    donotify($mesg, "Failure", 1);
754 755 756 757

    exit(-1);
}

758 759 760
#
# Something the user cares about. 
# 
761
sub email_status($)
762
{
763
    my($mesg) = $_[0];
764

765
    donotify($mesg, "Status", 0);
766 767
}

768
sub donotify($$$)
769
{
770
    my($mesg, $subtext, $iserr) = @_;
771
    my($subject, $from, $to, $hdrs);
772
    my $MAIL;
773

774 775 776
    $mesg = "$mesg\n";

    print STDOUT "$mesg";
777

778
    $subject = "Batch Mode Experiment $subtext $pid/$eid";
779
    $from    = $TBOPS;
780 781 782 783 784 785
    $hdrs    = "Reply-To: $TBOPS";
    
    #
    # An error goes just to Testbed Operations. Normal status messages go
    # to the user and to the Testbed Logs address.
    # 
786
    if ($iserr) {
787
	$to = "$TBOPS";
788 789
    }
    else {
790 791 792
	$to   = "$user_name <$user_email>";
	$hdrs = "Bcc: $TBLOGS\n".
	        "$hdrs";
793 794
    }

795
    SENDMAIL($to, $subject, $mesg, $from, $hdrs,
796
	     ($logname, "assign.log", $nsfile));
797
}
798