batch_daemon.in 14.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
#!/usr/bin/perl -wT
use English;
use Getopt::Std;

#
# Create a batch experiment.
#
# usage: batch_daemon
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
10
11
# TODO: Use "logger" instead of writing a log file.
#
12
13
sub usage()
{
14
15
    print STDOUT "Usage: batch_daemon [-d]\n" .
	"Use the -d option to prevent daemonization\n";
16
17
    exit(-1);
}
18
my  $optlist = "d";
19
20
21
22
23
24
25

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

28
29
30
31
32
33
34
#
# Testbed Support libraries
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;

Leigh B. Stoller's avatar
Leigh B. Stoller committed
35
36
37
38
39
#
# Ug, exit value from startexp when not enough nodes.
# 
my $TOOFEWNODES = 2;

40
41
42
43
my $tbbindir = "$TB/bin/";
my $batchdir = "$TB/batch";
my $startexp = "$TB/bin/startexp";
my $endexp   = "$TB/bin/endexp";
44
my $savelogs = "$TB/bin/savelogs";
45
my $avail    = "$TB/sbin/avail";
46
47
my $batchlog = "$TB/log/batchlog";
my $projroot = "/proj";
48
my $debug    = 0;
49
50
51
52
53
54
55
56
57
my $dirname;

#
# 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;
my $logname;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
58
my $nsfile;
59
my $user_name  = "Testbed Operations";
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
my $user_email = "$TBOPS";

#
# 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();
}
84
85
86
if (defined($options{"d"})) {
    $debug = $options{"d"};
}
87
88

# Go to ground.
89
90
91
if (! $debug) {
    daemonize();
}
92
93
94
95
96

#
# Loop, looking for batch experiments that want to run.
# 
while (1) {
97
    my($count, $i, $query_result, $pending_result, $running_result);
98
99
    my(%row, %pending_row);
    
100
101
102
103
104
105
106
107
108
109
    #
    # Need to lock the table here because of cancelation in killbatchexp.
    # 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!
    # Thats would ne annoying to users, and we love our users, right?
    #
110
    # So, now you're wondering what my selection criteria is? Well, its
111
112
113
114
115
    # damn simplistic. I set the "started" datetime field each attempt,
    # and I pick the batch_experiment with the oldest time, thereby cycling
    # through in a "least recently attempted" manner. 
    #
    $query_result =
116
	DBQuery("lock tables batch_experiments write");
117
118
119
120
121
122
123
    if (! $query_result) {
	print "DB Error locking tables. Waiting a bit ...\n";
	sleep(10);
	next;
    }
    
    $pending_result =
124
	DBQuery("SELECT * FROM batch_experiments ".
125
126
127
		"WHERE status='new' and canceled=0 and (attempts=0 or ".
		"((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(started) > (60 * 10)))) ".
		"ORDER BY started LIMIT 1");
128

129
    $running_result =
130
	DBQuery("SELECT * FROM batch_experiments ".
131
132
133
134
		"WHERE status='running' ORDER BY started");

    if (!$pending_result || !$running_result) {
	print "DB Error getting batch info. Waiting a bit ...\n";
135
	DBQuery("unlock tables");
136
137
138
139
140
141
	sleep(10);
	next;

    }

    if (!$pending_result->numrows && !$running_result->numrows) {
142
	DBQuery("unlock tables");
143
144
145
146
147
	sleep(10);
	next;
    }

    #
148
149
150
    # If we have a pending experiment to run, set its state to configuring
    # right away, while we have the tables locked. This prevents killbatchexp
    # from seeing it as something it can cancel.
151
    #
152
153
154
155
156
157
158
159
160
    if ($pending_result->numrows) {
	%pending_row = $pending_result->fetchhash();

	# Local vars!
	my $eid = $pending_row{'eid'};
	my $pid = $pending_row{'pid'};
	my $now = `date '+20%y-%m-%d %H:%M:%S'`;

	$query_result = 
161
	    DBQuery("update batch_experiments set status='configuring', ".
162
163
164
165
		    "started='$now' where eid='$eid' and pid='$pid'");

	if (! $query_result) {
	    print "DB error setting batch $pid/$eid to configuring.\n";
166
	    DBQuery("unlock tables");
167
168
169
170
	    sleep(10);
	    next;
	}
    }
171
    DBQueryWarn("unlock tables");
172

173
174
175
176
177
178
179
180
181
182
183
    #
    # 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
    # we fire up again and look for them in the event that paper goes down.
    #
184
    while (%row = $running_result->fetchhash()) {
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
	my $canceled = $row{'canceled'};
	if ($canceled) {
	    dosomething("cancel", %row);
	    next;
	}
	if (isexpdone(%row)) {
	    dosomething("end", %row);
	    next;
	}
    }

    #
    # Finally start an actual experiment!
    #
    if ($pending_result->numrows) {
	dosomething("start", %pending_row);
    }
202
    sleep(15);
203
204
205
}

