File: JobScheduler.java

package info (click to toggle)
libpj-java 0.0~20150107%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 13,396 kB
  • sloc: java: 99,543; ansic: 987; sh: 153; xml: 26; makefile: 10; sed: 4
file content (1921 lines) | stat: -rw-r--r-- 50,867 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
70
71
72
73
74
75
76
77
78
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
286
287
288
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
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
371
372
373
374
375
376
377
378
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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
//******************************************************************************
//
// File:    JobScheduler.java
// Package: edu.rit.pj.cluster
// Unit:    Class edu.rit.pj.cluster.JobScheduler
//
// This Java source file is copyright (C) 2012 by Alan Kaminsky. All rights
// reserved. For further information, contact the author, Alan Kaminsky, at
// ark@cs.rit.edu.
//
// This Java source file is part of the Parallel Java Library ("PJ"). PJ is free
// software; you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// PJ 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 General Public License for more details.
//
// Linking this library statically or dynamically with other modules is making a
// combined work based on this library. Thus, the terms and conditions of the
// GNU General Public License cover the whole combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent modules, and
// to copy and distribute the resulting executable under terms of your choice,
// provided that you also meet, for each linked independent module, the terms
// and conditions of the license of that module. An independent module is a
// module which is not derived from or based on this library. If you modify this
// library, you may extend this exception to your version of the library, but
// you are not obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
//
// A copy of the GNU General Public License is provided in the file gpl.txt. You
// may also obtain a copy of the GNU General Public License on the World Wide
// Web at http://www.gnu.org/licenses/gpl.html.
//
//******************************************************************************

package edu.rit.pj.cluster;

import edu.rit.http.HttpRequest;
import edu.rit.http.HttpResponse;
import edu.rit.http.HttpServer;

import edu.rit.mp.Channel;
import edu.rit.mp.ChannelGroup;
import edu.rit.mp.ChannelGroupClosedException;
import edu.rit.mp.ConnectListener;
import edu.rit.mp.Status;

import edu.rit.mp.ObjectBuf;

import edu.rit.mp.buf.ObjectItemBuf;

import edu.rit.pj.Version;

import edu.rit.util.Logger;
import edu.rit.util.PrintStreamLogger;
import edu.rit.util.Timer;
import edu.rit.util.TimerTask;
import edu.rit.util.TimerThread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;

import java.net.InetSocketAddress;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * Class JobScheduler is the main program for the PJ Job Scheduler Daemon
 * process for a parallel computer.
 * <P>
 * Run the Job Scheduler Daemon on the cluster's frontend processor by typing
 * this command:
 * <P>
 * java edu.rit.pj.cluster.JobScheduler <I>configfile</I>
 * <BR><I>configfile</I> = Configuration file name
 * <P>
 * For further information about the configuration file, see class {@linkplain
 * Configuration}.
 *
 * @author  Alan Kaminsky
 * @version 20-Jun-2012
 */
