batch_daemon.in 14.5 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
26
27
28
29
30

#
# Configure variables
#
my $TB       = "@prefix@";
my $DBNAME   = "@TBDBNAME@";
my $TBOPS    = "@TBOPSEMAIL@";

my $tbbindir = "$TB/bin/";
my $batchdir = "$TB/batch";
my $startexp = "$TB/bin/startexp";
my $endexp   = "$TB/bin/endexp";
31
my $avail    = "$TB/sbin/avail";
32
33
my $batchlog = "$TB/log/batchlog";
my $projroot = "/proj";
34
my $debug    = 0;
35
36
37
38
39
40
41
42
43
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
44
my $nsfile;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
my $user_name  = "Batch Daemon";
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();
}
70
71
72
if (defined($options{"d"})) {
    $debug = $options{"d"};
}
73
74

# Go to ground.
75
76
77
if (! $debug) {
    daemonize();
}
78
79
80
81
82
83
84
85
86
87
88

#
# Set up for querying the database.
# 
use Mysql;
my $DB = Mysql->connect("localhost", $DBNAME, "script", "none");

#
# Loop, looking for batch experiments that want to run.
# 
while (1) {
89
90
91
    my($count);
    my(%row, %pending_row);
    
92
93
94
95
96
97
98
99
100
101
    #
    # 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?
    #
102
    # So, now you're wondering what my selection criteria is? Well, its
103
104
105
106
107
    # 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 =
108
109
110
111
112
113
114
115
	DBquery("lock tables batch_experiments write");
    if (! $query_result) {
	print "DB Error locking tables. Waiting a bit ...\n";
	sleep(10);
	next;
    }
    
    $pending_result =
116
117
118
	DBquery("SELECT * FROM batch_experiments ".
		"WHERE status='new' and canceled=0 ORDER BY started LIMIT 1");

119
120
121
122
123
124
125
126
127
128
129
130
131
    $running_result =
	DBquery("SELECT * FROM batch_experiments ".
		"WHERE status='running' ORDER BY started");

    if (!$pending_result || !$running_result) {
	print "DB Error getting batch info. Waiting a bit ...\n";
	DBquery("unlock tables");
	sleep(10);
	next;

    }

    if (!$pending_result->numrows && !$running_result->numrows) {
132
133
134
135
136
137
	DBquery("unlock tables");
	sleep(10);
	next;
    }

    #
138
139
140
    # 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.
141
    #
142
143
144
145
146
147
148
149
150
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 = 
	    DBquery("update batch_experiments set status='configuring', ".
		    "started='$now' where eid='$eid' and pid='$pid'");

	if (! $query_result) {
	    print "DB error setting batch $pid/$eid to configuring.\n";
	    DBquery("unlock tables");
	    sleep(10);
	    next;
	}
    }
161
162
    DBquery("unlock tables");

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    #
    # 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.
    #
    $count = $running_result->numrows;
    for ($i = 0; $i < $count; $i++) {
	%row = $running_result->fetchhash();

	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);
    }
    sleep(60);
196
197
198
}

#
199
# Do something as the user. Either, start, end, or cancel an experiment.
200
#
201
sub dosomething($$)
202
{
203
204
    my($dowhat)   = shift;
    my(%exphash)  = @_;
205
206
207
208
209
210
    my($uid, $gid, $row);

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

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    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";
    }

227
228
229
    #
    # Start up a child to run the guts. The parent waits. If the
    # experiment configures okay, the parent can return to try something
230
    # else.
231
232
233
    #
    $childpid = fork();
    if ($childpid) {
234
235
	print "Child PID $childpid started to $dowhat $pid/$eid\n";

236
	waitpid($childpid, 0);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
237
	my $status = $? >> 8;
238

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

Leigh B. Stoller's avatar
Leigh B. Stoller committed
241
	sleep(5);
242

243
	unlink($logname);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
244
	return $status;
245
    }