#
206
# Do something as the user. Either, start, end, or cancel an experiment.
207
#
208
sub dosomething($$)
209
{
210
211
    my($dowhat)   = shift;
    my(%exphash)  = @_;
212
    my($uid, $gid, $row, $query_result);
213
214
215
216
217

    # Global vars
    $eid = $exphash{'eid'};
    $pid = $exphash{'pid'};

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    print "Doing a '$dowhat' to batch experiment $pid/$eid\n";

    #
    # 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.
    #
    $logname = `mktemp /tmp/$dowhat-batch-$pid-$eid.XXXXXX`;

    # Note different taint check (allow /).
    if ($logname =~ /^([-\@\w.\/]+)$/) {
	$logname = $1;
    } else {
	die "Bad data in $logname";
    }

234
235
236
    #
    # Start up a child to run the guts. The parent waits. If the
    # experiment configures okay, the parent can return to try something
237
    # else.
238
239
240
    #
    $childpid = fork();
    if ($childpid) {
241
242
	print "Child PID $childpid started to $dowhat $pid/$eid\n";

243
	waitpid($childpid, 0);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
244
	my $status = $? >> 8;
245

Leigh B. Stoller's avatar
Leigh B. Stoller committed
246
	print "Child PID $childpid exited with exit status $status\n";
247

Leigh B. Stoller's avatar
Leigh B. Stoller committed
248
	sleep(5);
249

250
	unlink($logname);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
251
	return $status;
252
    }
253
254
255
256
257
    openlog($logname);

    my $creator  = $exphash{'creator_uid'};
    my $longname = $exphash{'name'};
    
258
    # Global vars
259
    $dirname  = "$batchdir/$pid-$eid";
260
    $nsfile   = "$dirname/$eid.ns";
261
262
263
264
265

    #
    # Get some user information. 
    #
    $query_result =
266
267
	DBQueryFatal("SELECT usr_name,usr_email from users ".
		     "WHERE uid='$creator'");
268

269
    if ($query_result->numrows != 1) {
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
	fatal("DB Error getting user information for uid $creator\n");
    }
    @row = $query_result->fetchrow_array();
    $user_name  = $row[0];
    $user_email = $row[1];

    #
    # Figure out the unix uid/gid that the experiment configuration is
    # going to run as. 
    #
    (undef,undef,$uid) = getpwnam($creator) or
	fatal("No such user $creator");
    (undef,undef,$gid) = getgrnam($pid) or
	fatal("No such group $pid");

285
286
287
288
289
290
    #
    # Change the ownership of the log file before we flip.
    #
    chown($uid, $gid, $logname);

    # Flip to the user. We never flip back.
291
292
    $EGID = $GID = $gid;
    $EUID = $UID = $uid;
293
    $ENV{'USER'} = $creator;
294
    
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
    if ($dowhat eq "start") {
	startexp(%exphash);
    }
    elsif ($dowhat eq "end") {
	endexp(%exphash);
    }
    elsif ($dowhat eq "cancel") {
	cancelexp(1, %exphash);
    }
    exit(0);
}