public class JobScheduler
	implements JobSchedulerRef
	{

// Hidden data members.

	// Cluster name.
	private String myClusterName;

	// Log file.
	private Logger myLog;

	// Web interface host and port.
	private String myWebHost;
	private int myWebPort;

	// Job Scheduler host and port.
	private String mySchedulerHost;
	private int mySchedulerPort;

	// Job frontend host.
	private String myFrontendHost;

	// Maximum job time, or 0 if no maximum.
	private int myJobTime;

	// Mapping from backend processor name to backend info.
	private Map<String,BackendInfo> myNameToBackendMap =
		new HashMap<String,BackendInfo>();

	// Array of backend info records.
	private BackendInfo[] myBackendInfo;
	private int myBackendCount;

	// Next backend number to assign to a job.
	private int myNextBackendNumber = 0;

	// Next job number.
	private int myNextJobNumber = 1;

	// Mapping from job frontend to job info.
	private Map<JobFrontendRef,JobInfo> myFrontendToJobMap =
		new HashMap<JobFrontendRef,JobInfo>();

	// Queue of running jobs.
	private List<JobInfo> myRunningJobList =
		new LinkedList<JobInfo>();

	// Queue of waiting jobs.
	private List<JobInfo> myWaitingJobList =
		new LinkedList<JobInfo>();

	// Timer thread for lease renewals and expirations.
	private TimerThread myLeaseTimerThread;

	// Channel group for communicating with job frontend processes.
	private ChannelGroup myChannelGroup;

	// Server for web interface.
	private HttpServer myHttpServer;

	// Total compute time (msec) of all jobs.
	private long myTotalComputeTime;

	// Date and time when Job Scheduler started.
	private long myStartDateTime;

// Hidden constructors.

	/**
	 * Construct a new Job Scheduler Daemon.
	 *
	 * @param  configfile  Configuration file name.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private JobScheduler
		(String configfile)
		throws IOException
		{
		long now = System.currentTimeMillis();
		myStartDateTime = now;

		// Parse configuration file.
		Configuration config = new Configuration (configfile);
		myClusterName = config.getClusterName();
		myLog =
			new PrintStreamLogger
				(new PrintStream
					(new FileOutputStream (config.getLogFile(), true),
					 true));
		myWebHost = config.getWebHost();
		myWebPort = config.getWebPort();
		mySchedulerHost = config.getSchedulerHost();
		mySchedulerPort = config.getSchedulerPort();
		myFrontendHost = config.getFrontendHost();
		myJobTime = config.getJobTime();
		myBackendCount = config.getBackendCount();
		myBackendInfo = new BackendInfo [myBackendCount];
		for (int i = 0; i < myBackendCount; ++ i)
			{
			BackendInfo backendinfo = config.getBackendInfo (i);
			myNameToBackendMap.put (backendinfo.name, backendinfo);
			myBackendInfo[i] = backendinfo;
			}

		// Log startup.
		myLog.log (now, "Started " + Version.PJ_VERSION);

		// Set up shutdown hook.
		Runtime.getRuntime().addShutdownHook (new Thread()
			{
			public void run()
				{
				shutdown();
				}
			});

		// Set up lease timer thread.
		myLeaseTimerThread = new TimerThread();
		myLeaseTimerThread.setDaemon (true);
		myLeaseTimerThread.start();

		// Set up channel group.
		myChannelGroup =
			new ChannelGroup
				(new InetSocketAddress (mySchedulerHost, mySchedulerPort),
				 myLog);
		myLog.log (now, "Job Scheduler at " + myChannelGroup.listenAddress());
		myChannelGroup.setConnectListener (new ConnectListener()
			{
			public void nearEndConnected
				(ChannelGroup theChannelGroup,
				 Channel theChannel)
				{
				}
			public void farEndConnected
				(ChannelGroup theChannelGroup,
				 Channel theChannel)
				{
				createJob (theChannel);
				}
			});

		// Set up server for web interface.
		myHttpServer =
			new HttpServer (new InetSocketAddress (myWebHost, myWebPort), myLog)
				{
				protected void process
					(HttpRequest request,
					 HttpResponse response)
					throws IOException
					{
					processHttpRequest (request, response);
					}
				};
		myLog.log (now, "Web interface at " + myHttpServer.getAddress());

		// Log backend nodes.
		for (BackendInfo backend : myBackendInfo)
			{
			myLog.log
				(now,
				 "Backend " + backend.name + " at " + backend.host +
					", " + backend.totalCpus +
					" CPU" + (backend.totalCpus==1?"":"s"));
			}

		// Start accepting jobs.
		myChannelGroup.startListening();
		}

// Hidden operations.

	/**
	 * Create a job associated with the given channel.
	 *
	 * @param  theChannel  Channel for talking to Job Frontend process.
	 */
	private synchronized void createJob
		(Channel theChannel)
		{
		// Create Job Frontend proxy object for the channel.
		JobFrontendRef frontend =
			new JobFrontendProxy (myChannelGroup, theChannel);
		theChannel.info (frontend);

		// Create job information record.
		JobInfo jobinfo = getJobInfo (frontend);

		// Start lease timers.
		jobinfo.renewTimer.start
			(Constants.LEASE_RENEW_INTERVAL,
			 Constants.LEASE_RENEW_INTERVAL);
		jobinfo.expireTimer.start
			(Constants.LEASE_EXPIRE_INTERVAL);
		}

	/**
	 * Run this Job Scheduler.
	 */
	private void run()
		{
		ObjectItemBuf<JobSchedulerMessage> buf =
			ObjectBuf.buffer ((JobSchedulerMessage) null);
		Status status = null;
		JobSchedulerMessage message = null;
		JobFrontendRef frontend = null;

		receiveloop : for (;;)
			{
			// Receive a message from any channel.
			try
				{
				status = myChannelGroup.receive (null, null, buf);
				}
			catch (ChannelGroupClosedException exc)
				{
				// Normal termination.
				break receiveloop;
				}
			catch (Throwable exc)
				{
				myLog.log ("Exception while receiving message", exc);
				break receiveloop;
				}
			message = buf.item;

			// Get job frontend proxy associated with channel.
			frontend = (JobFrontendRef) status.channel.info();

			// Process message.
			try
				{
				message.invoke (this, frontend);
				}
			catch (Throwable exc)
				{
				myLog.log ("Exception while processing message", exc);
				}

			// Enable garbage collection of no-longer-needed objects while
			// waiting to receive next message.
			buf.item = null;
			status = null;
			message = null;
			frontend = null;
			}
		}

// Exported operations.

	/**
	 * Report that a backend node failed.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 * @param  name            Backend node name.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	public synchronized void backendFailed
		(JobFrontendRef theJobFrontend,
		 String name)
		throws IOException
		{
		BackendInfo backendinfo = myNameToBackendMap.get (name);
		if (backendinfo != null)
			{
			long now = System.currentTimeMillis();
			myLog.log (now, "Backend " + name + " failed");
//			if (backendinfo.state != BackendInfo.State.FAILED)
//				{
//				/*TBD*/ Cancel any reserved or running job
//				backendinfo.state = BackendInfo.State.FAILED;
//				backendinfo.stateTime = now;
//				backendinfo.job = null;
//				assignResourcesToJobs (now);
//				}
			}
		}

	/**
	 * Cancel a job.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 * @param  errmsg          Error message string.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	public synchronized void cancelJob
		(JobFrontendRef theJobFrontend,
		 String errmsg)
		throws IOException
		{
		JobInfo jobinfo = getJobInfo (theJobFrontend);
		doCancelJob (System.currentTimeMillis(), jobinfo, errmsg);
		}

	/**
	 * Report that a job finished.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	public synchronized void jobFinished
		(JobFrontendRef theJobFrontend)
		throws IOException
		{
		JobInfo jobinfo = getJobInfo (theJobFrontend);
		doFinishJob (System.currentTimeMillis(), jobinfo);
		}

	/**
	 * Renew the lease on a job.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	public synchronized void renewLease
		(JobFrontendRef theJobFrontend)
		throws IOException
		{
		JobInfo jobinfo = getJobInfo (theJobFrontend);
		jobinfo.expireTimer.start (Constants.LEASE_EXPIRE_INTERVAL);
		}

	/**
	 * Report a comment for a process.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 * @param  rank            Process rank.
	 * @param  comment         Comment string.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	public synchronized void reportComment
		(JobFrontendRef theJobFrontend,
		 int rank,
		 String comment)
		{
		JobInfo jobinfo = getJobInfo (theJobFrontend);
		jobinfo.comment[rank] = comment;
		}

	/**
	 * Request that a job be scheduled.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 * @param  username        User name.
	 * @param  Nn              Number of backend nodes.
	 * @param  Np              Number of processes.
	 * @param  Nt              Number of CPUs per process. 0 means "all CPUs."
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	public synchronized void requestJob
		(JobFrontendRef theJobFrontend,
		 String username,
		 int Nn,
		 int Np,
		 int Nt)
		throws IOException
		{
		JobInfo jobinfo = getJobInfo (theJobFrontend);
		long now = System.currentTimeMillis();
		myLog.log
			(now,
			 "Job " + jobinfo.jobnum + " queued, username=" + username +
				", nn=" + Nn + ", np=" + Np + ", nt=" + Nt);

		// Record job parameters.
		jobinfo.username = username;
		jobinfo.Nn = Math.min (Nn, Np);
		jobinfo.Np = Np;
		jobinfo.Nt = Nt;
		jobinfo.backend = new BackendInfo [Np];
		jobinfo.cpus = new int [Np];
		jobinfo.comment = new String [Np];
		for (int i = 0; i < Np; ++ i) jobinfo.comment[i] = "";

		// If the cluster doesn't have enough resources, cancel the job.
		if (! enoughResourcesForJob (jobinfo.Nn, jobinfo.Np, jobinfo.Nt))
			{
			doCancelJobTooFewResources (now, jobinfo);
			return;
			}

		// Add job to queue of waiting jobs.
		myWaitingJobList.add (jobinfo);

		// Inform job frontend of job number.
		theJobFrontend.assignJobNumber (this, jobinfo.jobnum, myFrontendHost);

		// Assign idle nodes to waiting jobs.
		assignResourcesToJobs (now);
		}

	/**
	 * Close communication with this Job Scheduler.
	 */
	public void close()
		{
		}

