File: dmtcp_coordinator.cpp

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (1722 lines) | stat: -rw-r--r-- 58,785 bytes parent folder | download
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
/****************************************************************************
 *   Copyright (C) 2006-2013 by Jason Ansel, Kapil Arya, and Gene Cooperman *
 *   jansel@csail.mit.edu, kapil@ccs.neu.edu, gene@ccs.neu.edu              *
 *                                                                          *
 *  This file is part of DMTCP.                                             *
 *                                                                          *
 *  DMTCP is free software: you can redistribute it and/or                  *
 *  modify it under the terms of the GNU Lesser General Public License as   *
 *  published by the Free Software Foundation, either version 3 of the      *
 *  License, or (at your option) any later version.                         *
 *                                                                          *
 *  DMTCP 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 Lesser General Public License for more details.                     *
 *                                                                          *
 *  You should have received a copy of the GNU Lesser General Public        *
 *  License along with DMTCP:dmtcp/src.  If not, see                        *
 *  <http://www.gnu.org/licenses/>.                                         *
 ****************************************************************************/

/****************************************************************************
 * Coordinator code logic:                                                  *
 * main calls eventLoop, a top-level event loop.                            *
 * eventLoop calls:  onConnect, onData, onDisconnect, startCheckpoint       *
 *   when client or dmtcp_command talks to coordinator.                     *
 * onConnect called on msg at listener port.  It passes control to:         *
 *   handleUserCommand, which takes single char arg ('s', 'c', 'k', 'q', ...)*
 * handleUserCommand calls broadcastMessage to send data back               *
 * any message sent by broadcastMessage takes effect only on returning      *
 *   back up to top level monitorSockets                                    *
 * Hence, even for checkpoint, handleUserCommand just changes state,        *
 *   broadcasts an initial checkpoint command, and then returns to top      *
 *   level.  Replies from clients then drive further state changes.         *
 * The prefix command 'b' (blocking) from dmtcp_command modifies behavior   *
 *   of 'c' so that the reply to dmtcp_command happens only when clients    *
 *   are back in RUNNING state.                                             *
 * onData called when a message arrives at a client's port.  It either      *
 *   processes a per-client special request, or continues the protocol      *
 *   for a checkpoint or restart sequence (see below).                      *
 *                                                                          *
 * updateMinimumState() is responsible for keeping track of states.         *
 * The coordinator keeps a ComputationStatus, with minimumState and         *
 *   maximumState for states of all workers, accessed through getStatus()   *
 *   or through minimumState()                                              *
 * The states for a worker (client) are:                                    *
 * Checkpoint: RUNNING -> SUSPENDED -> FD_LEADER_ELECTION -> DRAINED        *
 *       	  -> CHECKPOINTED -> NAME_SERVICE_DATA_REGISTERED           *
 *                -> DONE_QUERYING -> REFILLED -> RUNNING		    *
 * Restart:    RESTARTING -> CHECKPOINTED -> NAME_SERVICE_DATA_REGISTERED   *
 *                -> DONE_QUERYING -> REFILLED -> RUNNING	            *
 * If debugging, set gdb breakpoint on:					    *
 *   DmtcpCoordinator::onConnect					    *
 *   DmtcpCoordinator::onData						    *
 *   DmtcpCoordinator::handleUserCommand				    *
 *   DmtcpCoordinator::broadcastMessage					    *
 ****************************************************************************/

#include <stdlib.h>
#include "dmtcp_coordinator.h"
#include "constants.h"
#include "protectedfds.h"
#include "dmtcpmessagetypes.h"
#include "lookup_service.h"
#include "syscallwrappers.h"
#include "util.h"
#include "restartscript.h"
#include "../jalib/jassert.h"
#include "../jalib/jconvert.h"
#include "../jalib/jtimer.h"
#include "../jalib/jfilesystem.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <algorithm>
#include <iomanip>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#undef min
#undef max

#define BINARY_NAME "dmtcp_coordinator"

using namespace dmtcp;

static const char* theHelpMessage =
  "COMMANDS:\n"
  "  l : List connected nodes\n"
  "  s : Print status message\n"
  "  c : Checkpoint all nodes\n"
  "  i : Print current checkpoint interval\n"
  "      (To change checkpoint interval, use dmtcp_command)\n"
  "  k : Kill all nodes\n"
  "  q : Kill all nodes and quit\n"
  "  ? : Show this message\n"
  "\n"
;

static const char* theUsage =
  "Usage: dmtcp_coordinator [OPTIONS] [port]\n"
  "Coordinates checkpoints between multiple processes.\n\n"
  "Options:\n"
  "  -p, --coord-port PORT_NUM (environment variable DMTCP_COORD_PORT)\n"
  "      Port to listen on (default: " STRINGIFY(DEFAULT_PORT) ")\n"
  "  --port-file filename\n"
  "      File to write listener port number.\n"
  "      (Useful with '--port 0', which is used to assign a random port)\n"
  "  --ckptdir (environment variable DMTCP_CHECKPOINT_DIR):\n"
  "      Directory to store dmtcp_restart_script.sh (default: ./)\n"
  "  --tmpdir (environment variable DMTCP_TMPDIR):\n"
  "      Directory to store temporary files (default: env var TMDPIR or /tmp)\n"
  "  --exit-on-last\n"
  "      Exit automatically when last client disconnects\n"
  "  --exit-after-ckpt\n"
  "      Kill peer processes of computation after first checkpoint is created\n"
  "  --daemon\n"
  "      Run silently in the background after detaching from the parent process.\n"
  "  -i, --interval (environment variable DMTCP_CHECKPOINT_INTERVAL):\n"
  "      Time in seconds between automatic checkpoints\n"
  "      (default: 0, disabled)\n"
  "  --coord-logfile PATH (environment variable DMTCP_COORD_LOG_FILENAME\n"
  "              Coordinator will dump its logs to the given file\n"
  "  -q, --quiet \n"
  "      Skip startup msg; Skip NOTE msgs; if given twice, also skip WARNINGs\n"
  "  --help:\n"
  "      Print this message and exit.\n"
  "  --version:\n"
  "      Print version information and exit.\n"
  "\n"
  "COMMANDS:\n"
  "      type '?<return>' at runtime for list\n"
  "\n"
  HELP_AND_CONTACT_INFO
  "\n"
;


static int thePort = -1;
static string thePortFile;

static bool exitOnLast = false;
static bool blockUntilDone = false;
static bool exitAfterCkpt = false;
static bool exitAfterCkptOnce = false;
static int blockUntilDoneRemote = -1;
static uint32_t mask = 0;

static DmtcpCoordinator prog;

/* The coordinator can receive a second checkpoint request while processing the
 * first one.  If the second request comes at a point where the coordinator has
 * broadcast DMT_DO_SUSPEND message but the workers haven't replied, the
 * coordinator sends another DMT_DO_SUSPEND message.  The workers, having
 * replied to the first DMTCP_DO_SUSPEND message (by suspending all the user
 * threads), are waiting for the next message (DMT_DO_FD_LEADER_ELECTION or
 * DMT_KILL_PEER), however they receive DMT_DO_SUSPEND message and thus exit()
 * indicating an error.
 * The fix to this problem is to introduce a global
 * variable "workersRunningAndSuspendMsgSent" which, as the name implies,
 * indicates that the DMT_DO_SUSPEND message has been sent and the coordinator
 * is waiting for replies from the workers.  If this variable is set, the
 * coordinator will not process another checkpoint request.
*/
static bool workersRunningAndSuspendMsgSent = false;

static bool killInProgress = false;
static bool uniqueCkptFilenames = false;

/* If dmtcp_launch/dmtcp_restart specifies '-i', theCheckpointInterval
 * will be reset accordingly (valid for current computation).  If dmtcp_command
 * specifies '-i' (or if user interactively invokes 'i' in coordinator),
 * then both theCheckpointInterval and theDefaultCheckpointInterval are set.
 * A value of '0' means:  never checkpoint (manual checkpoint only).
 */
static uint32_t theCheckpointInterval = 0; /* Current checkpoint interval */
static uint32_t theDefaultCheckpointInterval = 0; /* Reset to this on new comp. */
static bool isRestarting = false;
static bool timerExpired = false;