#
# Try to start an experiment. Never returns.
# 
sub startexp($)
{
    my(%exphash)  = @_;
313
    my($exit_status, $running, $query_result);
314
315
316
317
318

    my $creator   = $exphash{'creator_uid'};
    my $longname  = $exphash{'name'};
    my $attempts  = $exphash{'attempts'};

319
320
321
322
    #
    # Insert an experiment record for startexp.
    #
    my $rightnow = `date '+20%y-%m-%d %H:%M:%S'`;
323
    $query_result =
324
325
	DBQueryFatal("insert into experiments ".
		     "(eid, pid, expt_created, expt_name, ".
326
		     "expt_head_uid, state, batchmode) ".
327
		     "VALUES ('$eid', '$pid', '$rightnow', '$longname', ".
328
		     "'$creator', 'new', 1)");
329
330
331
332

    #
    # Try to start the experiment. If it fails, the experiment is gone.
    #
333
    system("$startexp -b $logname $pid $eid $nsfile");
334
335
    $exit_status = $? >> 8;
    $running     = 1;
336
337
338
339
340
    if ($exit_status) {
	$running = 0;
    }
    
    #
341
342
    # Look for cancelation. If we get a DB error on this, just continue cause
    # we can pick up the cancelation later.
343
344
    #
    $query_result =
345
346
	DBQueryWarn("select canceled from batch_experiments ".
		    "where eid='$eid' and pid='$pid'");
347

348
349
    if ($query_result) {
	@row = $query_result->fetchrow_array();
350

351
352
353
354
355
356
357
358
	if ($row[0]) {
	    cancelexp($running);
	    #
	    # Never returns, but just to be safe ...
	    #
	    exit(0);
	}
    }
359
360
361
362

    #
    # If the configuration failed for lack of nodes, then don't send
    # email unless the number of attempts starts to get big.
363
    #
364
365
366
    # 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. 
367
368
    #
    if (! $running) {
369
370
371
372
	#
	# XXX - What if this update fails?
	# 
	$query_result = 
373
374
	    DBQueryWarn("update batch_experiments set status='new', ".
			"attempts=attempts+1 where eid='$eid' and pid='$pid'");
375
	$attempts++;
376

Leigh B. Stoller's avatar
Leigh B. Stoller committed
377
378
379
	if (($exit_status == $TOOFEWNODES && $attempts >= 9 &&
	     (($attempts % 9) == 0)) ||
	    (($exit_status != $TOOFEWNODES) && ($attempts % 5) == 0) ||
380
	    ($attempts == 0)) {
381
	    
382
383
384
385
	    email_status("Could not configure Batch Mode experiment ".
			 "$pid/$eid\n".
			 "There have been $attempts attempts made to start ".
			 "this batch\n");
386
	}
387
	exit($exit_status);
388
389
390
391
392
    }

    #
    # Well, it configured! Lets set it state to running.
    #
393
    # XXX - What if this update fails?
Leigh B. Stoller's avatar
Leigh B. Stoller committed
394
    #
395
    $query_result = 
396
397
	DBQueryWarn("update batch_experiments set status='running' ".
		    "where eid='$eid' and pid='$pid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
398

399
400
    email_status("Batch Mode experiment $pid/$eid is now running!\n".
		 "Please consult the Web interface to see how it is doing\n");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
401

402
    #
403
    # Done with this phase. Must exit.
404
    #
405
406
    exit(0);
}
407

408
409
410
411
412
413
#
# End an experiment. Never returns.
#
sub endexp($)
{
    my(%exphash)  = @_;
414
415
416
417
418
419

	#
	# Save tiplogs
	#
    system("$savelogs $pid $eid");

420
    system("$endexp -b $pid $eid");
421
422
423
424
425
426
427
428
429
    my $exit_status = $? >> 8;

    if ($exit_status) {
	#
	# TB admin is going to have to clean up. 
	# 
	fatal("Terminating Batch Mode experiment $pid/$eid");
    }
    
430
431
    DBQueryWarn("DELETE from batch_experiments ".
		"WHERE eid='$eid' and pid='$pid'");
432
433
434
    email_status("Batch Mode experiment $pid/$eid has finished!\n");
    system("rm -rf $dirname");
   
435
    #
436
    # Child must exit!
437
    #
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    exit(0);
}

#
# Cancel an experiment. Never returns.
#
sub cancelexp($$)
{
    my($running) = shift;
    my(%exphash) = @_;
    
    if ($running) {
	system("$endexp -b $pid $eid");
    }

453
454
455
    DBQueryWarn("DELETE from batch_experiments ".
		"WHERE eid='$eid' and pid='$pid'");
    donotify("Your Batch Mode experiment has been canceled. You may now\n".
456
		"reuse the experiment name\n", "Canceled", 0);
457
458
459
460
461
462
463
464
    system("rm -rf $dirname");
   
    #
    # Child must exit!
    #
    exit(0);
}

465
466
467
468
469
470
471
#
# Check experiment status. Looks to see if all of the nodes in an
# experiment have reported in.
#
sub isexpdone($)
{
    my(%exphash)  = @_;
472
    my($query_result, @row);
473
474
475
476
477
478
479
480
481
482
483
    
    # Global vars
    $eid = $exphash{'eid'};
    $pid = $exphash{'pid'};

    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 =
484
485
486
	DBQueryWarn("SELECT startstatus,bootstatus FROM nodes ".
		    "LEFT JOIN reserved ON nodes.node_id=reserved.node_id ".
		    "WHERE reserved.eid='$eid' and reserved.pid='$pid'");
487
488
489
490
491

    if (! $query_result) {
	return 0;
    }

492
493
494
495
496
497
498
499
500
501
502
503
504
    #
    # 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;
505
506
	}
    }