// More hidden operations.

	/**
	 * Take action when a job's lease renewal timer times out.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private synchronized void renewTimeout
		(Timer theTimer,
		 JobFrontendRef theJobFrontend)
		throws IOException
		{
		if (theTimer.isTriggered())
			{
			theJobFrontend.renewLease (this);
			}
		}

	/**
	 * Take action when a job's lease expiration timer times out.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private synchronized void expireTimeout
		(Timer theTimer,
		 JobFrontendRef theJobFrontend)
		throws IOException
		{
		if (theTimer.isTriggered())
			{
			JobInfo jobinfo = getJobInfo (theJobFrontend);
			doCancelJob
				(System.currentTimeMillis(),
				 jobinfo,
				 "Job frontend lease expired");
			}
		}

	/**
	 * Take action when a job's maximum job time timer times out.
	 *
	 * @param  theJobFrontend  Job frontend that is calling this method.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private synchronized void jobTimeout
		(Timer theTimer,
		 JobFrontendRef theJobFrontend)
		throws IOException
		{
		if (theTimer.isTriggered())
			{
			JobInfo jobinfo = getJobInfo (theJobFrontend);
			String errmsg =
				"Maximum job time (" + myJobTime + " seconds) exceeded";
			jobinfo.frontend.cancelJob (this, errmsg);
			doCancelJob (System.currentTimeMillis(), jobinfo, errmsg);
			}
		}

	/**
	 * Get the job info record associated with the given job frontend.
	 *
	 * @param  frontend  Job frontend.
	 *
	 * @return  Job info record.
	 */
	private JobInfo getJobInfo
		(JobFrontendRef frontend)
		{
		final JobFrontendRef fe = frontend;
		JobInfo jobinfo = myFrontendToJobMap.get (frontend);
		if (jobinfo == null)
			{
			jobinfo = new JobInfo
				(/*jobnum   */ myNextJobNumber ++,
				 /*state    */ JobInfo.State.WAITING,
				 /*stateTime*/ System.currentTimeMillis(),
				 /*username */ null,
				 /*Nn       */ 0,
				 /*Np       */ 0,
				 /*Nt       */ 0,
				 /*count    */ 0,
				 /*backend  */ null,
				 /*cpus     */ null,
				 /*nodeCount*/ 0,
				 /*frontend */ fe,
				 /*renewTimer*/
					myLeaseTimerThread.createTimer (new TimerTask()
						{
						public void action (Timer theTimer)
							{
							try
								{
								renewTimeout (theTimer, fe);
								}
							catch (Throwable exc)
								{
								myLog.log (exc);
								}
							}
						}),
				 /*expireTimer*/
					myLeaseTimerThread.createTimer (new TimerTask()
						{
						public void action (Timer theTimer)
							{
							try
								{
								expireTimeout (theTimer, fe);
								}
							catch (Throwable exc)
								{
								myLog.log (exc);
								}
							}
						}),
				 /*jobTimer*/
					myLeaseTimerThread.createTimer (new TimerTask()
						{
						public void action (Timer theTimer)
							{
							try
								{
								jobTimeout (theTimer, fe);
								}
							catch (Throwable exc)
								{
								myLog.log (exc);
								}
							}
						}));
			myFrontendToJobMap.put (frontend, jobinfo);
			}
		return jobinfo;
		}

	/**
	 * Finish the given job.
	 *
	 * @param  now      Current time.
	 * @param  jobinfo  Job info record.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private void doFinishJob
		(long now,
		 JobInfo jobinfo)
		throws IOException
		{
		myLog.log (now, "Job " + jobinfo.jobnum + " finished");
		doCleanupJob (now, jobinfo);
		}

	/**
	 * Cancel the given job.
	 *
	 * @param  now      Current time.
	 * @param  jobinfo  Job info record.
	 * @param  errmsg   Error message.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private void doCancelJob
		(long now,
		 JobInfo jobinfo,
		 String errmsg)
		throws IOException
		{
		myLog.log (now, "Job " + jobinfo.jobnum + " canceled: " + errmsg);
		doCleanupJob (now, jobinfo);
		}

	/**
	 * Cancel the given job because of too few resources.
	 *
	 * @param  now      Current time.
	 * @param  jobinfo  Job info record.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private void doCancelJobTooFewResources
		(long now,
		 JobInfo jobinfo)
		throws IOException
		{
		String errmsg;
		if (jobinfo.Nt == 0)
			{
			errmsg =
				"Too few resources available to assign " +
				jobinfo.Nn + " node" + (jobinfo.Nn==1?"":"s") + " and " +
				jobinfo.Np + " process" + (jobinfo.Np==1?"":"es");
			}
		else
			{
			errmsg =
				"Too few resources available to assign " +
				jobinfo.Nn + " node" + (jobinfo.Nn==1?"":"s") + ", " +
				jobinfo.Np + " process" + (jobinfo.Np==1?"":"es") + ", and " +
				jobinfo.Nt + " CPU" + (jobinfo.Nt==1?"":"s") + " per process";
			}
		jobinfo.frontend.cancelJob (this, errmsg);
		doCancelJob (now, jobinfo, errmsg);
		}

	/**
	 * Clean up the given job.
	 *
	 * @param  now      Current time.
	 * @param  jobinfo  Job info record.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private void doCleanupJob
		(long now,
		 JobInfo jobinfo)
		throws IOException
		{
		// Stop lease timers.
		jobinfo.renewTimer.stop();
		jobinfo.expireTimer.stop();
		jobinfo.jobTimer.stop();

		// Stop communication with job frontend.
		jobinfo.frontend.close();

		// Remove job from queues.
		myFrontendToJobMap.remove (jobinfo.frontend);
		myRunningJobList.remove (jobinfo);
		myWaitingJobList.remove (jobinfo);

		// Make each of the job's nodes idle (but not failed nodes).
		for (int i = 0; i < jobinfo.count; ++ i)
			{
			BackendInfo backendinfo = jobinfo.backend[i];
			if (backendinfo.state != BackendInfo.State.FAILED)
				{
				backendinfo.state = BackendInfo.State.IDLE;
				backendinfo.stateTime = now;
				backendinfo.job = null;
				}
			}

		// Update total compute time.
		myTotalComputeTime += (now - jobinfo.stateTime);

		// Assign idle nodes to waiting jobs.
		assignResourcesToJobs (now);
		}

	/**
	 * Assign idle nodes to waiting jobs.
	 *
	 * @param  now  Current time.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private void assignResourcesToJobs
		(long now)
		throws IOException
		{
		// List of jobs to be canceled.
		List<JobInfo> cancelList = new LinkedList<JobInfo>();

		// Decide what to do with each waiting job.
		Iterator<JobInfo> iter = myWaitingJobList.iterator();
		jobLoop : while (iter.hasNext())
			{
			JobInfo jobinfo = iter.next();

			// If the cluster doesn't have enough resources, don't try to
			// reserve any.
			if (! enoughResourcesForJob (jobinfo.Nn, jobinfo.Np, jobinfo.Nt))
				{
				iter.remove();
				cancelList.add (jobinfo);
				continue jobLoop;
				}

			// Used to decide how many processes for each node.
			int Np_div_Nn = jobinfo.Np / jobinfo.Nn;
			int Np_rem_Nn = jobinfo.Np % jobinfo.Nn;

			// Reserve idle nodes for this job until there are no more idle
			// nodes or this job has all the nodes it needs.
			int be = myNextBackendNumber;
			do
				{
				// Decide how many processes for this node.
				int Nproc = Np_div_Nn;
				if (jobinfo.nodeCount < Np_rem_Nn) ++ Nproc;

				// Reserve this node only if it is idle and it has enough CPUs.
				BackendInfo backendinfo = myBackendInfo[be];
				if (backendinfo.state == BackendInfo.State.IDLE &&
						backendinfo.totalCpus >= Nproc)
					{
					// Reserve node.
					backendinfo.state = BackendInfo.State.RESERVED;
					backendinfo.stateTime = now;
					backendinfo.job = jobinfo;

					// Used to decide how many CPUs for each process.
					int Nt_div_Nproc = backendinfo.totalCpus / Nproc;
					int Nt_rem_Nproc = backendinfo.totalCpus % Nproc;

					// Assign Np processes.
					for (int i = 0; i < Nproc; ++ i)
						{
						// Decide how many CPUs for this process.
						int Ncpus = jobinfo.Nt;
						if (Ncpus == 0)
							{
							Ncpus = Nt_div_Nproc;
							if (i < Nt_rem_Nproc) ++ Ncpus;
							}

						// Log information.
						myLog.log
							(now,
							 "Job " + jobinfo.jobnum + " assigned " +
							 backendinfo.name + ", rank=" + jobinfo.count +
							 ", CPUs=" + Ncpus);

						// Record information about process.
						jobinfo.backend[jobinfo.count] = backendinfo;
						jobinfo.cpus[jobinfo.count] = Ncpus;
						++ jobinfo.count;

						// Inform Job Frontend.
						jobinfo.frontend.assignBackend
							(/*theJobScheduler*/ this,
							 /*name           */ backendinfo.name,
							 /*host           */ backendinfo.host,
							 /*jvm            */ backendinfo.jvm,
							 /*classpath      */ backendinfo.classpath,
							 /*jvmflags       */ backendinfo.jvmflags,
							 /*shellCommand   */ backendinfo.shellCommand,
							 /*Nt             */ Ncpus);
						}

					// Assign one node.
					++ jobinfo.nodeCount;
					}

				// Consider next node.
				be = (be + 1) % myBackendCount;
				}
			while (be != myNextBackendNumber && jobinfo.count < jobinfo.Np);
			myNextBackendNumber = be;

			// If this job now has Np processes, start running this job.
			if (jobinfo.count == jobinfo.Np)
				{
				// Log information.
				myLog.log (now, "Job " + jobinfo.jobnum + " started");

				// Mark job as running.
				iter.remove();
				myRunningJobList.add (jobinfo);
				jobinfo.state = JobInfo.State.RUNNING;
				jobinfo.stateTime = now;

				// Mark all the job's nodes as running.
				for (BackendInfo backendinfo : jobinfo.backend)
					{
					backendinfo.state = BackendInfo.State.RUNNING;
					backendinfo.stateTime = now;
					}

				// If the Job Scheduler is imposing a maximum job time, start
				// job timer.
				if (myJobTime > 0)
					{
					jobinfo.jobTimer.start (myJobTime * 1000L);
					}
				}

			// If this job does not yet have Np processes, don't schedule any
			// further jobs.
			else
				{
				break jobLoop;
				}
			}

		// Cancel jobs for which there are insufficient resources.
		for (JobInfo jobinfo : cancelList)
			{
			doCancelJobTooFewResources (now, jobinfo);
			}
		}

	/**
	 * Determine if there are enough resources to run a job.
	 *
	 * @param  Nn  Number of backend nodes required.
	 * @param  Np  Number of processes required.
	 * @param  Nt  Number of CPUs per process required. 0 means "all CPUs."
	 *
	 * @return  True if there are enough resources, false if not.
	 */
	private boolean enoughResourcesForJob
		(int Nn,
		 int Np,
		 int Nt)
		{
		// Determine worst-case processes per node.
		int Ppn = (Np + Nn - 1) / Nn;

		// If number of CPUs per process is "all CPUs," assume one CPU per
		// process.
		if (Nt == 0) Nt = 1;

		// Count how many nodes meet the requirements.
		int nodeCount = 0;
		for (BackendInfo backendinfo : myBackendInfo)
			{
			// The node must not have failed.
			if (backendinfo.state != BackendInfo.State.FAILED &&

			// The node must have at least Ppn*Nt CPUs.
					backendinfo.totalCpus >= Ppn*Nt)
				{
				// The node meets the requirements.
				++ nodeCount;
				}
			}

		// Return outcome.
		return nodeCount >= Nn;
		}

	/**
	 * Process the given HTTP request.
	 *
	 * @param  request   HTTP request.
	 * @param  response  HTTP response.
	 *
	 * @exception  IOException
	 *     Thrown if an I/O error occurred.
	 */
	private void processHttpRequest
		(HttpRequest request,
		 HttpResponse response)
		throws IOException
		{
		long now = System.currentTimeMillis();

		// Reject an invalid HTTP request.
		if (! request.isValid())
			{
			response.setStatusCode
				(HttpResponse.Status.STATUS_400_BAD_REQUEST);
			PrintWriter out = response.getPrintWriter();
			printStatusHtmlStart (out, now);
			out.println ("<P>");
			out.println ("400 Bad Request");
			printStatusHtmlEnd (out);
			}

		// Reject all methods except GET.
		else if (! request.getMethod().equals (HttpRequest.GET_METHOD))
			{
			response.setStatusCode
				(HttpResponse.Status.STATUS_501_NOT_IMPLEMENTED);
			PrintWriter out = response.getPrintWriter();
			printStatusHtmlStart (out, now);
			out.println ("<P>");
			out.println ("501 Not Implemented");
			printStatusHtmlEnd (out);
			}

		// Print the status document.
		else if (request.getUri().equals ("/") ||
					request.getUri().equals ("/?"))
			{
			PrintWriter out = response.getPrintWriter();
			printStatusHtmlStart (out, now);
			printStatusHtmlBody (out, now);
			printStatusHtmlEnd (out);
			}

		// Print the debug document.
		else if (request.getUri().equals ("/debug"))
			{
			PrintWriter out = response.getPrintWriter();
			printDebugHtmlStart (out, now);
			printDebugHtmlBody (out);
			printStatusHtmlEnd (out);
			}

		// Print the detailed job status document.
		else if (request.getUri().startsWith ("/job/"))
			{
			String jobString = request.getUri().substring (5);
			try
				{
				int jobNum = Integer.parseInt (jobString);
				PrintWriter out = response.getPrintWriter();
				printJobDetailHtmlStart (out, now, jobNum);
				printJobDetailHtmlBody (out, now, jobNum);
				printStatusHtmlEnd (out);
				}
			catch (NumberFormatException exc)
				{
				PrintWriter out = response.getPrintWriter();
				printErrorHtmlStart (out);
				out.printf ("<P>Invalid job number \"%s\"</P>\n", jobString);
				printErrorHtmlEnd (out);
				}
			}

		// Reject all other URIs.
		else
			{
			response.setStatusCode
				(HttpResponse.Status.STATUS_404_NOT_FOUND);
			PrintWriter out = response.getPrintWriter();
			printErrorHtmlStart (out);
			out.println ("<P>404 Not Found</P>");
			printErrorHtmlEnd (out);
			}

		// Send the response.
		response.close();
		}

	/**
	 * Print the start of the status HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 * @param  now  Current time.
	 */
	private void printStatusHtmlStart
		(PrintWriter out,
		 long now)
		{
		out.println ("<HTML>");
		out.println ("<HEAD>");
		out.print   ("<TITLE>");
		out.print   (myClusterName);
		out.println ("</TITLE>");
		out.print   ("<META HTTP-EQUIV=\"refresh\" CONTENT=\"20;url=");
		printWebInterfaceURL (out);
		out.println ("\">");
		out.println ("<STYLE TYPE=\"text/css\">");
		out.println ("<!--");
		out.println ("* {font-family: Arial, Helvetica, Sans-Serif;}");
		out.println ("body {font-size: small;}");
		out.println ("h1 {font-size: 140%; font-weight: bold;}");
		out.println ("table {font-size: 100%;}");
		out.println ("-->");
		out.println ("</STYLE>");
		out.println ("</HEAD>");
		out.println ("<BODY>");
		out.print   ("<H1>");
		out.print   (myClusterName);
		out.println ("</H1>");
		out.println ("<P>");
		out.print   ("<FORM ACTION=\"");
		printWebInterfaceURL (out);
		out.println ("\" METHOD=\"get\">");
		out.println ("<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>");
		out.println ("<TR>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"center\">");
		out.print   ("<INPUT TYPE=\"submit\" VALUE=\"Refresh\">");
		out.println ("</TD>");
		out.println ("<TD WIDTH=20> </TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"center\">");
		out.print   (new Date (now));
		out.print   (" -- ");
		out.print   (Version.PJ_VERSION);
		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");
		out.println ("</FORM>");
		}

	/**
	 * Print the body of the status HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 * @param  now  Current time.
	 */
	private synchronized void printStatusHtmlBody
		(PrintWriter out,
		 long now)
		{
		out.println ("<P>");
		out.println ("<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"center\" VALIGN=\"top\">");

		out.println ("Nodes");
		out.println ("<TABLE BORDER=1 CELLPADDING=3 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");

		out.println ("<TABLE BORDER=0 CELLPADDING=3 CELLSPACING=0>");
		printBackendLabels (out);
		int i = 0;
		for (BackendInfo backend : myBackendInfo)
			{
			printBackendInfo (out, now, backend, i);
			++ i;
			}
		out.println ("</TABLE>");

		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");

		out.println ("</TD>");
		out.println ("<TD WIDTH=40> </TD>");
		out.println ("<TD ALIGN=\"center\" VALIGN=\"top\">");

		out.println ("Jobs");
		out.println ("<TABLE BORDER=1 CELLPADDING=3 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");

		out.println ("<TABLE BORDER=0 CELLPADDING=3 CELLSPACING=0>");
		printJobLabels (out);
		i = 0;
		for (JobInfo job : myRunningJobList)
			{
			printJobInfo (out, now, job, i);
			++ i;
			}
		for (JobInfo job : myWaitingJobList)
			{
			printJobInfo (out, now, job, i);
			++ i;
			}
		out.println ("</TABLE>");

		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");

		printTotalComputeTime (out);
		out.print ("<BR>");
		printJobCount (out);
		out.println ("<BR>Since " + new Date (myStartDateTime));

		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");
		}

	/**
	 * Print the job count.
	 *
	 * @param  out  Print writer.
	 */
	private void printJobCount
		(PrintWriter out)
		{
		if (myNextJobNumber == 2)
			{
			out.print ("1 job");
			}
		else
			{
			out.print (myNextJobNumber-1);
			out.print (" jobs");
			}
		out.println (" served");
		}

	/**
	 * Print the total CPU time.
	 *
	 * @param  out  Print writer.
	 */
	private void printTotalComputeTime
		(PrintWriter out)
		{
		if (myTotalComputeTime < 1000000L)
			{
			out.print (myTotalComputeTime / 1000L);
			}
		else if (myTotalComputeTime < 1000000000L)
			{
			out.print ("Over ");
			out.print (myTotalComputeTime / 1000000L);
			out.print (" thousand");
			}
		else if (myTotalComputeTime < 1000000000000L)
			{
			out.print ("Over ");
			out.print (myTotalComputeTime / 1000000000L);
			out.print (" million");
			}
		else if (myTotalComputeTime < 1000000000000000L)
			{
			out.print ("Over ");
			out.print (myTotalComputeTime / 1000000000000L);
			out.print (" billion");
			}
		else
			{
			out.print ("Over ");
			out.print (myTotalComputeTime / 1000000000000000L);
			out.print (" trillion");
			}
		out.println (" CPU seconds served");
		}

	/**
	 * Print the end of the status HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printStatusHtmlEnd
		(PrintWriter out)
		{
		out.println ("<P>");
		out.println ("<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.println ("Job queue web interface:&nbsp;&nbsp;");
		out.println ("</TD>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<A HREF=\"");
		printWebInterfaceURL (out);
		out.print   ("\">");
		printWebInterfaceURL (out);
		out.println ("</A>");
		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.println ("Powered by Parallel Java:&nbsp;&nbsp;");
		out.println ("</TD>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.println ("<A HREF=\"http://www.cs.rit.edu/~ark/pj.shtml\">http://www.cs.rit.edu/~ark/pj.shtml</A>");
		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.println ("Developed by Alan Kaminsky:&nbsp;&nbsp;");
		out.println ("</TD>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.println ("<A HREF=\"http://www.cs.rit.edu/~ark/\">http://www.cs.rit.edu/~ark/</A>");
		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");
		out.println ("</BODY>");
		out.println ("</HTML>");
		}

	/**
	 * Print the web interface URL on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printWebInterfaceURL
		(PrintWriter out)
		{
		out.printf ("http://%s:%d/", myWebHost, myWebPort);
		}

	/**
	 * Print the URL for the given job number on the given print writer.
	 *
	 * @param  out     Print writer.
	 * @param  jobNum  Job number.
	 */
	private void printJobNumberURL
		(PrintWriter out,
		 int jobNum)
		{
		out.printf ("http://%s:%d/job/%d", myWebHost, myWebPort, jobNum);
		}

	/**
	 * Print a link for the given job number on the given print writer.
	 *
	 * @param  out     Print writer.
	 * @param  jobNum  Job number.
	 */
	private void printJobNumberLink
		(PrintWriter out,
		 int jobNum)
		{
		out.printf ("<A HREF=\"http://%s:%d/job/%d\">&nbsp;%d&nbsp;</A>",
			myWebHost, myWebPort, jobNum, jobNum);
		}

	/**
	 * Print the difference between the given times on the given print writer.
	 *
	 * @param  out   Print writer.
	 * @param  now   Time now.
	 * @param  then  Time then.
	 */
	private void printDeltaTime
		(PrintWriter out,
		 long now,
		 long then)
		{
		out.print ((now - then + 500L) / 1000L);
		out.print (" sec");
		}

	/**
	 * Print the backend labels on the given print writer.
	 *
	 * @param  out      Print writer.
	 */
	private void printBackendLabels
		(PrintWriter out)
		{
		out.println ("<TR BGCOLOR=\"#E8E8E8\">");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Node</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>CPUs</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Status</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Job</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Time</I>");
		out.println ("</TD>");
		out.println ("</TR>");
		}

	/**
	 * Print the given backend info on the given print writer.
	 *
	 * @param  out      Print writer.
	 * @param  now      Current time.
	 * @param  backend  Backend info.
	 * @param  i        Even = white background, odd = gray background.
	 */
	private void printBackendInfo
		(PrintWriter out,
		 long now,
		 BackendInfo backend,
		 int i)
		{
		out.print   ("<TR BGCOLOR=\"#");
		out.print   (i%2==0 ? "FFFFFF" : "E8E8E8");
		out.println ("\">");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (backend.name);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (backend.totalCpus);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (backend.state == BackendInfo.State.FAILED)
			{
			out.print ("<FONT COLOR=\"#FF0000\"><B>");
			out.print (backend.state);
			out.print ("</B></FONT>");
			}
		else
			{
			out.print (backend.state);
			}
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (backend.job != null)
			{
			printJobNumberLink (out, backend.job.jobnum);
			}
		else
			{
			out.print ("&nbsp;");
			}
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (backend.job != null)
			{
			printDeltaTime (out, now, backend.job.stateTime);
			}
		else
			{
			out.print ("&nbsp;");
			}
		out.println ("</TD>");
		out.println ("</TR>");
		}

	/**
	 * Print the job labels on the given print writer.
	 *
	 * @param  out      Print writer.
	 */
	private void printJobLabels
		(PrintWriter out)
		{
		out.println ("<TR BGCOLOR=\"#E8E8E8\">");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Job</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>User</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>nn</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>np</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>nt</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Rank</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Node</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>CPUs</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Status</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Time</I>");
		out.println ("</TD>");
		out.println ("</TR>");
		}

	/**
	 * Print the given job info on the given print writer.
	 *
	 * @param  out  Print writer.
	 * @param  now  Current time.
	 * @param  job  Job info.
	 * @param  i    Even = white background, odd = gray background.
	 */
	private void printJobInfo
		(PrintWriter out,
		 long now,
		 JobInfo job,
		 int i)
		{
		boolean first;
		out.print   ("<TR BGCOLOR=\"#");
		out.print   (i%2==0 ? "FFFFFF" : "E8E8E8");
		out.println ("\">");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		printJobNumberLink (out, job.jobnum);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (job.username);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (job.Nn);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (job.Np);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (job.Nt == 0 ? "all" : ""+job.Nt);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (job.count == 0)
			{
			out.print ("&nbsp;");
			}
		else
			{
			for (int j = 0; j < job.count; ++ j)
				{
				if (j > 0) out.print ("<BR>");
				out.print (j);
				}
			}
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (job.count == 0)
			{
			out.print ("&nbsp;");
			}
		else
			{
			for (int j = 0; j < job.count; ++ j)
				{
				if (j > 0) out.print ("<BR>");
				out.print (job.backend[j].name);
				}
			}
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (job.count == 0)
			{
			out.print ("&nbsp;");
			}
		else
			{
			for (int j = 0; j < job.count; ++ j)
				{
				if (j > 0) out.print ("<BR>");
				out.print (job.cpus[j]);
				}
			}
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   (job.state);
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		printDeltaTime (out, now, job.stateTime);
		out.println ("</TD>");
		out.println ("</TR>");
		}

	/**
	 * Print the start of the debug HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printDebugHtmlStart
		(PrintWriter out,
		 long now)
		{
		out.println ("<HTML>");
		out.println ("<HEAD>");
		out.print   ("<TITLE>");
		out.print   (myClusterName);
		out.println ("</TITLE>");
		out.println ("<STYLE TYPE=\"text/css\">");
		out.println ("<!--");
		out.println ("* {font-family: Arial, Helvetica, Sans-Serif;}");
		out.println ("body {font-size: small;}");
		out.println ("h1 {font-size: 140%; font-weight: bold;}");
		out.println ("table {font-size: 100%;}");
		out.println ("-->");
		out.println ("</STYLE>");
		out.println ("</HEAD>");
		out.println ("<BODY>");
		out.print   ("<H1>");
		out.print   (myClusterName);
		out.println ("</H1>");
		out.println ("<P>");
		out.print   (new Date (now));
		out.print   (" -- ");
		out.print   (Version.PJ_VERSION);
		out.println ("</P>");
		}

	/**
	 * Print the body of the debug HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printDebugHtmlBody
		(PrintWriter out)
		{
		out.println ("<P>");
		out.println ("<HR/>");
		out.println ("<H3>Thread Dump</H3>");
		out.println ("</P>");
		Map<Thread,StackTraceElement[]> traces = Thread.getAllStackTraces();
		for (Map.Entry<Thread,StackTraceElement[]> entry : traces.entrySet())
			{
			Thread thread = entry.getKey();
			out.println ("<P>");
			out.print   ("Name: ");
			out.print   (thread.getName());
			out.println ("&nbsp;&nbsp;&nbsp;&nbsp;");
			out.print   (" ID: ");
			out.print   (thread.getId());
			out.println ("&nbsp;&nbsp;&nbsp;&nbsp;");
			out.print   (" Daemon: ");
			out.print   (thread.isDaemon() ? "yes" : "no");
			out.println ("&nbsp;&nbsp;&nbsp;&nbsp;");
			out.print   (" State: ");
			out.print   (thread.getState());
			out.println ("&nbsp;&nbsp;&nbsp;&nbsp;");
			out.print   (" Priority: ");
			out.print   (thread.getPriority());
			out.println ("&nbsp;&nbsp;&nbsp;&nbsp;");
			out.print   (" Thread Group: ");
			out.print   (thread.getThreadGroup().getName());
			out.println ();
			for (StackTraceElement element : entry.getValue())
				{
				out.print   ("<BR/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
				out.println (element);
				}
			out.println ("</P>");
			}
		out.println ("<P>");
		out.println ("<HR/>");
		out.println ("</P>");
		}

	/**
	 * Print the start of the detailed job status HTML document on the given
	 * print writer.
	 *
	 * @param  out     Print writer.
	 * @param  now     Current time.
	 * @param  jobNum  Job number.
	 */
	private void printJobDetailHtmlStart
		(PrintWriter out,
		 long now,
		 int jobNum)
		{
		out.println ("<HTML>");
		out.println ("<HEAD>");
		out.print   ("<TITLE>");
		out.print   (myClusterName);
		out.println ("</TITLE>");
		out.print   ("<META HTTP-EQUIV=\"refresh\" CONTENT=\"20;url=");
		printJobNumberURL (out, jobNum);
		out.println ("\">");
		out.println ("<STYLE TYPE=\"text/css\">");
		out.println ("<!--");
		out.println ("* {font-family: Arial, Helvetica, Sans-Serif;}");
		out.println ("body {font-size: small;}");
		out.println ("h1 {font-size: 140%; font-weight: bold;}");
		out.println ("table {font-size: 100%;}");
		out.println ("-->");
		out.println ("</STYLE>");
		out.println ("</HEAD>");
		out.println ("<BODY>");
		out.print   ("<H1>");
		out.print   (myClusterName);
		out.println ("</H1>");
		out.println ("<P>");
		out.print   ("<FORM ACTION=\"");
		printJobNumberURL (out, jobNum);
		out.println ("\" METHOD=\"get\">");
		out.println ("<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>");
		out.println ("<TR>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"center\">");
		out.print   ("<INPUT TYPE=\"submit\" VALUE=\"Refresh\">");
		out.println ("</TD>");
		out.println ("<TD WIDTH=20> </TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"center\">");
		out.print   (new Date (now));
		out.print   (" -- ");
		out.print   (Version.PJ_VERSION);
		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");
		out.println ("</FORM>");
		}

	/**
	 * Print the body of the detailed job status HTML document on the given
	 * print writer.
	 *
	 * @param  out     Print writer.
	 * @param  now     Current time.
	 * @param  jobNum  Job number.
	 */
	private synchronized void printJobDetailHtmlBody
		(PrintWriter out,
		 long now,
		 int jobNum)
		{
		JobInfo jobInfo = null;

		// Find job info.
		for (JobInfo job : myRunningJobList)
			{
			if (job.jobnum == jobNum)
				{
				jobInfo = job;
				break;
				}
			}
		if (jobInfo == null)
			{
			for (JobInfo job : myWaitingJobList)
				{
				if (job.jobnum == jobNum)
					{
					jobInfo = job;
					break;
					}
				}
			}

		out.println ("<P>");
		out.println ("<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\"><B>Job:</B></TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.printf  ("<TD ALIGN=\"left\" VALIGN=\"top\"><B>%d</B></TD>",
			jobNum);
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">User:</TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.printf  ("<TD ALIGN=\"left\" VALIGN=\"top\">%s</TD>",
			jobInfo == null ? " " : jobInfo.username);
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">Nodes (nn):</TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.printf  ("<TD ALIGN=\"left\" VALIGN=\"top\">%s</TD>",
			jobInfo == null ? " " : ""+jobInfo.Nn);
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">Processes (np):</TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.printf  ("<TD ALIGN=\"left\" VALIGN=\"top\">%s</TD>",
			jobInfo == null ? " " : ""+jobInfo.Np);
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">Threads (nt):</TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.printf  ("<TD ALIGN=\"left\" VALIGN=\"top\">%s</TD>",
			jobInfo == null ? " " : jobInfo.Nt == 0 ? "All" : ""+jobInfo.Nt);
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">Status:</TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.printf  ("<TD ALIGN=\"left\" VALIGN=\"top\">%s</TD>",
			jobInfo == null ? "Not in queue" : jobInfo.state);
		out.println ("</TR>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">Time:</TD>");
		out.println ("<TD WIDTH=10> </TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		if (jobInfo == null)
			{
			out.print (" ");
			}
		else
			{
			printDeltaTime (out, now, jobInfo.stateTime);
			}
		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");
		out.println ("</P>");

		if (jobInfo == null || jobInfo.count == 0) return;

		out.println ("<P>");
		out.println ("<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"center\" VALIGN=\"top\">");

		out.println ("Processes");
		out.println ("<TABLE BORDER=1 CELLPADDING=3 CELLSPACING=0>");
		out.println ("<TR>");
		out.println ("<TD ALIGN=\"left\" VALIGN=\"top\">");

		out.println ("<TABLE BORDER=0 CELLPADDING=3 CELLSPACING=0>");
		printJobDetailProcessLabels (out);
		for (int i = 0; i < jobInfo.count; ++ i)
			{
			printJobDetailProcessInfo (out, jobInfo, i);
			}
		out.println ("</TABLE>");

		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");

		out.println ("</TD>");
		out.println ("</TR>");
		out.println ("</TABLE>");
		out.println ("</P>");
		}

	/**
	 * Print the detailed job status process labels on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printJobDetailProcessLabels
		(PrintWriter out)
		{
		out.println ("<TR BGCOLOR=\"#E8E8E8\">");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Rank</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Node</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>CPUs</I>");
		out.println ("</TD>");
		out.print   ("<TD ALIGN=\"left\" VALIGN=\"top\">");
		out.print   ("<I>Comment</I>");
		out.println ("</TD>");
		out.println ("</TR>");
		}

	/**
	 * Print the detailed job status process information on the given print
	 * writer.
	 *
	 * @param  out      Print writer.
	 * @param  jobInfo  Job info.
	 * @param  rank     Process rank.
	 */
	private void printJobDetailProcessInfo
		(PrintWriter out,
		 JobInfo jobInfo,
		 int rank)
		{
		out.printf ("<TR BGCOLOR=\"#%s\">\n",
			rank%2 == 0 ? "FFFFFF" : "E8E8E8");
		out.printf ("<TD ALIGN=\"left\" VALIGN=\"top\">%d&nbsp;&nbsp;</TD>\n",
			rank);
		out.printf ("<TD ALIGN=\"left\" VALIGN=\"top\">%s&nbsp;&nbsp;</TD>\n",
			jobInfo.backend[rank].name);
		out.printf ("<TD ALIGN=\"left\" VALIGN=\"top\">%d&nbsp;&nbsp;</TD>\n",
			jobInfo.cpus[rank]);
		out.printf ("<TD ALIGN=\"left\" VALIGN=\"top\">%s</TD>\n",
			jobInfo.comment[rank]);
		out.println ("</TR>");
		}

	/**
	 * Print the start of the error HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printErrorHtmlStart
		(PrintWriter out)
		{
		out.println ("<HTML>");
		out.println ("<HEAD>");
		out.print   ("<TITLE>");
		out.print   (myClusterName);
		out.println ("</TITLE>");
		out.println ("<STYLE TYPE=\"text/css\">");
		out.println ("<!--");
		out.println ("* {font-family: Arial, Helvetica, Sans-Serif;}");
		out.println ("body {font-size: small;}");
		out.println ("h1 {font-size: 140%; font-weight: bold;}");
		out.println ("table {font-size: 100%;}");
		out.println ("-->");
		out.println ("</STYLE>");
		out.println ("</HEAD>");
		out.println ("<BODY>");
		}

	/**
	 * Print the end of the error HTML document on the given print writer.
	 *
	 * @param  out  Print writer.
	 */
	private void printErrorHtmlEnd
		(PrintWriter out)
		{
		out.println ("</BODY>");
		out.println ("</HTML>");
		}

	/**
	 * Shut down this Job Scheduler.
	 */
	private void shutdown()
		{
		if (myChannelGroup != null)
			{
			myChannelGroup.close();
			}
		if (myHttpServer != null)
			{
			try { myHttpServer.close(); } catch (IOException exc) {}
			}
		myLog.log ("Stopped");
		}

// Main program.

	/**
	 * Job Scheduler main program.
	 */
	public static void main
		(String[] args)
		throws Exception
		{
		if (args.length != 1)
			{
			System.err.println
				("Usage: java edu.rit.pj.cluster.JobScheduler <configfile>");
			System.exit (1);
			}

		JobScheduler scheduler = new JobScheduler (args[0]);
		scheduler.run();
		}

	}