static void resetCkptTimer();

const int STDIN_FD = fileno ( stdin );

JTIMER ( checkpoint );
JTIMER ( restart );

static UniquePid compId;
static int numPeers = -1;
static time_t curTimeStamp = -1;
static time_t ckptTimeStamp = -1;

static LookupService lookupService;

static string coordHostname;
static struct in_addr localhostIPAddr;

static string tmpDir;
static string ckptDir;
static string globalCkptDir;

#define MAX_EVENTS 10000
struct epoll_event events[MAX_EVENTS];
int epollFd;
static jalib::JSocket *listenSock = NULL;

static void removeStaleSharedAreaFile();
static void preExitCleanup();

static pid_t _nextVirtualPid = INITIAL_VIRTUAL_PID;

static int theNextClientNumber = 1;
vector<CoordClient*> clients;

CoordClient::CoordClient(const jalib::JSocket& sock,
                         const struct sockaddr_storage *addr,
                         socklen_t len,
                         DmtcpMessage &hello_remote,
                         int isNSWorker)
  : _sock(sock)
{
  _isNSWorker = isNSWorker;
  _realPid = hello_remote.realPid;
  _clientNumber = theNextClientNumber++;
  _identity = hello_remote.from;
  _state = hello_remote.state;
  _virtualPid = 0;
  struct sockaddr_in *in = (struct sockaddr_in*) addr;
  _ip = inet_ntoa(in->sin_addr);
}

void CoordClient::readProcessInfo(DmtcpMessage& msg)
{
  if (msg.extraBytes > 0) {
    char* extraData = new char[msg.extraBytes];
    _sock.readAll(extraData, msg.extraBytes);
    _hostname = extraData;
    _progname = extraData + _hostname.length() + 1;
    delete [] extraData;
  }
}

pid_t DmtcpCoordinator::getNewVirtualPid()
{
  pid_t pid = -1;
  JASSERT(_virtualPidToClientMap.size() < MAX_VIRTUAL_PID/1000)
    .Text("Exceeded maximum number of processes allowed");
  while (1) {
    pid = _nextVirtualPid;
    _nextVirtualPid += 1000;
    if (_nextVirtualPid > MAX_VIRTUAL_PID) {
      _nextVirtualPid = INITIAL_VIRTUAL_PID;
    }
    if (_virtualPidToClientMap.find(pid) == _virtualPidToClientMap.end()) {
      break;
    }
  }
  JASSERT(pid != -1) .Text("Not Reachable");
  return pid;
}

static string replyData = "";

void DmtcpCoordinator::handleUserCommand(char cmd, DmtcpMessage* reply /*= NULL*/)
{
  if (reply != NULL) reply->coordCmdStatus = CoordCmdStatus::NOERROR;

  switch ( cmd ){
  case 'b': case 'B':  // prefix blocking command, prior to checkpoint command
    JTRACE ( "blocking checkpoint beginning..." );
    blockUntilDone = true;
    break;
  case 'x': case 'X':  // prefix exit command, prior to checkpoint command
    JTRACE ( "Will exit after creating the checkpoint..." );
    exitAfterCkptOnce = true;
    break;
  case 'd': case 'D':
    broadcastMessage(DMT_UPDATE_LOGGING);
    break;
  case 'e': case 'E':
  {
    ComputationStatus s = getStatus();

    if (s.minimumState == WorkerState::RUNNING && s.minimumStateUnanimous
        && !workersRunningAndSuspendMsgSent) {
      JTRACE("Received DMT_GET_COORD_CKPT_DIR msg");
      reply->extraBytes = ckptDir.length() + 1;
    }
    else {
      JTRACE("Received DMT_GET_COORD_CKPT_DIR msg during checkpointing");
    }

    if (reply && reply->extraBytes > 0) {
      replyData = ckptDir;
    }
    break;
  }
  case 'c': case 'C':
    JTRACE ( "checkpointing..." );
    if(startCheckpoint()){
      if (reply != NULL) reply->numPeers = getStatus().numPeers;
    }else{
      if (reply != NULL) reply->coordCmdStatus = CoordCmdStatus::ERROR_NOT_RUNNING_STATE;
    }
    break;
  case 'i': case 'I':
    JTRACE("setting checkpoint interval...");
    updateCheckpointInterval ( theCheckpointInterval );
    if (theCheckpointInterval == 0)
      printf("Current Checkpoint Interval:"
             " Disabled (checkpoint manually instead)\n");
    else
      printf("Current Checkpoint Interval: %d\n", theCheckpointInterval);
    if (theDefaultCheckpointInterval == 0)
      printf("Default Checkpoint Interval:"
             " Disabled (checkpoint manually instead)\n");
    else
      printf("Default Checkpoint Interval: %d\n", theDefaultCheckpointInterval);
    break;
  case 'l': case 'L':
  case 't': case 'T':
  {
    if (reply != NULL) {
      replyData = printList();
      reply->extraBytes = replyData.length();
    } else {
      JASSERT_STDERR << printList();
    }
    break;
  }
  case 'q': case 'Q':
  {
    JNOTE ( "killing all connected peers and quitting ..." );
    broadcastMessage ( DMT_KILL_PEER );
    JASSERT_STDERR << "DMTCP coordinator exiting... (per request)\n";
    for (size_t i = 0; i < clients.size(); i++) {
      clients[i]->sock().close();
    }
    listenSock->close();
    preExitCleanup();
    JTRACE ("Exiting ...");
    exit ( 0 );
    break;
  }
  case 'k': case 'K':
    JNOTE ( "Killing all connected Peers..." );
    //FIXME: What happens if a 'k' command is followed by a 'c' command before
    //       the *real* broadcast takes place?         --Kapil
    broadcastMessage ( DMT_KILL_PEER );
    break;
  case 'h': case 'H': case '?':
    JASSERT_STDERR << theHelpMessage;
    break;
  case 's': case 'S':
  {
    ComputationStatus s = getStatus();
    bool running = (s.minimumStateUnanimous &&
                    s.minimumState==WorkerState::RUNNING);
    if (reply != NULL) {
      reply->numPeers = s.numPeers;
      reply->isRunning = running;
      reply->theCheckpointInterval = theCheckpointInterval;
    } else {
      printStatus(s.numPeers, running);
    }
    break;
  }
  case ' ': case '\t': case '\n': case '\r':
    //ignore whitespace
    break;
  default:
    JTRACE("unhandled user command")(cmd);
    if (reply != NULL){
      reply->coordCmdStatus = CoordCmdStatus::ERROR_INVALID_COMMAND;
    }
  }
  return;
}

void DmtcpCoordinator::printStatus(size_t numPeers, bool isRunning)
{
  ostringstream o;
  o << "Status..." << std::endl
    << "Host: " << coordHostname
    << " (" << inet_ntoa(localhostIPAddr) << ")" << std::endl
    << "Port: " << thePort << std::endl
    << "Checkpoint Interval: ";

  if (theCheckpointInterval == 0) {
    o << "disabled (checkpoint manually instead)" << std::endl;
  } else {
    o << theCheckpointInterval << std::endl;
  }

  o << "Exit on last client: " << exitOnLast << std::endl
    << "Exit after checkpoint: " << exitAfterCkpt << std::endl
    // << "Exit after checkpoint (first time only): " << exitAfterCkptOnce
    //    << std::endl
    << "Computation Id: " << compId << std::endl
    << "Checkpoint Dir: " << ckptDir << std::endl
    << "NUM_PEERS=" << numPeers << std::endl
    << "RUNNING=" << (isRunning ? "yes" : "no") << std::endl;
  printf("%s", o.str().c_str());
  fflush(stdout);
}

string DmtcpCoordinator::printList()
{
  ostringstream o;
  o << "Client List:\n";
  o << "#, PROG[virtPID:realPID]@HOST, DMTCP-UNIQUEPID, STATE\n";
  for (size_t i = 0; i < clients.size(); i++) {
    o << clients[i]->clientNumber()
      << ", " << clients[i]->progname()
      << "[" << clients[i]->identity().pid() << ":" << clients[i]->realPid()
      << "]@" << clients[i]->hostname()
#ifdef PRINT_REMOTE_IP
      << "(" << clients[i]->ip() << ")"
#endif
      << ", " << clients[i]->identity()
      << ", " << clients[i]->state()
      << '\n';
  }
  return o.str();
}