246
247
248
249
250
251
252
253
    openlog($logname);

    #
    # Form a new connection to the DB since we are in the child. Not sure
    # if this happens as a result of the fork, but lets be sure.
    #
    undef($DB);
    $DB = Mysql->connect("localhost", $DBNAME, "script", "none");
254

255
256
257
258
259
    my $creator  = $exphash{'creator_uid'};
    my $longname = $exphash{'name'};
    
    # Global var
    $dirname  = "$batchdir/$pid-$eid";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
260
    $nsfile  = "$dirname/$eid.ns";
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

    #
    # Get some user information. 
    #
    $query_result =
	$DB->query("SELECT usr_name,usr_email from users ".
		   "WHERE uid='$creator'");

    if (! $query_result ||
	$query_result->numrows != 1) {
	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");

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

    # Flip to the user. We never flip back.
292
293
    $EGID = $GID = $gid;
    $EUID = $UID = $uid;
294
    $ENV{'USER'} = $creator;
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
    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)  = @_;
    my($exit_status, $running);

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

322
    #
323
324
    # Lets see if there are enough nodes. This is a really hacky test,
    # especially for the sharks since they are allocated by shelf. 
325
    #
326
327
328
329
    system("$avail type=pc > /dev/null");
    my $availpcs = $? >> 8;
    system("$avail type=shark > /dev/null");
    my $availsharks = $? >> 8;
330

331
332
333
334
335
336
337
338
339
    if ($availpcs < $numpcs || $availsharks < $numsharks) {
	#
	# XXX - What if this update fails?
	# 
	$query_result = 
	    DBquery("update batch_experiments set status='new' ".
		    "where eid='$eid' and pid='$pid'");
	
	exit(69);
340
341
342
343
344
345
    }

    #
    # Insert an experiment record for startexp.
    #
    my $rightnow = `date '+20%y-%m-%d %H:%M:%S'`;
346
347
348
349
350
351
352
353
354
    $query_result =
	DBquery("insert into experiments ".
		"(eid, pid, expt_created, expt_name, ".
		"expt_head_uid, expt_start, expt_ready, batchmode) ".
		"VALUES ('$eid', '$pid', '$rightnow', '$longname', ".
		"'$creator', '$rightnow', 0, 1)");
    if (! $query_result) {
	fatal("DB error inserting experiment record. Quitting ...\n");
    }
355
356
357
358
359

    #
    # Try to start the experiment. If it fails, the experiment is gone.
    #
    system("$startexp -b $pid $eid $nsfile");
360
361
    $exit_status = $? >> 8;
    $running     = 1;
362
363
364
365
366
    if ($exit_status) {
	$running = 0;
    }
    
    #
367
368
    # Look for cancelation. If we get a DB error on this, just continue cause
    # we can pick up the cancelation later.
369
370
371
372
373
    #
    $query_result =
	DBquery("select canceled from batch_experiments ".
		"where eid='$eid' and pid='$pid'");

374
375
    if ($query_result) {
	@row = $query_result->fetchrow_array();
376

377
378
379
380
381
382
383
384
385
	if ($row[0]) {
	    cancelexp($running);
	    #
	    # Never returns, but just to be safe ...
	    #
	    exit(0);
	}
    }
			    
386
387
388
389
390
391
    #
    # If the configuration failed, then send email for now. This
    # part needs work. We have to reset the state to "new" so that
    # it will be retried again later. 
    #
    if (! $running) {
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
	#
	# XXX - What if this update fails?
	# 
	$query_result = 
	    DBquery("update batch_experiments set status='new', ".
		    "attempts=attempts+1 where eid='$eid' and pid='$pid'");

	if (($attempts % 5) == 0) {
	    $attempts++;
	    
	    fatal("Could not configure Batch Mode experiment $pid/$eid\n".
		  "There have been $attempts attempts made to start this ".
		  "batch\n");
	}
	exit(45);
407
408
409
410
411
    }

    #
    # Well, it configured! Lets set it state to running.
    #
412
    # XXX - What if this update fails?
Leigh B. Stoller's avatar
Leigh B. Stoller committed
413
    #