507
    return 1;
508
509
510
511
}

#
# Start up a child, and set its descriptors talking to a log file.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
512
# The log file already exists, created with mktemp above.
513
514
515
516
517
518
519
# 
sub openlog($)
{
    my($logname) = $_[0];
	
    #
    # We have to disconnect from the caller by redirecting both STDIN and
Leigh B. Stoller's avatar
Leigh B. Stoller committed
520
521
    # STDOUT away from the pipe. Otherwise the caller will continue to wait
    # even though the parent has exited. 
522
523
    #
    open(STDIN, "< /dev/null") or
524
	fatal("opening /dev/null for STDIN: $!");
525
526
527
528
529
530
531
532
533

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

    return 0;
}

534
535
536
537
538
#
# 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.
# 
539
sub fatal($)
540
541
542
{
    my($mesg) = $_[0];

543
    donotify($mesg, "Failure", 1);
544
545
546
547

    exit(-1);
}

548
549
550
#
# Something the user cares about. 
# 
551
sub email_status($)
552
{
553
    my($mesg) = $_[0];
554

555
    donotify($mesg, "Status", 0);
556
557
}

558
sub donotify($$$)
559
{
560
    my($mesg, $subtext, $iserr) = @_;
561
    my($subject, $from, $to, $hdrs);
562
    my $MAIL;
563
564
565

    print STDOUT "$mesg\n";

566
567
    $subject = "TESTBED: Batch Mode Experiment $subtext $pid/$eid";
    $from    = $TBOPS;
568
569
570
571
572
573
    $hdrs    = "Reply-To: $TBOPS";
    
    #
    # An error goes just to Testbed Operations. Normal status messages go
    # to the user and to the Testbed Logs address.
    # 
574
    if ($iserr) {
575
	$to = "$TBOPS";
576
577
    }
    else {
578
579
580
	$to   = "$user_name <$user_email>";
	$hdrs = "Bcc: $TBLOGS\n".
	        "$hdrs";
581
582
    }

583
    if (! ($MAIL = OPENMAIL($to, $subject, $from, $hdrs))) {
584
585
	die("Cannot start mail program!");
    }
586

587
    print $MAIL $mesg;
588
589

    if (defined($logname) && open(IN, "$logname")) {
590
	print $MAIL "\n\n---------\n\n";
591
592
	
	while (<IN>) {
593
	    print $MAIL "$_";
594
595
596
	}
	close(IN);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
597
598

    if (defined($nsfile) && open(IN, "$nsfile")) {
599
	print $MAIL "\n\n---------\n\n";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
600
601
	
	while (<IN>) {
602
	    print $MAIL "$_";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
603
604
605
606
	}
	close(IN);
    }
    
607
    close($MAIL);
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
}

#
# Become a daemon.
# 
sub daemonize()
{
    my $mypid = fork();
    if ($mypid) {
	exit(0);
    }

    #
    # We have to disconnect from the caller by redirecting both STDIN and
    # STDOUT away from the pipe. Otherwise the caller will continue to wait
    # even though the parent has exited. 
    #
    open(STDIN, "< /dev/null") or
	die("opening /dev/null for STDIN: $!");

    #
    # Open the batch log and start writing to it. 
    #
    open(STDERR, ">> $batchlog") or die("opening $batchlog for STDERR: $!");
    open(STDOUT, ">> $batchlog") or die("opening $batchlog for STDOUT: $!");

    return 0;
}