void DmtcpCoordinator::updateMinimumState(WorkerState::eWorkerState oldState)
{
  WorkerState::eWorkerState newState = minimumState();
  JTRACE("updating minimum state")(oldState)(newState);

  if ( oldState == WorkerState::RUNNING
       && newState == WorkerState::SUSPENDED )
  {
    JNOTE ( "locking all nodes" );
    broadcastMessage(DMT_DO_FD_LEADER_ELECTION, getStatus().numPeers );
  }
  if ( oldState == WorkerState::SUSPENDED
       && newState == WorkerState::FD_LEADER_ELECTION )
  {
    JNOTE ( "registering peer info pre ckpt" );
    broadcastMessage ( DMT_DO_PRE_CKPT_NAME_SERVICE_DATA_REGISTER );
  }
  if ( oldState == WorkerState::FD_LEADER_ELECTION
       && newState == WorkerState::PRE_CKPT_NAME_SERVICE_DATA_REGISTER )
  {
    JNOTE ( "querying peer info pre ckpt" );
    broadcastMessage ( DMT_DO_PRE_CKPT_NAME_SERVICE_DATA_QUERY );
  }
  if ( oldState == WorkerState::PRE_CKPT_NAME_SERVICE_DATA_REGISTER
       && newState == WorkerState::PRE_CKPT_NAME_SERVICE_DATA_QUERY )
  {
    JNOTE ( "draining all nodes" );
    broadcastMessage ( DMT_DO_DRAIN );
  }
  if ( oldState == WorkerState::PRE_CKPT_NAME_SERVICE_DATA_QUERY
       && newState == WorkerState::DRAINED )
  {
    JNOTE ( "checkpointing all nodes" );
    broadcastMessage ( DMT_DO_CHECKPOINT );
  }

#ifdef COORD_NAMESERVICE
  if ( oldState == WorkerState::DRAINED
       && newState == WorkerState::CHECKPOINTED )
  {
    RestartScript::writeScript(ckptDir,
                               uniqueCkptFilenames,
                               ckptTimeStamp,
                               theCheckpointInterval,
                               thePort,
                               compId,
                               _restartFilenames,
                               _rshCmdFileNames,
                               _sshCmdFileNames);

    if (exitAfterCkpt || exitAfterCkptOnce) {
      JNOTE("Checkpoint Done. Killing all peers.");
      JTIMER_STOP ( checkpoint );
      broadcastMessage(DMT_KILL_PEER);
      exitAfterCkptOnce = false;
    } else {
      JNOTE ( "building name service database" );
      // lookupService.reset();
      broadcastMessage ( DMT_DO_REGISTER_NAME_SERVICE_DATA );
    }
  }
  if ( oldState == WorkerState::RESTARTING
       && newState == WorkerState::CHECKPOINTED )
  {
    JTIMER_STOP ( restart );

    lookupService.reset();
    JNOTE ( "building name service database (after restart)" );
    broadcastMessage ( DMT_DO_REGISTER_NAME_SERVICE_DATA );
  }
  if ( oldState == WorkerState::CHECKPOINTED
       && newState == WorkerState::NAME_SERVICE_DATA_REGISTERED ){
    JNOTE ( "entertaining queries now" );
    broadcastMessage ( DMT_DO_SEND_QUERIES );
  }
  if ( oldState == WorkerState::NAME_SERVICE_DATA_REGISTERED
       && newState == WorkerState::DONE_QUERYING ){
    JNOTE ( "refilling all nodes" );
    broadcastMessage ( DMT_DO_REFILL );
  }
  if ( oldState == WorkerState::DONE_QUERYING
       && newState == WorkerState::REFILLED )
    /* then broadcastMessage(DMT_DO_RESUME) after the #endif, below */
#else
  if ( oldState == WorkerState::DRAINED
       && newState == WorkerState::CHECKPOINTED )
  {
    RestartScript::writeScript(ckptDir,
                               uniqueCkptFilenames,
                               ckptTimeStamp,
                               theCheckpointInterval,
                               thePort,
                               compId,
                               _restartFilenames);

    if (exitAfterCkpt || exitAfterCkptOnce) {
      JNOTE("Checkpoint Done. Killing all peers.");
      JTIMER_STOP ( checkpoint );
      broadcastMessage(DMT_KILL_PEER);
      exitAfterCkptOnce = false;
    } else {
      JNOTE ( "refilling all nodes" );
      broadcastMessage ( DMT_DO_REFILL );
    }
  }
  if ( oldState == WorkerState::RESTARTING
       && newState == WorkerState::CHECKPOINTED )
  {
    JTIMER_STOP ( restart );

    JNOTE ( "refilling all nodes (after checkpoint)" );
    broadcastMessage ( DMT_DO_REFILL );
  }
  if ( oldState == WorkerState::CHECKPOINTED
       && newState == WorkerState::REFILLED )
#endif
  {
    JNOTE ( "restarting all nodes" );
    broadcastMessage ( DMT_DO_RESUME );

    JTIMER_STOP ( checkpoint );
    isRestarting = false;

    resetCkptTimer();

    if (blockUntilDone) {
      DmtcpMessage blockUntilDoneReply(DMT_USER_CMD_RESULT);
      JNOTE ( "replying to dmtcp_command:  we're done" );
      // These were set in DmtcpCoordinator::onConnect in this file
      jalib::JSocket remote ( blockUntilDoneRemote );
      remote << blockUntilDoneReply;
      remote.close();
      blockUntilDone = false;
      blockUntilDoneRemote = -1;
    }
  }
}

void DmtcpCoordinator::onData(CoordClient *client)
{
  DmtcpMessage msg;
  JASSERT(client != NULL);

  client->sock() >> msg;
  msg.assertValid();
  char *extraData = 0;
  if (msg.extraBytes > 0) {
    extraData = new char[msg.extraBytes];
    client->sock().readAll(extraData, msg.extraBytes);
  }

  switch ( msg.type )
  {
    case DMT_OK:
    {
      WorkerState::eWorkerState oldState = client->state();
      client->setState ( msg.state );
      ComputationStatus s = getStatus();
      WorkerState::eWorkerState newState = s.minimumState;

      JTRACE ("got DMT_OK message")
        ( oldState )( msg.from )( msg.state )( newState );

      updateMinimumState(oldState);
      break;
    }
    case DMT_UNIQUE_CKPT_FILENAME:
      uniqueCkptFilenames = true;
      // Fall though
    case DMT_CKPT_FILENAME:
    {
      JASSERT ( extraData!=0 )
        .Text ( "extra data expected with DMT_CKPT_FILENAME message" );
      string ckptFilename;
      string hostname;
      string shellType;

      ckptFilename = extraData;
      shellType = extraData + ckptFilename.length() + 1;
      hostname = extraData + shellType.length() + 1 + ckptFilename.length() + 1;

      JTRACE ( "recording restart info with shellType" ) ( ckptFilename ) ( hostname ) (shellType);
      if(shellType.empty()) {
        _restartFilenames[hostname].push_back ( ckptFilename );
      } else if(shellType == "rsh") {
        _rshCmdFileNames[hostname].push_back( ckptFilename );
      } else if(shellType == "ssh") {
        _sshCmdFileNames[hostname].push_back( ckptFilename );
      } else {
        JASSERT(0)(shellType)
          .Text("Shell command not supported. Report this to DMTCP community.");
      }
    }
    break;
    case DMT_UPDATE_CKPT_DIR:
    {
      JASSERT(extraData != 0)
        .Text("extra data expected with DMT_UPDATE_CKPT_DIR message");
      if (strcmp(ckptDir.c_str(), extraData) != 0) {
        ckptDir = extraData;
        JNOTE("Updated ckptDir") (ckptDir);
      }
    }
    break;

#ifdef COORD_NAMESERVICE
    case DMT_REGISTER_NAME_SERVICE_DATA:
    {
      JTRACE ("received REGISTER_NAME_SERVICE_DATA msg") (client->identity());
      lookupService.registerData(msg, (const void*) extraData);
    }
    break;

    case DMT_REGISTER_NAME_SERVICE_DATA_SYNC:
    {
      JTRACE ("received REGISTER_NAME_SERVICE_DATA_SYNC msg") (client->identity());
      lookupService.registerData(msg, (const void*) extraData);
      DmtcpMessage response(DMT_REGISTER_NAME_SERVICE_DATA_SYNC_RESPONSE);
      JTRACE("Sending NS response to the client...");
      client->sock() << response;
    }
    break;
    case DMT_NAME_SERVICE_QUERY:
    {
      JTRACE ("received NAME_SERVICE_QUERY msg") (client->identity());
      lookupService.respondToQuery(client->sock(), msg,
                                   (const void*) extraData);
    }
    break;
    case DMT_NAME_SERVICE_GET_UNIQUE_ID:
    {
      JTRACE("received NAME_SERVICE_GET_UNIQUE_ID msg") (client->identity());
      lookupService.respondToQuery(client->sock(), msg,
                                   (const void *)extraData);
    }
    break;
  
#endif

    case DMT_UPDATE_PROCESS_INFO_AFTER_FORK:
    {
        JNOTE("Updating process Information after fork()")
          (client->hostname()) (client->progname()) (msg.from) (client->identity());
        client->identity(msg.from);
        client->realPid(msg.realPid);
    }
    break;
    case DMT_UPDATE_PROCESS_INFO_AFTER_INIT_OR_EXEC:
    {
      string progname = extraData;
      JNOTE("Updating process Information after exec()")
        (progname) (msg.from) (client->identity());
      client->progname(progname);
      client->identity(msg.from);
    }
    break;

    case DMT_NULL:
      JWARNING(false) (msg.type) .Text("unexpected message from worker. Closing connection");
      onDisconnect(client);
      break;
    default:
      JASSERT ( false ) ( msg.from ) ( msg.type )
        .Text ( "unexpected message from worker" );
  }

  delete[] extraData;
}