414
415
416
    $query_result = 
	DBquery("update batch_experiments set status='running' ".
		"where eid='$eid' and pid='$pid'");
Leigh B. Stoller's avatar
Leigh B. Stoller committed
417

418
419
    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
420

421
    #
422
    # Done with this phase. Must exit.
423
    #
424
425
    exit(0);
}
426

427
428
429
430
431
432
#
# End an experiment. Never returns.
#
sub endexp($)
{
    my(%exphash)  = @_;
433
    
434
435
436
437
438
    system("$endexp -b $pid $eid");
    DBquery("DELETE from batch_experiments WHERE eid='$eid' and pid='$pid'");
    email_status("Batch Mode experiment $pid/$eid has finished!\n");
    system("rm -rf $dirname");
   
439
    #
440
    # Child must exit!
441
    #
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    exit(0);
}

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

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

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
#
# Check experiment status. Looks to see if all of the nodes in an
# experiment have reported in.
#
sub isexpdone($)
{
    my(%exphash)  = @_;
    my($row, $done);
    
    # 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 =
	DBquery("SELECT startstatus FROM nodes LEFT JOIN reserved ".
		"ON nodes.node_id=reserved.node_id ".
		"WHERE reserved.eid='$eid' and reserved.pid='$pid'");

    if (! $query_result) {
	return 0;
    }

    $done = 1;
    for ($i = 0; $i < $query_result->numrows; $i++) {
	@row = $query_result->fetchrow_array();
	
	if ($row[0] eq "none") {
	    $done = 0;
	}
    }
    return $done;
}

506
507
508
sub DBquery($)
{
    my($query) = $_[0];
509
    my($result);
510

511
    $result = $DB->query($query);
512

513
514
    if (! $result) {
	print "DB Query failed: $query\n";
515
516
    }

517
    return $result;
518
519
520
521
}

#
# Start up a child, and set its descriptors talking to a log file.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
522
# The log file already exists, created with mktemp above.
523
524
525
526
527
528
529
# 
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
530
531
    # STDOUT away from the pipe. Otherwise the caller will continue to wait
    # even though the parent has exited. 
532
533
    #
    open(STDIN, "< /dev/null") or
534
	fatal("opening /dev/null for STDIN: $!");
535
536
537
538
539
540
541
542
543

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

    return 0;
}

544
sub fatal($)
545
546
547
{
    my($mesg) = $_[0];

548
    notify_user($mesg, "Failure", 1);
549
550
551
552

    exit(-1);
}

553
sub email_status($)
554
{
555
    my($mesg) = $_[0];
556

557
    notify_user($mesg, "Status", 0);
558
559
}

560
sub notify_user($$$)
561
{
562
563
    my($mesg, $subline, $iserr) = @_;
    my($to,$cc);
564
565
566

    print STDOUT "$mesg\n";

567
568
569
570
571
572
    #
    # If an error, goes to TBOPS and is CC'ed to user.
    # Otherwise goes to user and is CC'ed to TBOPS
    #
    if ($iserr) {
	$to = $TBOPS;
573
	$cc = $user_email;
574
575
    }
    else {
576
	$to = $user_email;
577
578
579
	$cc = $TBOPS;
    }

580
    open(MAIL, "| /usr/bin/mail ".
581
	 "-s \"TESTBED: Batch Mode Experiment $subline $pid/$eid\" ".
582
	 "-c $cc $to >/dev/null 2>&1")
583
584
585
586
587
588
589
590
591
592
593
594
	or die "Cannot start mail program: $!";

    print MAIL $mesg;

    if (defined($logname) && open(IN, "$logname")) {
	print MAIL "\n\n---------\n\n";
	
	while (<IN>) {
	    print MAIL "$_";
	}
	close(IN);
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
595
596
597
598
599
600
601
602
603
604

    if (defined($nsfile) && open(IN, "$nsfile")) {
	print MAIL "\n\n---------\n\n";
	
	while (<IN>) {
	    print MAIL "$_";
	}
	close(IN);
    }
    
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
    close(MAIL);
}

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