static void removeStaleSharedAreaFile()
{
  ostringstream o;
  o << tmpDir
    << "/dmtcpSharedArea." << compId << "." << std::hex << curTimeStamp;
  JTRACE("Removing sharedArea file.") (o.str());
  unlink(o.str().c_str());
}

static void preExitCleanup()
{
  removeStaleSharedAreaFile();
  JTRACE("Removing port-file") (thePortFile);
  unlink(thePortFile.c_str());
}

void DmtcpCoordinator::onDisconnect(CoordClient *client)
{
  if (client->isNSWorker()) {
    client->sock().close();
    delete client;
    return;
  }
  for (size_t i = 0; i < clients.size(); i++) {
    if (clients[i] == client) {
      clients.erase(clients.begin() + i);
      break;
    }
  }
  client->sock().close();
  JNOTE ( "client disconnected" ) ( client->identity() ) (client->progname());
  _virtualPidToClientMap.erase(client->virtualPid());

  ComputationStatus s = getStatus();
  if (s.numPeers < 1) {
    if (exitOnLast) {
      JNOTE ("last client exited, shutting down..");
      handleUserCommand('q');
    } else {
      removeStaleSharedAreaFile();
    }
    // If a kill in is progress, the coordinator refuses any new connections,
    // thus we need to reset it to false once all the processes in the
    // computations have disconnected.
    killInProgress = false;
    if (theCheckpointInterval != theDefaultCheckpointInterval) {
      updateCheckpointInterval(theDefaultCheckpointInterval);
      JNOTE ( "CheckpointInterval reset on end of current computation" )
        ( theCheckpointInterval );
    }
  } else {
    updateMinimumState(client->state());
  }
}

void DmtcpCoordinator::initializeComputation()
{
  //this is the first connection, do some initializations
  workersRunningAndSuspendMsgSent = false;
  killInProgress = false;
  //_nextVirtualPid = INITIAL_VIRTUAL_PID;

  // drop current computation group to 0
  compId = UniquePid(0,0,0);
  curTimeStamp = 0; // Drop timestamp to 0
  numPeers = -1; // Drop number of peers to unknown
  blockUntilDone = false;
  exitAfterCkptOnce = false;
}

void DmtcpCoordinator::onConnect()
{
  struct sockaddr_storage remoteAddr;
  socklen_t remoteLen = sizeof(remoteAddr);
  jalib::JSocket remote = listenSock->accept(&remoteAddr, &remoteLen);
  JTRACE("accepting new connection") (remote.sockfd());

  if (!remote.isValid()) {
    remote.close();
    return;
  }

  DmtcpMessage hello_remote;
  hello_remote.poison();
  JTRACE("Reading from incoming connection...");
  remote >> hello_remote;
  if (!remote.isValid()) {
    remote.close();
    return;
  }

  if (hello_remote.type == DMT_UPDATE_GLOBAL_CKPT_DIR) {
    JASSERT(hello_remote.extraBytes > 0) (hello_remote.extraBytes);
    ComputationStatus s = getStatus();
    char *extraData = new char[hello_remote.extraBytes];
    remote.readAll(extraData, hello_remote.extraBytes);
    DmtcpMessage reply;

    if (s.minimumState == WorkerState::RUNNING && s.minimumStateUnanimous
        && !workersRunningAndSuspendMsgSent) {
      reply.type = DMT_UPDATE_GLOBAL_CKPT_DIR_SUCCEED;
      globalCkptDir = extraData;
      JTRACE("Received DMT_UPDATE_GLOBAL_CKPT_DIR msg, "
             "updating the global checkpoint dir")
        (hello_remote.from) (globalCkptDir);
    } else {
      reply.type = DMT_UPDATE_GLOBAL_CKPT_DIR_FAIL;
      JTRACE("Received DMT_UPDATE_GLOBAL_CKPT_DIR msg during checkpointing, "
             "will not update the global checkpoint dir") (hello_remote.from);
    }

    remote << reply;
    delete [] extraData;
    remote.close();
    return;
  }

#ifdef COORD_NAMESERVICE
  if (hello_remote.type == DMT_NAME_SERVICE_WORKER) {
    CoordClient *client = new CoordClient(remote, &remoteAddr, remoteLen,
		                          hello_remote);

    addDataSocket(client);
    return;
  }
  if (hello_remote.type == DMT_NAME_SERVICE_QUERY) {
    JASSERT(hello_remote.extraBytes > 0) (hello_remote.extraBytes);
    char *extraData = new char[hello_remote.extraBytes];
    remote.readAll(extraData, hello_remote.extraBytes);

    JTRACE ("received NAME_SERVICE_QUERY msg on running") (hello_remote.from);
    lookupService.respondToQuery(remote, hello_remote, extraData);
    delete [] extraData;
    remote.close();
    return;
  }
  if (hello_remote.type == DMT_NAME_SERVICE_GET_UNIQUE_ID) {
    JASSERT(hello_remote.extraBytes > 0) (hello_remote.extraBytes);
    char *extraData = new char[hello_remote.extraBytes];
    remote.readAll(extraData, hello_remote.extraBytes);

    JTRACE("received NAME_SERVICE_GET_UNIQUE_ID msg on running")
          (hello_remote.from);
    lookupService.respondToQuery(remote, hello_remote, extraData);
    delete[] extraData;
    remote.close();
    return;
  }
  if (hello_remote.type == DMT_REGISTER_NAME_SERVICE_DATA) {
    JASSERT(hello_remote.extraBytes > 0) (hello_remote.extraBytes);
    char *extraData = new char[hello_remote.extraBytes];
    remote.readAll(extraData, hello_remote.extraBytes);

    JTRACE ("received REGISTER_NAME_SERVICE_DATA msg on running") (hello_remote.from);
    lookupService.registerData(hello_remote, (const void*) extraData);
    delete [] extraData;
    remote.close();
    return;
  }
  if (hello_remote.type == DMT_REGISTER_NAME_SERVICE_DATA_SYNC) {
    JASSERT(hello_remote.extraBytes > 0) (hello_remote.extraBytes);
    char *extraData = new char[hello_remote.extraBytes];
    remote.readAll(extraData, hello_remote.extraBytes);

    JTRACE ("received REGISTER_NAME_SERVICE_DATA msg on running") (hello_remote.from);
    lookupService.registerData(hello_remote, (const void*) extraData);
    delete [] extraData;
    DmtcpMessage response(DMT_REGISTER_NAME_SERVICE_DATA_SYNC_RESPONSE);
    JTRACE("Reading from incoming connection...");
    remote << response;
    remote.close();
    return;
  }
#endif

  if (hello_remote.type == DMT_USER_CMD) {
    // TODO(kapil): Update ckpt interval only if a valid one was supplied to
    // dmtcp_command.
    updateCheckpointInterval(hello_remote.theCheckpointInterval);
    processDmtUserCmd(hello_remote, remote);
    return;
  }

  if (killInProgress) {
    JNOTE("Connection request received in the middle of killing computation. "
          "Sending it the kill message.");
    DmtcpMessage msg;
    msg.type = DMT_KILL_PEER;
    remote << msg;
    remote.close();
    return;
  }

  // If no client is connected to Coordinator, then there can be only zero data
  // sockets OR there can be one data socket and that should be STDIN.
  if (clients.size() == 0) {
    initializeComputation();
  }

  CoordClient *client = new CoordClient(remote, &remoteAddr, remoteLen,
                                        hello_remote);

  if( hello_remote.extraBytes > 0 ){
    client->readProcessInfo(hello_remote);
  }

  if (hello_remote.type == DMT_RESTART_WORKER) {
    if (!validateRestartingWorkerProcess(hello_remote, remote,
                                         &remoteAddr, remoteLen)) {
      return;
    }
    client->virtualPid(hello_remote.from.pid());
    _virtualPidToClientMap[client->virtualPid()] = client;
    isRestarting = true;
  } else if (hello_remote.type == DMT_NEW_WORKER) {
    JASSERT(hello_remote.state == WorkerState::RUNNING ||
            hello_remote.state == WorkerState::UNKNOWN);
    JASSERT(hello_remote.virtualPid == -1);
    client->virtualPid(getNewVirtualPid());
    if (!validateNewWorkerProcess(hello_remote, remote, client,
                                  &remoteAddr, remoteLen)) {
      return;
    }
    _virtualPidToClientMap[client->virtualPid()] = client;
  } else {
    JASSERT(false) (hello_remote.type)
      .Text("Connect request from Unknown Remote Process Type");
  }

  updateCheckpointInterval(hello_remote.theCheckpointInterval);
  JNOTE ( "worker connected" ) ( hello_remote.from );

  clients.push_back(client);
  addDataSocket(client);

  JTRACE("END") (clients.size());
}

void DmtcpCoordinator::processDmtUserCmd(DmtcpMessage& hello_remote,
                                         jalib::JSocket& remote )
{
  //dmtcp_command doesn't handshake (it is antisocial)
  JTRACE("got user command from dmtcp_command")((char)hello_remote.coordCmd);
  DmtcpMessage reply;
  reply.type = DMT_USER_CMD_RESULT;
  // if previous 'b' blocking prefix command had set blockUntilDone
  if (blockUntilDone && blockUntilDoneRemote == -1  &&
      hello_remote.coordCmd == 'c') {
    // Reply will be done in DmtcpCoordinator::onData in this file.
    blockUntilDoneRemote = remote.sockfd();
    handleUserCommand( hello_remote.coordCmd, &reply );
  } else if (hello_remote.coordCmd == 'i') {
//    theDefaultCheckpointInterval = hello_remote.theCheckpointInterval;
//    theCheckpointInterval = theDefaultCheckpointInterval;
    handleUserCommand( hello_remote.coordCmd, &reply );
    remote << reply;
    remote.close();
  } else if (hello_remote.coordCmd == 'd') {
    mask = hello_remote.logMask;
    handleUserCommand(hello_remote.coordCmd);
    remote << reply;
  } else {
    handleUserCommand( hello_remote.coordCmd, &reply );
    remote << reply;
    if (reply.extraBytes > 0) {
      remote.writeAll(replyData.c_str(), reply.extraBytes);
    }
    remote.close();
  }
  return;
}

/*
 * Returns the current timestamp with nanosecond resolution
 */
static uint64_t
getCurrTimestamp()
{
  struct timespec value;
  uint64_t nsecs = 0;
  JASSERT(clock_gettime(CLOCK_MONOTONIC, &value) == 0);
  nsecs = value.tv_sec*1000000000L + value.tv_nsec;
  return nsecs;
}


bool DmtcpCoordinator::validateRestartingWorkerProcess(
    DmtcpMessage& hello_remote,
    jalib::JSocket& remote,
    const struct sockaddr_storage* remoteAddr,
    socklen_t remoteLen)
{
  const struct sockaddr_in *sin = (const struct sockaddr_in*) remoteAddr;
  string remoteIP = inet_ntoa(sin->sin_addr);
  DmtcpMessage hello_local ( DMT_ACCEPT );

  JASSERT(hello_remote.state == WorkerState::RESTARTING) (hello_remote.state);

  if (compId == UniquePid(0,0,0)) {
    JASSERT ( minimumState() == WorkerState::UNKNOWN )
      .Text ( "Coordinator should be idle at this moment" );
    // Coordinator is free at this moment - set up all the things
    compId = hello_remote.compGroup;
    numPeers = hello_remote.numPeers;
    curTimeStamp = getCurrTimestamp();
    JNOTE ( "FIRST dmtcp_restart connection.  Set numPeers. Generate timestamp" )
      ( numPeers ) ( curTimeStamp ) ( compId );
    JTIMER_START(restart);
  } else if (minimumState() != WorkerState::RESTARTING &&
             minimumState() != WorkerState::CHECKPOINTED) {
    JNOTE ("Computation not in RESTARTING or CHECKPOINTED state."
           "  Reject incoming computation process requesting restart.")
      (compId) (hello_remote.compGroup) (minimumState());
    hello_local.type = DMT_REJECT_NOT_RESTARTING;
    remote << hello_local;
    remote.close();
    return false;
  } else if ( hello_remote.compGroup != compId) {
    JNOTE ("Reject incoming computation process requesting restart,"
           " since it is not from current computation.")
      ( compId ) ( hello_remote.compGroup );
    hello_local.type = DMT_REJECT_WRONG_COMP;
    remote << hello_local;
    remote.close();
    return false;
  }
  // dmtcp_restart already connected and compGroup created.
  // Computation process connection
  JASSERT ( curTimeStamp != 0 );

  JTRACE("Connection from (restarting) computation process")
    ( compId ) ( hello_remote.compGroup ) ( minimumState() );

  hello_local.coordTimeStamp = curTimeStamp;
  if (Util::strStartsWith(remoteIP, "127.")) {
    memcpy(&hello_local.ipAddr, &localhostIPAddr, sizeof localhostIPAddr);
  } else {
    memcpy(&hello_local.ipAddr, &sin->sin_addr, sizeof localhostIPAddr);
  }
  remote << hello_local;

  // NOTE: Sending the same message twice. We want to make sure that the
  // worker process receives/processes the first messages as soon as it
  // connects to the coordinator. The second message will be processed in
  // postRestart routine in DmtcpWorker.
  //
  // The reason to do this is the following. The dmtcp_restart process
  // connects to the coordinator at a very early stage. Later on, before
  // exec()'ing into mtcp_restart, it reconnects to the coordinator using
  // it's original UniquiePid and closes the earlier socket connection.
  // However, the coordinator might process the disconnect() before it
  // processes the connect() which would lead to a situation where the
  // coordinator is not connected to any worker processes. The coordinator
  // would now process the connect() and may reject the worker because the
  // worker state is RESTARTING, but the minimumState() is UNKNOWN.
  //remote << hello_local;

  return true;
}

bool DmtcpCoordinator::validateNewWorkerProcess(
    DmtcpMessage& hello_remote,
    jalib::JSocket& remote,
    CoordClient *client,
    const struct sockaddr_storage* remoteAddr,
    socklen_t remoteLen)
{
  const struct sockaddr_in *sin = (const struct sockaddr_in*) remoteAddr;
  string remoteIP = inet_ntoa(sin->sin_addr);
  DmtcpMessage hello_local(DMT_ACCEPT);
  hello_local.virtualPid = client->virtualPid();
  ComputationStatus s = getStatus();

  JASSERT(hello_remote.state == WorkerState::RUNNING ||
          hello_remote.state == WorkerState::UNKNOWN) (hello_remote.state);

  if (workersRunningAndSuspendMsgSent == true) {
    /* Worker trying to connect after SUSPEND message has been sent.
     * This happens if the worker process is executing a fork() system call
     * when the DMT_DO_SUSPEND is broadcast. We need to make sure that the
     * child process is allowed to participate in the current checkpoint.
     */
    JASSERT(s.numPeers > 0) (s.numPeers);
    JASSERT(s.minimumState != WorkerState::SUSPENDED) (s.minimumState);

    // Handshake
    hello_local.compGroup = compId;
    remote << hello_local;

    // Now send DMT_DO_SUSPEND message so that this process can also
    // participate in the current checkpoint
    DmtcpMessage suspendMsg (DMT_DO_SUSPEND);
    suspendMsg.compGroup = compId;
    remote << suspendMsg;

  } else if (s.numPeers > 0 && s.minimumState != WorkerState::RUNNING &&
             s.minimumState != WorkerState::UNKNOWN) {
    // If some of the processes are not in RUNNING state
    JNOTE("Current computation not in RUNNING state."
          "  Refusing to accept new connections.")
      (compId) (hello_remote.from)
      (s.numPeers) (s.minimumState);
    hello_local.type = DMT_REJECT_NOT_RUNNING;
    remote << hello_local;
    remote.close();
    return false;

  } else if (hello_remote.compGroup != UniquePid()) {
    // New Process trying to connect to Coordinator but already has compGroup
    JNOTE ("New process not part of currently running computation group"
           "on this coordinator.  Rejecting.")
      (hello_remote.compGroup);

    hello_local.type = DMT_REJECT_WRONG_COMP;
    remote << hello_local;
    remote.close();
    return false;

  } else {
    // If first process, create the new computation group
    if (compId == UniquePid(0,0,0)) {
      // Connection of new computation.
      compId = UniquePid(hello_remote.from.hostid(), client->virtualPid(),
                         hello_remote.from.time(),
                         hello_remote.from.computationGeneration());

      curTimeStamp = getCurrTimestamp();
      numPeers = -1;
      JTRACE("First process connected.  Creating new computation group.")
        (compId);
    } else {
      JTRACE("New process connected")
        (hello_remote.from) (client->virtualPid());
    }
    hello_local.compGroup = compId;
    hello_local.coordTimeStamp = curTimeStamp;
    if (Util::strStartsWith(remoteIP, "127.")) {
      memcpy(&hello_local.ipAddr, &localhostIPAddr, sizeof localhostIPAddr);
    } else {
      memcpy(&hello_local.ipAddr, &sin->sin_addr, sizeof localhostIPAddr);
    }
    remote << hello_local;
  }
  return true;
}

bool DmtcpCoordinator::startCheckpoint()
{
  uniqueCkptFilenames = false;
  ComputationStatus s = getStatus();
  if ( s.minimumState == WorkerState::RUNNING && s.minimumStateUnanimous
       && !workersRunningAndSuspendMsgSent )
  {
    time(&ckptTimeStamp);
    JTIMER_START ( checkpoint );
    _restartFilenames.clear();
    _rshCmdFileNames.clear();
    _sshCmdFileNames.clear();
    JNOTE ( "starting checkpoint, suspending all nodes" )( s.numPeers );
    compId.incrementGeneration();
    JNOTE("Incremented computationGeneration") (compId.computationGeneration());
    // Pass number of connected peers to all clients
    broadcastMessage(DMT_DO_SUSPEND);

    // Suspend Message has been sent but the workers are still in running
    // state.  If the coordinator receives another checkpoint request from user
    // at this point, it should fail.
    workersRunningAndSuspendMsgSent = true;
    return true;
  } else {
    if (s.numPeers > 0) {
      JTRACE ( "delaying checkpoint, workers not ready" ) ( s.minimumState )
	     ( s.numPeers );
    }
    return false;
  }
}

void DmtcpCoordinator::broadcastMessage(DmtcpMessageType type, int numPeers)
{
  DmtcpMessage msg;
  msg.type = type;
  msg.compGroup = compId;
  if (numPeers > 0) {
    msg.numPeers = numPeers;
  }
  // Coordinator broadcasts the global checkpoint dir at the beginning of
  // a checkpoint.
  if (msg.type == DMT_DO_SUSPEND && !globalCkptDir.empty()) {
    msg.extraBytes = globalCkptDir.length() + 1;
  }

  if (msg.type == DMT_KILL_PEER && clients.size() > 0) {
    killInProgress = true;
  } else if (msg.type == DMT_UPDATE_LOGGING) {
    msg.logMask = mask;
  } else if (msg.type == DMT_DO_FD_LEADER_ELECTION) {
    // All the workers are in SUSPENDED state, now it is safe to reset
    // this flag.
    workersRunningAndSuspendMsgSent = false;
  }

  for (size_t i = 0; i < clients.size(); i++) {
    clients[i]->sock() << msg;
    if (msg.extraBytes > 0) {
      clients[i]->sock().writeAll(globalCkptDir.c_str(), msg.extraBytes);
    }
  }
  JTRACE ("sending message")( type );
}

DmtcpCoordinator::ComputationStatus DmtcpCoordinator::getStatus() const
{
  ComputationStatus status;
  const static WorkerState::eWorkerState INITIAL_MIN = WorkerState::_MAX;
  const static WorkerState::eWorkerState INITIAL_MAX = WorkerState::UNKNOWN;
  int min = INITIAL_MIN;
  int max = INITIAL_MAX;
  int count = 0;
  bool unanimous = true;
  for (size_t i = 0; i < clients.size(); i++) {
    WorkerState::eWorkerState cliState = clients[i]->state();
    count++;
    unanimous = unanimous && (min==cliState || min==INITIAL_MIN);
    if ( cliState < min ) min = cliState;
    if ( cliState > max ) max = cliState;
  }

  status.minimumState = ( min==INITIAL_MIN ? WorkerState::UNKNOWN
			  : (WorkerState::eWorkerState)min );
  if( status.minimumState == WorkerState::CHECKPOINTED &&
      isRestarting && count < numPeers ){
    JTRACE("minimal state counted as CHECKPOINTED but not all processes"
	   " are connected yet.  So we wait.") ( numPeers ) ( count );
    status.minimumState = WorkerState::RESTARTING;
  }
  status.minimumStateUnanimous = unanimous;

  status.maximumState = ( max==INITIAL_MAX ? WorkerState::UNKNOWN
			  : (WorkerState::eWorkerState)max );
  status.numPeers = count;
  return status;
}

static void signalHandler(int signum)
{
  if (signum == SIGINT) {
    prog.handleUserCommand('q');
  } else if (signum == SIGALRM) {
    timerExpired = true;
  } else {
    JASSERT(false) .Text("Not reached");
  }
}

static void setupSignalHandlers()
{
  struct sigaction action;
  sigemptyset(&action.sa_mask);
  action.sa_flags = 0;
  action.sa_handler = signalHandler;

  sigaction(SIGINT, &action, NULL);
  sigaction(SIGALRM, &action, NULL);
}

// This code is also copied to ssh.cpp:updateCoordHost()
static void calcLocalAddr()
{
  char hostname[HOST_NAME_MAX];
  JASSERT(gethostname(hostname, sizeof hostname) == 0) (JASSERT_ERRNO);

  struct addrinfo *result = NULL;
  struct addrinfo *res;
  int error;
  struct addrinfo hints;

  memset(&localhostIPAddr, 0, sizeof localhostIPAddr);
  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_family = AF_UNSPEC; // accept AF_INET and AF_INET6
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;
  hints.ai_protocol = 0;
  hints.ai_canonname = NULL;
  hints.ai_addr = NULL;
  hints.ai_next = NULL;

  // FROM: Wikipedia:CNAME_record:
  //  When a DNS resolver encounters a CNAME record while looking for a regular
  //  resource record, it will restart the query using the canonical name
  //  instead of the original name. (If the resolver is specifically told to
  //  look for CNAME records, the canonical name (right-hand side) is returned,
  //  rather than restarting the query.)
  hints.ai_flags |= AI_CANONNAME;
  error = getaddrinfo(hostname, NULL, &hints, &result);
  hints.ai_flags ^= AI_CANONNAME;
  if (error == 0 && result) {
    // if hostname was not fully qualified with domainname, replace it with
    // canonname.  Otherwise, keep current alias returned from gethostname().
    if ( Util::strStartsWith(result->ai_canonname, hostname) &&
         result->ai_canonname[strlen(hostname)] == '.' &&
         strlen(result->ai_canonname) < sizeof(hostname) ) {
      strncpy(hostname, result->ai_canonname, sizeof hostname);
    }
    freeaddrinfo(result);
  }
  // OPTIONAL:  If we still don't have a domainname, we could resolve with DNS
  //   (similar to 'man 1 host'), but we ont't know if Internet is present.

  /* resolve the hostname into a list of addresses */
  error = getaddrinfo(hostname, NULL, &hints, &result);
  if (error == 0) {
    /* loop over all returned results and do inverse lookup */
    bool success = false;
    bool at_least_one_match = false;
    char name[NI_MAXHOST] = "";
    for (res = result; res != NULL; res = res->ai_next) {
      struct sockaddr_in *s = (struct sockaddr_in *)res->ai_addr;

      error = getnameinfo(res->ai_addr,
                          res->ai_addrlen,
                          name,
                          NI_MAXHOST,
                          NULL,
                          0,
                          0);
      if (error != 0) {
        JTRACE("getnameinfo() failed.") (gai_strerror(error));
        continue;
      } else {
        JASSERT(sizeof localhostIPAddr == sizeof s->sin_addr);
        if ( strncmp( name, hostname, sizeof hostname ) == 0 ) {
          success = true;
          memcpy(&localhostIPAddr, &s->sin_addr, sizeof s->sin_addr);
          break; // Stop here.  We found a matching hostname.
        }
        if (!at_least_one_match) { // Prefer the first match over later ones.
          at_least_one_match = true;
          memcpy(&localhostIPAddr, &s->sin_addr, sizeof s->sin_addr);
        }
      }
    }
    if (result) {
      freeaddrinfo(result);
    }
    if (at_least_one_match) {
      success = true;  // Call it a success even if hostname != name
      if ( strncmp( name, hostname, sizeof hostname ) != 0 ) {
        JTRACE("Canonical hostname different from original hostname")
              (name)(hostname);
      }
    }

    JWARNING(success) (hostname)
      .Text("Failed to find coordinator IP address.  DMTCP may fail.");
  } else {
    if (error == EAI_SYSTEM) {
      perror("getaddrinfo");
    } else {
      JTRACE("Error in getaddrinfo") (gai_strerror(error));
    }
    inet_aton("127.0.0.1", &localhostIPAddr);
  }

  coordHostname = hostname;
}

static void resetCkptTimer()
{
  alarm(theCheckpointInterval);
}

void DmtcpCoordinator::updateCheckpointInterval(uint32_t interval)
{
  static bool firstClient = true;
  if ( (interval != DMTCPMESSAGE_SAME_CKPT_INTERVAL &&
        interval != theCheckpointInterval) ||
       firstClient ) {
    int oldInterval = theCheckpointInterval;
    if (interval != DMTCPMESSAGE_SAME_CKPT_INTERVAL) {
      theCheckpointInterval = interval;
    }
    JNOTE ( "CheckpointInterval updated (for this computation only)" )
      ( oldInterval ) ( theCheckpointInterval );
    firstClient = false;
    resetCkptTimer();
  }
}

void DmtcpCoordinator::eventLoop(bool daemon)
{
  struct epoll_event ev;
  epollFd = epoll_create(MAX_EVENTS);
  JASSERT(epollFd != -1) (JASSERT_ERRNO);

  ev.events = EPOLLIN;
  ev.data.ptr = listenSock;
  JASSERT(epoll_ctl(epollFd, EPOLL_CTL_ADD, listenSock->sockfd(), &ev) != -1)
    (JASSERT_ERRNO);

  if (!daemon &&
      // epoll_ctl below fails if STDIN is pointing to /dev/null.
      // Not sure why.
      jalib::Filesystem::GetDeviceName(0) != "/dev/null" &&
      jalib::Filesystem::GetDeviceName(0) != "/dev/zero" &&
      jalib::Filesystem::GetDeviceName(0) != "/dev/random") {
    ev.events = EPOLLIN;
#ifdef EPOLLRDHUP
    ev.events |= EPOLLRDHUP;
#endif
    ev.data.ptr = (void*) STDIN_FILENO;
    JASSERT(epoll_ctl(epollFd, EPOLL_CTL_ADD, STDIN_FILENO, &ev) != -1)
      (JASSERT_ERRNO);
  }

  while (true) {
    // Wait until either there is some activity on client sockets, or the timer
    // has expired.
    int nfds;
    do {
      nfds = epoll_wait(epollFd, events, MAX_EVENTS, -1);
    } while (nfds < 0 && errno == EINTR && ! timerExpired);

    // The ckpt timer has expired; it's time to checkpoint.
    if (nfds == -1 && errno == EINTR && timerExpired) {
      timerExpired = false;
      startCheckpoint();
      continue;
    }

    // alarm() is not always the only source of interrupts.
    // For example, any signal, including signal 0 or SIGWINCH can cause this.
    JASSERT(nfds != -1 || errno == EINTR) (JASSERT_ERRNO);

    for (int n = 0; n < nfds; ++n) {
      void *ptr = events[n].data.ptr;
      if ((events[n].events & EPOLLHUP) ||
#ifdef EPOLLRDHUP
          (events[n].events & EPOLLRDHUP) ||
#endif
          (events[n].events & EPOLLERR)) {
        JASSERT(ptr != listenSock);
        if (ptr == (void*) STDIN_FILENO) {
          JASSERT(epoll_ctl(epollFd, EPOLL_CTL_DEL, STDIN_FILENO, &ev) != -1)
            (JASSERT_ERRNO);
          close(STDIN_FD);
        } else {
          onDisconnect((CoordClient*)ptr);
        }
      } else if (events[n].events & EPOLLIN) {
        if (ptr == (void*) listenSock) {
          onConnect();
        } else if (ptr == (void*) STDIN_FILENO) {
          char buf[1];
          int ret = Util::readAll(STDIN_FD, buf, sizeof(buf));
          JASSERT(ret != -1) (JASSERT_ERRNO);
          if (ret > 0) {
            handleUserCommand(buf[0]);
          } else {
            JNOTE("closing stdin");
            JASSERT(epoll_ctl(epollFd, EPOLL_CTL_DEL, STDIN_FILENO, &ev) != -1)
              (JASSERT_ERRNO);
            close(STDIN_FD);
          }
        } else {
          onData((CoordClient*)ptr);
        }
      }
    }
  }
}

void DmtcpCoordinator::addDataSocket(CoordClient *client)
{
  struct epoll_event ev;

#ifdef EPOLLRDHUP
  ev.events = EPOLLIN | EPOLLRDHUP;
#else
  ev.events = EPOLLIN;
#endif
  ev.data.ptr = client;
  JASSERT(epoll_ctl(epollFd, EPOLL_CTL_ADD, client->sock().sockfd(), &ev) != -1)
    (JASSERT_ERRNO);
}

#define shift argc--; argv++

int main ( int argc, char** argv )
{
  Util::setProtectedFdBase();
  initializeJalib();

  //parse port
  thePort = DEFAULT_PORT;
  const char* portStr = getenv( ENV_VAR_NAME_PORT );
  if ( portStr == NULL ) portStr = getenv("DMTCP_PORT"); // deprecated
  if ( portStr != NULL ) thePort = jalib::StringToInt( portStr );

  bool daemon = false;
  bool useLogFile = false;
  string logFilename = "";
  bool quiet = false;

  char * tmpdir_arg = NULL;

  /* NOTE: The convention is that user-specified explicit runtime arguments
   *       get a higher priority than env. vars. The logFilename variable will
   *       be over-written if the coordinator was invoked with
   *       `--logfile <filename>.
   */
  if (getenv(ENV_VAR_COORD_LOGFILE)) {
    useLogFile = true;
    logFilename = getenv(ENV_VAR_COORD_LOGFILE);
  }

  shift;
  while(argc > 0){
    string s = argv[0];
    if(s=="-h" || s=="--help"){
      printf("%s", theUsage);
      return 1;
    } else if ((s=="--version") && argc==1){
      printf("%s", DMTCP_VERSION_AND_COPYRIGHT_INFO);
      return 1;
    }else if(s == "-q" || s == "--quiet"){
      quiet = true;
      jassert_quiet++;
      shift;
    }else if(s=="--exit-on-last"){
      exitOnLast = true;
      shift;
    }else if(s=="--exit-after-ckpt"){
      exitAfterCkpt = true;
      shift;
    }else if(s=="--daemon"){
      daemon = true;
      shift;
    } else if(s=="--coord-logfile") {
      useLogFile = true;
      logFilename = argv[1];
      shift; shift;
    } else if (s == "-i" || s == "--interval") {
      setenv(ENV_VAR_CKPT_INTR, argv[1], 1);
      shift; shift;
    } else if (argv[0][0] == '-' && argv[0][1] == 'i' &&
               isdigit(argv[0][2])) { // else if -i5, for example
      setenv(ENV_VAR_CKPT_INTR, argv[0]+2, 1);
      shift;
    } else if (argc>1 && (s == "-p" || s == "--port" || s == "--coord-port")) {
      thePort = jalib::StringToInt( argv[1] );
      shift; shift;
    } else if (argv[0][0] == '-' && argv[0][1] == 'p' &&
               isdigit(argv[0][2])) { // else if -p0, for example
      thePort = jalib::StringToInt( argv[0]+2 );
      shift;
    }else if(argc>1 && s == "--port-file"){
      thePortFile = argv[1];
      shift; shift;
    }else if(argc>1 && (s == "-c" || s == "--ckptdir")){
      setenv(ENV_VAR_CHECKPOINT_DIR, argv[1], 1);
      shift; shift;
    }else if(argc>1 && (s == "-t" || s == "--tmpdir")){
      tmpdir_arg = argv[1];
      shift; shift;
    }else if(argc == 1){ //last arg can be port
      char *endptr;
      long x = strtol(argv[0], &endptr, 10);
      if ((ssize_t)strlen(argv[0]) != endptr - argv[0]) {
        fprintf(stderr, theUsage, DEFAULT_PORT);
        return 1;
      } else {
        thePort = jalib::StringToInt( argv[0] );
        shift;
      }
      x++, x--; // to suppress unused variable warning
    }else{
      fprintf(stderr, theUsage, DEFAULT_PORT);
      return 1;
    }
  }

  tmpDir = Util::calcTmpDir(tmpdir_arg);
  Util::initializeLogFile(tmpDir);

  JTRACE ( "New DMTCP coordinator starting." )
    ( UniquePid::ThisProcess() );

  if ( thePort < 0 )
  {
    fprintf(stderr, theUsage, DEFAULT_PORT);
    return 1;
  }

  calcLocalAddr();

  if (getenv(ENV_VAR_CHECKPOINT_DIR) != NULL) {
    ckptDir = getenv(ENV_VAR_CHECKPOINT_DIR);
  } else {
    ckptDir = get_current_dir_name();
  }

  /*Test if the listener socket is already open*/
  if ( fcntl(PROTECTED_COORD_FD, F_GETFD) != -1 ) {
    listenSock = new jalib::JServerSocket ( PROTECTED_COORD_FD );
    JASSERT ( listenSock->port() != -1 ) .Text ( "Invalid listener socket" );
    JTRACE ( "Using already created listener socket" ) ( listenSock->port() );
  } else {

    errno = 0;
    listenSock = new jalib::JServerSocket(jalib::JSockAddr::ANY, thePort, 128);
    JASSERT ( listenSock->isValid() ) ( thePort ) ( JASSERT_ERRNO )
      .Text ( "Failed to create listen socket."
       "\nIf msg is \"Address already in use\", this may be an old coordinator."
       "\nKill default coordinator and try again:  dmtcp_command -q"
       "\nIf that fails, \"pkill -9 dmtcp_coord\","
       " and try again in a minute or so." );
  }

  thePort = listenSock->port();
  if (!thePortFile.empty()) {
    Util::writeCoordPortToFile(thePort, thePortFile.c_str());
  }
  JTRACE("Listening on port")(thePort);

  //parse checkpoint interval
  const char* interval = getenv ( ENV_VAR_CKPT_INTR );
  if ( interval != NULL ) {
    theDefaultCheckpointInterval = jalib::StringToInt ( interval );
    theCheckpointInterval = theDefaultCheckpointInterval;
  }

#if 0
  if (!quiet) {
    JASSERT_STDERR <<
      "dmtcp_coordinator starting..." <<
      "\n    Port: " << thePort <<
      "\n    Checkpoint Interval: ";
    if(theCheckpointInterval==0)
      JASSERT_STDERR << "disabled (checkpoint manually instead)";
    else
      JASSERT_STDERR << theCheckpointInterval;
    JASSERT_STDERR  <<
      "\n    Exit on last client: " << exitOnLast << "\n";
  }
#else
  if (!quiet) {
    fprintf(stderr, "dmtcp_coordinator starting..."
            "\n    Host: %s (%s)"
            "\n    Port: %d"
            "\n    Checkpoint Interval: ",
            coordHostname.c_str(), inet_ntoa(localhostIPAddr), thePort);
    if (theCheckpointInterval==0)
      fprintf(stderr, "disabled (checkpoint manually instead)");
    else
      fprintf(stderr, "%d", theCheckpointInterval);
    fprintf(stderr, "\n    Exit on last client: %d\n", exitOnLast);
  }
#endif

  if (daemon) {
    if (!quiet) {
      JASSERT_STDERR  << "Backgrounding...\n";
    }
    int fd = -1;
    if (!useLogFile) {
      fd = open("/dev/null", O_RDWR);
      JASSERT(dup2(fd, STDIN_FILENO) == STDIN_FILENO);
    } else {
      fd = open(logFilename.c_str(), O_CREAT|O_WRONLY|O_APPEND, 0666);
      JASSERT_SET_LOG(logFilename, "", "");
      int nullFd = open("/dev/null", O_RDWR);
      JASSERT(dup2(nullFd, STDIN_FILENO) == STDIN_FILENO);
      close(nullFd);
    }
    JASSERT(dup2(fd, STDOUT_FILENO) == STDOUT_FILENO);
    JASSERT(dup2(fd, STDERR_FILENO) == STDERR_FILENO);
    JASSERT_CLOSE_STDERR();
    if (fd > STDERR_FILENO) {
      close(fd);
    }

    if (fork() > 0) {
      JTRACE ( "Parent Exiting after fork()" );
      exit(0);
    }
    //pid_t sid = setsid();
  } else {
    if (!quiet) {
      JASSERT_STDERR  <<
        "Type '?' for help." <<
        "\n\n";
    }
  }

  /* We set up the signal handler for SIGINT and SIGALRM.
   * SIGINT is used to send DMT_KILL_PEER message to all the connected peers
   * before exiting.
   * SIGALRM is used for interval checkpointing.
   */
  setupSignalHandlers();

  /* If the coordinator was started transparently by dmtcp_launch, then we
   * want to block signals, such as SIGINT.  To see why this is important:
   * % gdb dmtcp_launch a.out
   * (gdb) run
   * ^C   # Stop gdb to get its attention, and continue debugging.
   * # The above scenario causes the SIGINT to go to a.out and its child,
   * # the dmtcp_coordinator.  The coord then triggers the SIGINT handler,
   * # which sends DMT_KILL_PEER to kill a.out.
   */
  if ( exitOnLast && daemon ) {
    sigset_t set;
    sigfillset(&set);
    // unblock SIGALRM because we are using alarm() for interval checkpointing
    sigdelset(&set, SIGALRM);
    // sigprocmask is only per-thread; but the coordinator is single-threaded.
    sigprocmask(SIG_BLOCK, &set, NULL);
  }

  prog.eventLoop(daemon);
  return 0;
}