summaryrefslogtreecommitdiffstats
path: root/geo-replication/syncdaemon/master.py
blob: babf94cbc1139dfed33cebcbec6ac9b2287a0b17 (plain)
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
#
# Copyright (c) 2011-2014 Red Hat, Inc. <http://www.redhat.com>
# This file is part of GlusterFS.

# This file is licensed to you under your choice of the GNU Lesser
# General Public License, version 3 or any later version (LGPLv3 or
# later), or the GNU General Public License, version 2 (GPLv2), in all
# cases as published by the Free Software Foundation.
#

import os
import sys
import time
import stat
import json
import logging
import fcntl
import socket
import string
import errno
import tarfile
from errno import ENOENT, ENODATA, EPIPE, EEXIST, EACCES, EAGAIN
from threading import Condition, Lock
from datetime import datetime
from gconf import gconf
from tempfile import NamedTemporaryFile
from syncdutils import Thread, GsyncdError, boolify, escape
from syncdutils import unescape, select, gauxpfx, md5hex, selfkill
from syncdutils import lstat, errno_wrap
from syncdutils import NoPurgeTimeAvailable, PartialHistoryAvailable

URXTIME = (-1, 0)

# Default rollover time set in changelog translator
# changelog rollover time is hardcoded here to avoid the
# xsync usage when crawling switch happens from history
# to changelog. If rollover time increased in translator
# then geo-rep can enter into xsync crawl after history
# crawl before starting live changelog crawl.
CHANGELOG_ROLLOVER_TIME = 15

# Utility functions to help us to get to closer proximity
# of the DRY principle (no, don't look for elevated or
# perspectivistic things here)


def _xtime_now():
    t = time.time()
    sec = int(t)
    nsec = int((t - sec) * 1000000)
    return (sec, nsec)


def _volinfo_hook_relax_foreign(self):
    volinfo_sys = self.get_sys_volinfo()
    fgn_vi = volinfo_sys[self.KFGN]
    if fgn_vi:
        expiry = fgn_vi['timeout'] - int(time.time()) + 1
        logging.info('foreign volume info found, waiting %d sec for expiry' %
                     expiry)
        time.sleep(expiry)
        volinfo_sys = self.get_sys_volinfo()
    return volinfo_sys


# The API!

def gmaster_builder(excrawl=None):
    """produce the GMaster class variant corresponding
       to sync mode"""
    this = sys.modules[__name__]
    modemixin = gconf.special_sync_mode
    if not modemixin:
        modemixin = 'normal'
    changemixin = 'xsync' if gconf.change_detector == 'xsync' \
                  else excrawl or gconf.change_detector
    logging.info('setting up %s change detection mode' % changemixin)
    modemixin = getattr(this, modemixin.capitalize() + 'Mixin')
    crawlmixin = getattr(this, 'GMaster' + changemixin.capitalize() + 'Mixin')
    sendmarkmixin = boolify(
        gconf.use_rsync_xattrs) and SendmarkRsyncMixin or SendmarkNormalMixin
    purgemixin = boolify(
        gconf.ignore_deletes) and PurgeNoopMixin or PurgeNormalMixin
    syncengine = boolify(gconf.use_tarssh) and TarSSHEngine or RsyncEngine

    class _GMaster(crawlmixin, modemixin, sendmarkmixin,
                   purgemixin, syncengine):
        pass
    return _GMaster


# Mixin classes that implement the data format
# and logic particularities of the certain
# sync modes

class NormalMixin(object):

    """normal geo-rep behavior"""

    minus_infinity = URXTIME

    # following staticmethods ideally would be
    # methods of an xtime object (in particular,
    # implementing the hooks needed for comparison
    # operators), but at this point we don't yet
    # have a dedicated xtime class

    @staticmethod
    def serialize_xtime(xt):
        return "%d.%d" % tuple(xt)

    @staticmethod
    def deserialize_xtime(xt):
        return tuple(int(x) for x in xt.split("."))

    @staticmethod
    def native_xtime(xt):
        return xt

    @staticmethod
    def xtime_geq(xt0, xt1):
        return xt0 >= xt1

    def make_xtime_opts(self, is_master, opts):
        if not 'create' in opts:
            opts['create'] = is_master
        if not 'default_xtime' in opts:
            opts['default_xtime'] = URXTIME

    def xtime_low(self, rsc, path, **opts):
        if rsc == self.master:
            xt = rsc.server.xtime(path, self.uuid)
        else:
            xt = rsc.server.stime(path, self.uuid)
            if isinstance(xt, int) and xt == ENODATA:
                xt = rsc.server.xtime(path, self.uuid)
                if not isinstance(xt, int):
                    self.slave.server.set_stime(path, self.uuid, xt)
        if isinstance(xt, int) and xt != ENODATA:
            return xt
        if xt == ENODATA or xt < self.volmark:
            if opts['create']:
                xt = _xtime_now()
                rsc.server.aggregated.set_xtime(path, self.uuid, xt)
            else:
                xt = opts['default_xtime']
        return xt

    def keepalive_payload_hook(self, timo, gap):
        # first grab a reference as self.volinfo
        # can be changed in main thread
        vi = self.volinfo
        if vi:
            # then have a private copy which we can mod
            vi = vi.copy()
            vi['timeout'] = int(time.time()) + timo
        else:
            # send keep-alives more frequently to
            # avoid a delay in announcing our volume info
            # to slave if it becomes established in the
            # meantime
            gap = min(10, gap)
        return (vi, gap)

    def volinfo_hook(self):
        return self.get_sys_volinfo()

    def xtime_reversion_hook(self, path, xtl, xtr):
        if xtr > xtl:
            raise GsyncdError("timestamp corruption for " + path)

    def need_sync(self, e, xte, xtrd):
        return xte > xtrd

    def set_slave_xtime(self, path, mark):
        self.slave.server.set_stime(path, self.uuid, mark)
        # self.slave.server.set_xtime_remote(path, self.uuid, mark)


class PartialMixin(NormalMixin):

    """a variant tuned towards operation with a master
       that has partial info of the slave (brick typically)"""

    def xtime_reversion_hook(self, path, xtl, xtr):
        pass


class RecoverMixin(NormalMixin):

    """a variant that differs from normal in terms
       of ignoring non-indexed files"""

    @staticmethod
    def make_xtime_opts(is_master, opts):
        if not 'create' in opts:
            opts['create'] = False
        if not 'default_xtime' in opts:
            opts['default_xtime'] = URXTIME

    def keepalive_payload_hook(self, timo, gap):
        return (None, gap)

    def volinfo_hook(self):
        return _volinfo_hook_relax_foreign(self)

# Further mixins for certain tunable behaviors


class SendmarkNormalMixin(object):

    def sendmark_regular(self, *a, **kw):
        return self.sendmark(*a, **kw)


class SendmarkRsyncMixin(object):

    def sendmark_regular(self, *a, **kw):
        pass


class PurgeNormalMixin(object):

    def purge_missing(self, path, names):
        self.slave.server.purge(path, names)


class PurgeNoopMixin(object):

    def purge_missing(self, path, names):
        pass


class TarSSHEngine(object):

    """Sync engine that uses tar(1) piped over ssh(1)
       for data transfers. Good for lots of small files.
    """

    def a_syncdata(self, files):
        self.unlinked_gfids = []
        logging.debug('files: %s' % (files))
        self.current_files_skipped_count = 0
        del self.skipped_gfid_list[:]
        for f in files:
            pb = self.syncer.add(f)

            def regjob(se, xte, pb):
                rv = pb.wait()
                if rv[0]:
                    logging.debug('synced ' + se)
                    return True
                else:
                    # stat check for file presence
                    st = lstat(se)
                    if isinstance(st, int):
                        # file got unlinked in the interim
                        self.unlinked_gfids.append(se)
                        return True

                    se_list = se.split('/')
                    self.current_files_skipped_count += 1
                    self.skipped_gfid_list.append(se_list[1])
            self.add_job(self.FLAT_DIR_HIERARCHY, 'reg', regjob, f, None, pb)

    def syncdata_wait(self):
        if self.wait(self.FLAT_DIR_HIERARCHY, None):
            return True

    def syncdata(self, files):
        self.a_syncdata(files)
        self.syncdata_wait()


class RsyncEngine(object):

    """Sync engine that uses rsync(1) for data transfers"""

    def a_syncdata(self, files):
        self.unlinked_gfids = []
        logging.debug('files: %s' % (files))
        self.current_files_skipped_count = 0
        del self.skipped_gfid_list[:]
        for f in files:
            logging.debug('candidate for syncing %s' % f)
            pb = self.syncer.add(f)

            def regjob(se, xte, pb):
                rv = pb.wait()
                if rv[0]:
                    logging.debug('synced ' + se)
                    return True
                else:
                    # stat to check if the file exist
                    st = lstat(se)
                    if isinstance(st, int):
                        # file got unlinked in the interim
                        self.unlinked_gfids.append(se)
                        return True

                    se_list = se.split('/')
                    self.current_files_skipped_count += 1
                    self.skipped_gfid_list.append(se_list[1])
            self.add_job(self.FLAT_DIR_HIERARCHY, 'reg', regjob, f, None, pb)

    def syncdata_wait(self):
        if self.wait(self.FLAT_DIR_HIERARCHY, None):
            return True

    def syncdata(self, files):
        self.a_syncdata(files)
        self.syncdata_wait()


class GMasterCommon(object):

    """abstract class impementling master role"""

    KFGN = 0
    KNAT = 1

    def get_sys_volinfo(self):
        """query volume marks on fs root

        err out on multiple foreign masters
        """
        fgn_vis, nat_vi = (
            self.master.server.aggregated.foreign_volume_infos(),
            self.master.server.aggregated.native_volume_info())
        fgn_vi = None
        if fgn_vis:
            if len(fgn_vis) > 1:
                raise GsyncdError("cannot work with multiple foreign masters")
            fgn_vi = fgn_vis[0]
        return fgn_vi, nat_vi

    @property
    def uuid(self):
        if self.volinfo:
            return self.volinfo['uuid']

    @property
    def volmark(self):
        if self.volinfo:
            return self.volinfo['volume_mark']

    def xtime(self, path, *a, **opts):
        """get amended xtime

        as of amending, we can create missing xtime, or
        determine a valid value if what we get is expired
        (as of the volume mark expiry); way of amendig
        depends on @opts and on subject of query (master
        or slave).
        """
        if a:
            rsc = a[0]
        else:
            rsc = self.master
        self.make_xtime_opts(rsc == self.master, opts)
        return self.xtime_low(rsc, path, **opts)

    def get_initial_crawl_data(self):
        # while persisting only 'files_syncd' is non-zero, rest of
        # the stats are nulls. lets keep it that way in case they
        # are needed to be used some day...
        default_data = {'files_syncd': 0,
                        'files_remaining': 0,
                        'bytes_remaining': 0,
                        'purges_remaining': 0,
                        'total_files_skipped': 0}
        if getattr(gconf, 'state_detail_file', None):
            try:
                with open(gconf.state_detail_file, 'r+') as f:
                    loaded_data = json.load(f)
                    diff_data = set(default_data) - set(loaded_data)
                    if len(diff_data):
                        for i in diff_data:
                            loaded_data[i] = default_data[i]
                    return loaded_data
            except IOError:
                logging.warn('Creating new gconf.state_detail_file.')
                # Create file with initial data
                try:
                    with open(gconf.state_detail_file, 'wb') as f:
                        json.dump(default_data, f)
                    return default_data
                except:
                    raise
        return default_data

    def update_crawl_data(self):
        if getattr(gconf, 'state_detail_file', None):
            try:
                same_dir = os.path.dirname(gconf.state_detail_file)
                with NamedTemporaryFile(dir=same_dir, delete=False) as tmp:
                    json.dump(self.total_crawl_stats, tmp)
                    tmp.flush()
                    os.fsync(tmp.fileno())
                    os.rename(tmp.name, gconf.state_detail_file)
            except (IOError, OSError):
                raise

    def __init__(self, master, slave):
        self.master = master
        self.slave = slave
        self.jobtab = {}
        if boolify(gconf.use_tarssh):
            logging.info("using 'tar over ssh' as the sync engine")
            self.syncer = Syncer(slave, self.slave.tarssh, [2])
        else:
            logging.info("using 'rsync' as the sync engine")
            # partial transfer (cf. rsync(1)), that's normal
            self.syncer = Syncer(slave, self.slave.rsync, [23, 24])
        # crawls vs. turns:
        # - self.crawls is simply the number of crawl() invocations on root
        # - one turn is a maximal consecutive sequence of crawls so that each
        #   crawl in it detects a change to be synced
        # - self.turns is the number of turns since start
        # - self.total_turns is a limit so that if self.turns reaches it, then
        #   we exit (for diagnostic purposes)
        # so, eg., if the master fs changes unceasingly, self.turns will remain
        # 0.
        self.crawls = 0
        self.turns = 0
        self.total_turns = int(gconf.turns)
        self.crawl_start = datetime.now()
        self.lastreport = {'crawls': 0, 'turns': 0, 'time': 0}
        self.total_crawl_stats = None
        self.start = None
        self.change_seen = None
        # the actual volinfo we make use of
        self.volinfo = None
        self.terminate = False
        self.sleep_interval = 1
        self.checkpoint_thread = None
        self.current_files_skipped_count = 0
        self.skipped_gfid_list = []
        self.unlinked_gfids = []

    def init_keep_alive(cls):
        """start the keep-alive thread """
        timo = int(gconf.timeout or 0)
        if timo > 0:
            def keep_alive():
                while True:
                    vi, gap = cls.keepalive_payload_hook(timo, timo * 0.5)
                    cls.slave.server.keep_alive(vi)
                    time.sleep(gap)
            t = Thread(target=keep_alive)
            t.start()

    def mgmt_lock(self):
        """Take management volume lock """
        bname = str(gconf.volume_id) + "_subvol_" + str(gconf.subvol_num) \
            + ".lock"
        mgmt_lock_dir = os.path.join(gconf.meta_volume_mnt, "geo-rep")
        path = os.path.join(mgmt_lock_dir, bname)
        logging.debug("lock_file_path: %s" % path)
        try:
            fd = os.open(path, os.O_CREAT | os.O_RDWR)
        except OSError:
            ex = sys.exc_info()[1]
            if ex.errno == ENOENT:
                logging.info("Creating geo-rep directory in meta volume...")
                try:
                    os.makedirs(mgmt_lock_dir)
                except OSError:
                    ex = sys.exc_info()[1]
                    if ex.errno == EEXIST:
                        pass
                    else:
                        raise
        try:
            fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except:
            ex = sys.exc_info()[1]
            os.close(fd)
            if isinstance(ex, IOError) and ex.errno in (EACCES, EAGAIN):
                # cannot grab, it's taken
                logging.debug("Lock held by someother worker process")
                return False
            raise
        logging.debug("Got the lock")
        return True


    def should_crawl(self):
        if not gconf.use_meta_volume:
            return gconf.glusterd_uuid in self.master.server.node_uuid()

        if not os.path.ismount(gconf.meta_volume_mnt):
            logging.error("Meta-volume is not mounted. Worker Exiting...")
            sys.exit(1)
        return self.mgmt_lock()


    def register(self):
        self.register()

    def crawlwrap(self, oneshot=False, register_time=None):
        if oneshot:
            # it's important to do this during the oneshot crawl as
            # for a passive gsyncd (ie. in a replicate scenario)
            # the keepalive thread would keep the connection alive.
            self.init_keep_alive()

        # If crawlwrap is called when partial history available,
        # then it sets register_time which is the time when geo-rep
        # worker registerd to changelog consumption. Since nsec is
        # not considered in register time, their are chances of skipping
        # changes detection in xsync crawl. This limit will be reset when
        # crawlwrap is called again.
        self.live_changelog_start_time = None
        if register_time:
            self.live_changelog_start_time = (register_time, 0)

        # no need to maintain volinfo state machine.
        # in a cascading setup, each geo-replication session is
        # independent (ie. 'volume-mark' and 'xtime' are not
        # propogated). This is because the slave's xtime is now
        # stored on the master itself. 'volume-mark' just identifies
        # that we are in a cascading setup and need to enable
        # 'geo-replication.ignore-pid-check' option.
        volinfo_sys = self.volinfo_hook()
        self.volinfo = volinfo_sys[self.KNAT]
        inter_master = volinfo_sys[self.KFGN]
        logging.info("%s master with volume id %s ..." %
                     (inter_master and "intermediate" or "primary",
                      self.uuid))
        gconf.configinterface.set('volume_id', self.uuid)
        if self.volinfo:
            if self.volinfo['retval']:
                logging.warn("master cluster's info may not be valid %d" %
                             self.volinfo['retval'])
            self.start_checkpoint_thread()
        else:
            raise GsyncdError("master volinfo unavailable")
        self.total_crawl_stats = self.get_initial_crawl_data()
        self.lastreport['time'] = time.time()
        logging.info('crawl interval: %d seconds' % self.sleep_interval)

        t0 = time.time()
        crawl = self.should_crawl()
        while not self.terminate:
            if self.start:
                logging.debug("... crawl #%d done, took %.6f seconds" %
                              (self.crawls, time.time() - self.start))
            self.start = time.time()
            should_display_info = self.start - self.lastreport['time'] >= 60
            if should_display_info:
                logging.info("%d crawls, %d turns",
                             self.crawls - self.lastreport['crawls'],
                             self.turns - self.lastreport['turns'])
                self.lastreport.update(crawls=self.crawls,
                                       turns=self.turns,
                                       time=self.start)
            t1 = time.time()
            if int(t1 - t0) >= int(gconf.replica_failover_interval):
                crawl = self.should_crawl()
                t0 = t1
            self.update_worker_remote_node()
            if not crawl:
                self.update_worker_health("Passive")
                # bring up _this_ brick to the cluster stime
                # which is min of cluster (but max of the replicas)
                brick_stime = self.xtime('.', self.slave)
                cluster_stime = self.master.server.aggregated.stime_mnt(
                    '.', '.'.join([str(self.uuid), str(gconf.slave_id)]))
                logging.debug("Cluster stime: %s | Brick stime: %s" %
                              (repr(cluster_stime), repr(brick_stime)))
                if not isinstance(cluster_stime, int):
                    if brick_stime < cluster_stime:
                        self.slave.server.set_stime(
                            self.FLAT_DIR_HIERARCHY, self.uuid, cluster_stime)
                        # Purge all changelogs available in processing dir
                        # less than cluster_stime
                        proc_dir = os.path.join(self.setup_working_dir(),
                                                ".processing")

                        if os.path.exists(proc_dir):
                            to_purge = [f for f in os.listdir(proc_dir)
                                        if (f.startswith("CHANGELOG.") and
                                            int(f.split('.')[-1]) <
                                            cluster_stime[0])]
                            for f in to_purge:
                                os.remove(os.path.join(proc_dir, f))

                time.sleep(5)
                continue
            self.update_worker_health("Active")
            self.crawl()
            if oneshot:
                return
            time.sleep(self.sleep_interval)

    @classmethod
    def _checkpt_param(cls, chkpt, prm, xtimish=True):
        """use config backend to lookup a parameter belonging to
           checkpoint @chkpt"""
        cprm = gconf.configinterface.get_realtime('checkpoint_' + prm)
        if not cprm:
            return
        chkpt_mapped, val = cprm.split(':', 1)
        if unescape(chkpt_mapped) != chkpt:
            return
        if xtimish:
            val = cls.deserialize_xtime(val)
        return val

    @classmethod
    def _set_checkpt_param(cls, chkpt, prm, val, xtimish=True):
        """use config backend to store a parameter associated
           with checkpoint @chkpt"""
        if xtimish:
            val = cls.serialize_xtime(val)
        gconf.configinterface.set(
            'checkpoint_' + prm, "%s:%s" % (escape(chkpt), val))

    @staticmethod
    def humantime(*tpair):
        """format xtime-like (sec, nsec) pair to human readable format"""
        ts = datetime.fromtimestamp(float('.'.join(str(n) for n in tpair))).\
            strftime("%Y-%m-%d %H:%M:%S")
        if len(tpair) > 1:
            ts += '.' + str(tpair[1])
        return ts

    def _crawl_time_format(self, crawl_time):
        # Ex: 5 years, 4 days, 20:23:10
        years, days = divmod(crawl_time.days, 365.25)
        years = int(years)
        days = int(days)

        date = ""
        m, s = divmod(crawl_time.seconds, 60)
        h, m = divmod(m, 60)

        if years != 0:
            date += "%s %s " % (years, "year" if years == 1 else "years")
        if days != 0:
            date += "%s %s " % (days, "day" if days == 1 else "days")

        date += "%s:%s:%s" % (string.zfill(h, 2),
                              string.zfill(m, 2), string.zfill(s, 2))
        return date

    def checkpt_service(self, chan, chkpt):
        """checkpoint service loop

        monitor and verify checkpoint status for @chkpt, and listen
        for incoming requests for whom we serve a pretty-formatted
        status report"""
        while True:
            chkpt = gconf.configinterface.get_realtime("checkpoint")
            if not chkpt:
                gconf.configinterface.delete("checkpoint_completed")
                gconf.configinterface.delete("checkpoint_target")
                # dummy loop for the case when there is no checkpt set
                select([chan], [], [])
                conn, _ = chan.accept()
                conn.send('\0')
                conn.close()
                continue

            checkpt_tgt = self._checkpt_param(chkpt, 'target')
            if not checkpt_tgt:
                checkpt_tgt = self.xtime('.')
                if isinstance(checkpt_tgt, int):
                    raise GsyncdError("master root directory is "
                                      "unaccessible (%s)",
                                      os.strerror(checkpt_tgt))
                self._set_checkpt_param(chkpt, 'target', checkpt_tgt)
            logging.debug("checkpoint target %s has been determined "
                          "for checkpoint %s" %
                          (repr(checkpt_tgt), chkpt))

            # check if the label is 'now'
            chkpt_lbl = chkpt
            try:
                x1, x2 = chkpt.split(':')
                if x1 == 'now':
                    chkpt_lbl = "as of " + self.humantime(x2)
            except:
                pass
            completed = self._checkpt_param(chkpt, 'completed', xtimish=False)
            if completed:
                completed = tuple(int(x) for x in completed.split('.'))
            s, _, _ = select([chan], [], [], (not completed) and 5 or None)
            # either request made and we re-check to not
            # give back stale data, or we still hunting for completion
            if (self.native_xtime(checkpt_tgt) and (
                    self.native_xtime(checkpt_tgt) < self.volmark)):
                # indexing has been reset since setting the checkpoint
                status = "is invalid"
            else:
                xtr = self.xtime('.', self.slave)
                if isinstance(xtr, int):
                    raise GsyncdError("slave root directory is "
                                      "unaccessible (%s)",
                                      os.strerror(xtr))
                ncompleted = self.xtime_geq(xtr, checkpt_tgt)
                if completed and not ncompleted:  # stale data
                    logging.warn("completion time %s for checkpoint %s "
                                 "became stale" %
                                 (self.humantime(*completed), chkpt))
                    completed = None
                    gconf.configinterface.delete('checkpoint_completed')
                if ncompleted and not completed:  # just reaching completion
                    completed = "%.6f" % time.time()
                    self._set_checkpt_param(
                        chkpt, 'completed', completed, xtimish=False)
                    completed = tuple(int(x) for x in completed.split('.'))
                    logging.info("checkpoint %s completed" % chkpt)
                status = completed and \
                    "completed at " + self.humantime(completed[0]) or \
                    "not reached yet"
            if s:
                conn = None
                try:
                    conn, _ = chan.accept()
                    try:
                        conn.send("checkpoint %s is %s\0" %
                                  (chkpt_lbl, status))
                    except:
                        exc = sys.exc_info()[1]
                        if ((isinstance(exc, OSError) or isinstance(
                                exc, IOError)) and exc.errno == EPIPE):
                            logging.debug('checkpoint client disconnected')
                        else:
                            raise
                finally:
                    if conn:
                        conn.close()

    def start_checkpoint_thread(self):
        """prepare and start checkpoint service"""
        if self.checkpoint_thread or not (
            getattr(gconf, 'state_socket_unencoded', None) and getattr(
                gconf, 'socketdir', None)
        ):
            return
        chan = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        state_socket = os.path.join(
            gconf.socketdir, md5hex(gconf.state_socket_unencoded) + ".socket")
        try:
            os.unlink(state_socket)
        except:
            if sys.exc_info()[0] == OSError:
                pass
        chan.bind(state_socket)
        chan.listen(1)
        chkpt = gconf.configinterface.get_realtime("checkpoint")
        t = Thread(target=self.checkpt_service, args=(chan, chkpt))
        t.start()
        self.checkpoint_thread = t

    def add_job(self, path, label, job, *a, **kw):
        """insert @job function to job table at @path with @label"""
        if self.jobtab.get(path) is None:
            self.jobtab[path] = []
        self.jobtab[path].append((label, a, lambda: job(*a, **kw)))

    def add_failjob(self, path, label):
        """invoke .add_job with a job that does nothing just fails"""
        logging.debug('salvaged: ' + label)
        self.add_job(path, label, lambda: False)

    def wait(self, path, *args):
        """perform jobs registered for @path

        Reset jobtab entry for @path,
        determine success as the conjunction of
        success of all the jobs. In case of
        success, call .sendmark on @path
        """
        jobs = self.jobtab.pop(path, [])
        succeed = True
        for j in jobs:
            ret = j[-1]()
            if not ret:
                succeed = False
        if succeed and not args[0] is None:
            self.sendmark(path, *args)
        return succeed

    def sendmark(self, path, mark, adct=None):
        """update slave side xtime for @path to master side xtime

        also can send a setattr payload (see Server.setattr).
        """
        if adct:
            self.slave.server.setattr(path, adct)
        self.set_slave_xtime(path, mark)


class XCrawlMetadata(object):
    def __init__(self, st_uid, st_gid, st_mode, st_atime, st_mtime):
        self.st_uid = int(st_uid)
        self.st_gid = int(st_gid)
        self.st_mode = int(st_mode)
        self.st_atime = float(st_atime)
        self.st_mtime = float(st_mtime)


class GMasterChangelogMixin(GMasterCommon):

    """ changelog based change detection and syncing """

    # index for change type and entry
    IDX_START = 0
    IDX_END = 2
    UNLINK_ENTRY = 2

    POS_GFID = 0
    POS_TYPE = 1
    POS_ENTRY1 = -1

    TYPE_META = "M "
    TYPE_GFID = "D "
    TYPE_ENTRY = "E "

    # flat directory hierarchy for gfid based access
    FLAT_DIR_HIERARCHY = '.'

    # maximum retries per changelog before giving up
    MAX_RETRIES = 10

    CHANGELOG_LOG_LEVEL = 9
    CHANGELOG_CONN_RETRIES = 5

    def archive_and_purge_changelogs(self, changelogs):
        # Creates tar file instead of tar.gz, since changelogs will
        # be appended to existing tar. archive name is
        # archive_<YEAR><MONTH>.tar
        archive_name = "archive_%s.tar" % datetime.today().strftime(
            gconf.changelog_archive_format)

        try:
            tar = tarfile.open(os.path.join(self.processed_changelogs_dir,
                                            archive_name),
                               "a")
        except tarfile.ReadError:
            tar = tarfile.open(os.path.join(self.processed_changelogs_dir,
                                            archive_name),
                               "w")

        for f in changelogs:
            try:
                f = os.path.basename(f)
                tar.add(os.path.join(self.processed_changelogs_dir, f),
                        arcname=os.path.basename(f))
            except:
                exc = sys.exc_info()[1]
                if ((isinstance(exc, OSError) or
                     isinstance(exc, IOError)) and exc.errno == ENOENT):
                    continue
                else:
                    tar.close()
                    raise
        tar.close()

        for f in changelogs:
            try:
                f = os.path.basename(f)
                os.remove(os.path.join(self.processed_changelogs_dir, f))
            except OSError as e:
                if e.errno == errno.ENOENT:
                    continue
                else:
                    raise

    def fallback_xsync(self):
        logging.info('falling back to xsync mode')
        gconf.configinterface.set('change-detector', 'xsync')
        selfkill()

    def setup_working_dir(self):
        workdir = os.path.join(gconf.working_dir, md5hex(gconf.local_path))
        logging.debug('changelog working dir %s' % workdir)
        return workdir

    def get_purge_time(self):
        purge_time = self.xtime('.', self.slave)
        if isinstance(purge_time, int):
            purge_time = None
        return purge_time

    def process_change(self, change, done, retry):
        pfx = gauxpfx()
        clist = []
        entries = []
        meta_gfid = set()
        datas = set()

        # basic crawl stats: files and bytes
        files_pending = {'count': 0, 'purge': 0, 'bytes': 0, 'files': []}
        try:
            f = open(change, "r")
            clist = f.readlines()
            f.close()
        except IOError:
            raise

        def edct(op, **ed):
            dct = {}
            dct['op'] = op
            for k in ed:
                if k == 'stat':
                    st = ed[k]
                    dst = dct['stat'] = {}
                    if st:
                        dst['uid'] = st.st_uid
                        dst['gid'] = st.st_gid
                        dst['mode'] = st.st_mode
                        dst['atime'] = st.st_atime
                        dst['mtime'] = st.st_mtime
                else:
                    dct[k] = ed[k]
            return dct

        # entry counts (not purges)
        def entry_update():
            files_pending['count'] += 1

        # purge count
        def purge_update():
            files_pending['purge'] += 1

        for e in clist:
            e = e.strip()
            et = e[self.IDX_START:self.IDX_END]   # entry type
            ec = e[self.IDX_END:].split(' ')      # rest of the bits

            if et == self.TYPE_ENTRY:
                # extract information according to the type of
                # the entry operation. create(), mkdir() and mknod()
                # have mode, uid, gid information in the changelog
                # itself, so no need to stat()...
                ty = ec[self.POS_TYPE]

                # PARGFID/BNAME
                en = unescape(os.path.join(pfx, ec[self.POS_ENTRY1]))
                # GFID of the entry
                gfid = ec[self.POS_GFID]

                if ty in ['UNLINK', 'RMDIR']:
                    # The index of PARGFID/BNAME for UNLINK, RMDIR
                    # is no more the last index. It varies based on
                    # changelog.capture-del-path is enabled or not.
                    en = unescape(os.path.join(pfx, ec[self.UNLINK_ENTRY]))

                    # Remove from DATA list, so that rsync will
                    # not fail
                    pt = os.path.join(pfx, ec[0])
                    if pt in datas:
                        datas.remove(pt)

                    if not boolify(gconf.ignore_deletes):
                        purge_update()
                        entries.append(edct(ty, gfid=gfid, entry=en))
                elif ty in ['CREATE', 'MKDIR', 'MKNOD']:
                    entry_update()
                    # stat information present in the changelog itself
                    entries.append(edct(ty, gfid=gfid, entry=en,
                                        mode=int(ec[2]),
                                        uid=int(ec[3]), gid=int(ec[4])))
                elif ty == "RENAME":
                    go = os.path.join(pfx, gfid)
                    st = lstat(go)
                    if isinstance(st, int):
                        st = {}

                    entry_update()
                    e1 = unescape(os.path.join(pfx, ec[self.POS_ENTRY1 - 1]))
                    entries.append(edct(ty, gfid=gfid, entry=e1, entry1=en,
                                        stat=st))
                else:
                    # stat() to get mode and other information
                    go = os.path.join(pfx, gfid)
                    st = lstat(go)
                    if isinstance(st, int):
                        logging.debug('file %s got purged in the interim' % go)
                        continue

                    if ty == 'LINK':
                        entry_update()
                        entries.append(edct(ty, stat=st, entry=en, gfid=gfid))
                    elif ty == 'SYMLINK':
                        rl = errno_wrap(os.readlink, [en], [ENOENT])
                        if isinstance(rl, int):
                            continue
                        entry_update()
                        entries.append(
                            edct(ty, stat=st, entry=en, gfid=gfid, link=rl))
                    else:
                        logging.warn('ignoring %s [op %s]' % (gfid, ty))
            elif et == self.TYPE_GFID:
                # If self.unlinked_gfids is available, then that means it is
                # retrying the changelog second time. Do not add the GFID's
                # to rsync job if failed previously but unlinked in master
                if self.unlinked_gfids and \
                   os.path.join(pfx, ec[0]) in self.unlinked_gfids:
                    logging.debug("ignoring data, since file purged interim")
                else:
                    datas.add(os.path.join(pfx, ec[0]))
            elif et == self.TYPE_META:
                if ec[1] == 'SETATTR':  # only setattr's for now...
                    if len(ec) == 5:
                        # In xsync crawl, we already have stat data
                        # avoid doing stat again
                        meta_gfid.add((os.path.join(pfx, ec[0]),
                                       XCrawlMetadata(st_uid=ec[2],
                                                      st_gid=ec[3],
                                                      st_mode=ec[4],
                                                      st_atime=ec[5],
                                                      st_mtime=ec[6])))
                    else:
                        meta_gfid.add((os.path.join(pfx, ec[0]), ))
                elif ec[1] == 'SETXATTR':
                    # To sync xattr/acls use rsync/tar, --xattrs and --acls
                    # switch to rsync and tar
                    if boolify(gconf.sync_xattrs) or boolify(gconf.sync_acls):
                        datas.add(os.path.join(pfx, ec[0]))
            else:
                logging.warn('got invalid changelog type: %s' % (et))
        logging.debug('entries: %s' % repr(entries))
        if not retry:
            self.update_worker_cumilitive_status(files_pending)
        # sync namespace
        if entries:
            self.slave.server.entry_ops(entries)
        # sync metadata
        if meta_gfid:
            meta_entries = []
            for go in meta_gfid:
                if len(go) > 1:
                    st = go[1]
                else:
                    st = lstat(go[0])
                if isinstance(st, int):
                    logging.debug('file %s got purged in the interim' % go[0])
                    continue
                meta_entries.append(edct('META', go=go[0], stat=st))
            if meta_entries:
                self.slave.server.meta_ops(meta_entries)
        # sync data
        if datas:
            self.a_syncdata(datas)

    def process(self, changes, done=1):
        tries = 0
        retry = False

        while True:
            self.skipped_gfid_list = []
            self.current_files_skipped_count = 0

            # first, fire all changelog transfers in parallel. entry and
            # metadata are performed synchronously, therefore in serial.
            # However at the end of each changelog, data is synchronized
            # with syncdata_async() - which means it is serial w.r.t
            # entries/metadata of that changelog but happens in parallel
            # with data of other changelogs.

            for change in changes:
                logging.debug('processing change %s' % change)
                self.process_change(change, done, retry)
                if not retry:
                    # number of changelogs processed in the batch
                    self.turns += 1

            # Now we wait for all the data transfers fired off in the above
            # step to complete. Note that this is not ideal either. Ideally
            # we want to trigger the entry/meta-data transfer of the next
            # batch while waiting for the data transfer of the current batch
            # to finish.

            # Note that the reason to wait for the data transfer (vs doing it
            # completely in the background and call the changelog_done()
            # asynchronously) is because this waiting acts as a "backpressure"
            # and prevents a spiraling increase of wait stubs from consuming
            # unbounded memory and resources.

            # update the slave's time with the timestamp of the _last_
            # changelog file time suffix. Since, the changelog prefix time
            # is the time when the changelog was rolled over, introduce a
            # tolerance of 1 second to counter the small delta b/w the
            # marker update and gettimeofday().
            # NOTE: this is only for changelog mode, not xsync.

            # @change is the last changelog (therefore max time for this batch)
            if self.syncdata_wait():
                self.unlinked_gfids = []
                if done:
                    xtl = (int(change.split('.')[-1]) - 1, 0)
                    self.upd_stime(xtl)
                    map(self.changelog_done_func, changes)
                    self.archive_and_purge_changelogs(changes)
                self.update_worker_files_syncd()
                break

            # We do not know which changelog transfer failed, retry everything.
            retry = True
            tries += 1
            if tries == self.MAX_RETRIES:
                logging.warn('changelogs %s could not be processed - '
                             'moving on...' %
                             ' '.join(map(os.path.basename, changes)))
                self.update_worker_total_files_skipped(
                    self.current_files_skipped_count)
                logging.warn('SKIPPED GFID = %s' %
                             ','.join(self.skipped_gfid_list))
                self.update_worker_files_syncd()
                if done:
                    xtl = (int(change.split('.')[-1]) - 1, 0)
                    self.upd_stime(xtl)
                    map(self.changelog_done_func, changes)
                    self.archive_and_purge_changelogs(changes)
                break
            # it's either entry_ops() or Rsync that failed to do it's
            # job. Mostly it's entry_ops() [which currently has a problem
            # of failing to create an entry but failing to return an errno]
            # Therefore we do not know if it's either Rsync or the freaking
            # entry_ops() that failed... so we retry the _whole_ changelog
            # again.
            # TODO: remove entry retries when it's gets fixed.
            logging.warn('incomplete sync, retrying changelogs: %s' %
                         ' '.join(map(os.path.basename, changes)))
            time.sleep(0.5)

    def upd_stime(self, stime, path=None):
        if not path:
            path = self.FLAT_DIR_HIERARCHY
        if not stime == URXTIME:
            self.sendmark(path, stime)

    def get_worker_status_file(self):
        file_name = gconf.local_path + '.status'
        file_name = file_name.replace("/", "_")
        worker_status_file = gconf.georep_session_working_dir + file_name
        return worker_status_file

    def update_worker_status(self, key, value):
        default_data = {"remote_node": "N/A",
                        "worker status": "Not Started",
                        "crawl status": "N/A",
                        "files_syncd": 0,
                        "files_remaining": 0,
                        "bytes_remaining": 0,
                        "purges_remaining": 0,
                        "total_files_skipped": 0}
        worker_status_file = self.get_worker_status_file()
        try:
            with open(worker_status_file, 'r+') as f:
                loaded_data = json.load(f)
                loaded_data[key] = value
                os.ftruncate(f.fileno(), 0)
                os.lseek(f.fileno(), 0, os.SEEK_SET)
                json.dump(loaded_data, f)
                f.flush()
                os.fsync(f.fileno())
        except (IOError, OSError, ValueError):
            logging.info('Creating new %s' % worker_status_file)
            try:
                with open(worker_status_file, 'wb') as f:
                    default_data[key] = value
                    json.dump(default_data, f)
                    f.flush()
                    os.fsync(f.fileno())
            except:
                raise

    def update_worker_cumilitive_status(self, files_pending):
        default_data = {"remote_node": "N/A",
                        "worker status": "Not Started",
                        "crawl status": "N/A",
                        "files_syncd": 0,
                        "files_remaining": 0,
                        "bytes_remaining": 0,
                        "purges_remaining": 0,
                        "total_files_skipped": 0}
        worker_status_file = self.get_worker_status_file()
        try:
            with open(worker_status_file, 'r+') as f:
                loaded_data = json.load(f)
                loaded_data['files_remaining'] = files_pending['count']
                loaded_data['bytes_remaining'] = files_pending['bytes']
                loaded_data['purges_remaining'] = files_pending['purge']
                os.ftruncate(f.fileno(), 0)
                os.lseek(f.fileno(), 0, os.SEEK_SET)
                json.dump(loaded_data, f)
                f.flush()
                os.fsync(f.fileno())
        except (IOError, OSError, ValueError):
            logging.info('Creating new %s' % worker_status_file)
            try:
                with open(worker_status_file, 'wb') as f:
                    default_data['files_remaining'] = files_pending['count']
                    default_data['bytes_remaining'] = files_pending['bytes']
                    default_data['purges_remaining'] = files_pending['purge']
                    json.dump(default_data, f)
                    f.flush()
                    os.fsync(f.fileno())
            except:
                raise

    def update_worker_remote_node(self):
        node = sys.argv[-1]
        node = node.split("@")[-1]
        remote_node_ip = node.split(":")[0]
        remote_node_vol = node.split(":")[3]
        remote_node = remote_node_ip + '::' + remote_node_vol
        self.update_worker_status('remote_node', remote_node)

    def update_worker_health(self, state):
        self.update_worker_status('worker status', state)

    def update_worker_crawl_status(self, state):
        self.update_worker_status('crawl status', state)

    def update_worker_files_syncd(self):
        default_data = {"remote_node": "N/A",
                        "worker status": "Not Started",
                        "crawl status": "N/A",
                        "files_syncd": 0,
                        "files_remaining": 0,
                        "bytes_remaining": 0,
                        "purges_remaining": 0,
                        "total_files_skipped": 0}
        worker_status_file = self.get_worker_status_file()
        try:
            with open(worker_status_file, 'r+') as f:
                loaded_data = json.load(f)
                loaded_data['files_syncd'] += loaded_data['files_remaining']
                loaded_data['files_remaining'] = 0
                loaded_data['bytes_remaining'] = 0
                loaded_data['purges_remaining'] = 0
                os.ftruncate(f.fileno(), 0)
                os.lseek(f.fileno(), 0, os.SEEK_SET)
                json.dump(loaded_data, f)
                f.flush()
                os.fsync(f.fileno())
        except (IOError, OSError, ValueError):
            logging.info('Creating new %s' % worker_status_file)
            try:
                with open(worker_status_file, 'wb') as f:
                    json.dump(default_data, f)
                    f.flush()
                    os.fsync(f.fileno())
            except:
                raise

    def update_worker_files_remaining(self, state):
        self.update_worker_status('files_remaining', state)

    def update_worker_bytes_remaining(self, state):
        self.update_worker_status('bytes_remaining', state)

    def update_worker_purges_remaining(self, state):
        self.update_worker_status('purges_remaining', state)

    def update_worker_total_files_skipped(self, value):
        default_data = {"remote_node": "N/A",
                        "worker status": "Not Started",
                        "crawl status": "N/A",
                        "files_syncd": 0,
                        "files_remaining": 0,
                        "bytes_remaining": 0,
                        "purges_remaining": 0,
                        "total_files_skipped": 0}
        worker_status_file = self.get_worker_status_file()
        try:
            with open(worker_status_file, 'r+') as f:
                loaded_data = json.load(f)
                loaded_data['total_files_skipped'] = value
                loaded_data['files_remaining'] -= value
                os.ftruncate(f.fileno(), 0)
                os.lseek(f.fileno(), 0, os.SEEK_SET)
                json.dump(loaded_data, f)
                f.flush()
                os.fsync(f.fileno())
        except (IOError, OSError, ValueError):
            logging.info('Creating new %s' % worker_status_file)
            try:
                with open(worker_status_file, 'wb') as f:
                    default_data['total_files_skipped'] = value
                    json.dump(default_data, f)
                    f.flush()
                    os.fsync(f.fileno())
            except:
                raise

    def crawl(self):
        self.update_worker_crawl_status("Changelog Crawl")
        changes = []
        # get stime (from the brick) and purge changelogs
        # that are _historical_ to that time.
        purge_time = self.get_purge_time()

        self.changelog_agent.scan()
        self.crawls += 1
        changes = self.changelog_agent.getchanges()
        if changes:
            if purge_time:
                logging.info("slave's time: %s" % repr(purge_time))
                processed = [x for x in changes
                             if int(x.split('.')[-1]) < purge_time[0]]
                for pr in processed:
                    logging.info(
                        'skipping already processed change: %s...' %
                        os.path.basename(pr))
                    self.changelog_done_func(pr)
                    changes.remove(pr)
                self.archive_and_purge_changelogs(processed)

            if changes:
                logging.debug('processing changes %s' % repr(changes))
                self.process(changes)

    def register(self, register_time, changelog_agent):
        self.changelog_agent = changelog_agent
        self.sleep_interval = int(gconf.change_interval)
        self.changelog_done_func = self.changelog_agent.done
        self.processed_changelogs_dir = os.path.join(self.setup_working_dir(),
                                                     ".processed")


class GMasterChangeloghistoryMixin(GMasterChangelogMixin):
    def register(self, register_time, changelog_agent):
        self.changelog_agent = changelog_agent
        self.changelog_register_time = register_time
        self.history_crawl_start_time = register_time
        self.changelog_done_func = self.changelog_agent.history_done
        self.history_turns = 0
        self.processed_changelogs_dir = os.path.join(self.setup_working_dir(),
                                                     ".history/.processed")

    def crawl(self):
        self.history_turns += 1
        self.update_worker_crawl_status("History Crawl")
        purge_time = self.get_purge_time()

        logging.info('starting history crawl... turns: %s, stime: %s'
                     % (self.history_turns, repr(purge_time)))

        if not purge_time or purge_time == URXTIME:
            logging.info("stime not available, abandoning history crawl")
            raise NoPurgeTimeAvailable()

        # Changelogs backend path is hardcoded as
        # <BRICK_PATH>/.glusterfs/changelogs, if user configured to different
        # location then consuming history will not work(Known issue as of now)
        changelog_path = os.path.join(gconf.local_path,
                                      ".glusterfs/changelogs")
        ret, actual_end = self.changelog_agent.history(
            changelog_path,
            purge_time[0],
            self.changelog_register_time,
            int(gconf.sync_jobs))

        # scan followed by getchanges till scan returns zero.
        # history_scan() is blocking call, till it gets the number
        # of changelogs to process. Returns zero when no changelogs
        # to be processed. returns positive value as number of changelogs
        # to be processed, which will be fetched using
        # history_getchanges()
        while self.changelog_agent.history_scan() > 0:
            self.crawls += 1

            changes = self.changelog_agent.history_getchanges()
            if changes:
                if purge_time:
                    logging.info("slave's time: %s" % repr(purge_time))
                    processed = [x for x in changes
                                 if int(x.split('.')[-1]) < purge_time[0]]
                    for pr in processed:
                        logging.info('skipping already processed change: '
                                     '%s...' % os.path.basename(pr))
                        self.changelog_done_func(pr)
                        changes.remove(pr)

            if changes:
                logging.debug('processing changes %s' % repr(changes))
                self.process(changes)

        history_turn_time = int(time.time()) - self.history_crawl_start_time

        logging.info('finished history crawl syncing, endtime: %s, stime: %s'
                     % (actual_end, repr(self.get_purge_time())))

        # If TS returned from history_changelog is < register_time
        # then FS crawl may be required, since history is only available
        # till TS returned from history_changelog
        if actual_end < self.changelog_register_time:
            if self.history_turns < 2:
                sleep_time = 1
                if history_turn_time < CHANGELOG_ROLLOVER_TIME:
                    sleep_time = CHANGELOG_ROLLOVER_TIME - history_turn_time
                time.sleep(sleep_time)
                self.history_crawl_start_time = int(time.time())
                self.crawl()
            else:
                # This exeption will be catched in resource.py and
                # fallback to xsync for the small gap.
                raise PartialHistoryAvailable(str(actual_end))


class GMasterXsyncMixin(GMasterChangelogMixin):

    """
    This crawl needs to be xtime based (as of now
    it's not. this is because we generate CHANGELOG
    file during each crawl which is then processed
    by process_change()).
    For now it's used as a one-shot initial sync
    mechanism and only syncs directories, regular
    files, hardlinks and symlinks.
    """

    XSYNC_MAX_ENTRIES = 1 << 13

    def register(self, register_time=None, changelog_agent=None):
        self.counter = 0
        self.comlist = []
        self.stimes = []
        self.sleep_interval = 60
        self.tempdir = self.setup_working_dir()
        self.tempdir = os.path.join(self.tempdir, 'xsync')
        self.processed_changelogs_dir = self.tempdir
        logging.info('xsync temp directory: %s' % self.tempdir)
        try:
            os.makedirs(self.tempdir)
        except OSError:
            ex = sys.exc_info()[1]
            if ex.errno == EEXIST and os.path.isdir(self.tempdir):
                pass
            else:
                raise

    def crawl(self):
        """
        event dispatcher thread

        this thread dispatches either changelog or synchronizes stime.
        additionally terminates itself on receiving a 'finale' event
        """
        def Xsyncer():
            self.Xcrawl()
        t = Thread(target=Xsyncer)
        t.start()
        logging.info('starting hybrid crawl..., stime: %s'
                     % repr(self.get_purge_time()))
        self.update_worker_crawl_status("Hybrid Crawl")
        while True:
            try:
                item = self.comlist.pop(0)
                if item[0] == 'finale':
                    logging.info('finished hybrid crawl syncing, stime: %s'
                                 % repr(self.get_purge_time()))
                    break
                elif item[0] == 'xsync':
                    logging.info('processing xsync changelog %s' % (item[1]))
                    self.process([item[1]], 0)
                    self.archive_and_purge_changelogs([item[1]])
                elif item[0] == 'stime':
                    logging.debug('setting slave time: %s' % repr(item[1]))
                    self.upd_stime(item[1][1], item[1][0])
                else:
                    logging.warn('unknown tuple in comlist (%s)' % repr(item))
            except IndexError:
                time.sleep(1)

    def write_entry_change(self, prefix, data=[]):
        if not getattr(self, "fh", None):
            self.open()

        self.fh.write("%s %s\n" % (prefix, ' '.join(data)))

    def open(self):
        try:
            self.xsync_change = os.path.join(
                self.tempdir, 'XSYNC-CHANGELOG.' + str(int(time.time())))
            self.fh = open(self.xsync_change, 'w')
        except IOError:
            raise

    def close(self):
        if getattr(self, "fh", None):
            self.fh.flush()
            os.fsync(self.fh.fileno())
            self.fh.close()
            self.fh = None

    def fname(self):
        return self.xsync_change

    def put(self, mark, item):
        self.comlist.append((mark, item))

    def sync_xsync(self, last):
        """schedule a processing of changelog"""
        self.close()
        if self.counter > 0:
            self.put('xsync', self.fname())
        self.counter = 0
        if not last:
            time.sleep(1)  # make sure changelogs are 1 second apart

    def sync_stime(self, stime=None, last=False):
        """schedule a stime synchronization"""
        if stime:
            self.put('stime', stime)
        if last:
            self.put('finale', None)

    def sync_done(self, stime=[], last=False):
        self.sync_xsync(last)
        if stime:
            # Send last as True only for last stime entry
            for st in stime[:-1]:
                self.sync_stime(st, False)

            if stime and stime[-1]:
                self.sync_stime(stime[-1], last)

    def is_sticky(self, path, mo):
        """check for DHTs linkto sticky bit file"""
        sticky = False
        if mo & 01000:
            sticky = self.master.server.linkto_check(path)
        return sticky

    def Xcrawl(self, path='.', xtr_root=None):
        """
        generate a CHANGELOG file consumable by process_change.

        slave's xtime (stime) is _cached_ for comparisons across
        the filesystem tree, but set after directory synchronization.
        """
        if path == '.':
            self.crawls += 1
        if not xtr_root:
            # get the root stime and use it for all comparisons
            xtr_root = self.xtime('.', self.slave)
            if isinstance(xtr_root, int):
                if xtr_root != ENOENT:
                    logging.warn("slave cluster not returning the "
                                 "correct xtime for root (%d)" % xtr_root)
                xtr_root = self.minus_infinity
        xtl = self.xtime(path)
        if isinstance(xtl, int):
            logging.warn("master cluster's xtime not found")
        xtr = self.xtime(path, self.slave)
        if isinstance(xtr, int):
            if xtr != ENOENT:
                logging.warn("slave cluster not returning the "
                             "correct xtime for %s (%d)" % (path, xtr))
            xtr = self.minus_infinity
        xtr = max(xtr, xtr_root)
        if not self.need_sync(path, xtl, xtr):
            if path == '.':
                self.sync_done([(path, xtl)], True)
            return
        self.xtime_reversion_hook(path, xtl, xtr)
        logging.debug("entering " + path)
        dem = self.master.server.entries(path)
        pargfid = self.master.server.gfid(path)
        if isinstance(pargfid, int):
            logging.warn('skipping directory %s' % (path))
        for e in dem:
            bname = e
            e = os.path.join(path, e)
            xte = self.xtime(e)
            if isinstance(xte, int):
                logging.warn("irregular xtime for %s: %s" %
                             (e, errno.errorcode[xte]))
                continue
            if not self.need_sync(e, xte, xtr):
                continue
            st = self.master.server.lstat(e)
            if isinstance(st, int):
                logging.warn('%s got purged in the interim ...' % e)
                continue
            if self.is_sticky(e, st.st_mode):
                logging.debug('ignoring sticky bit file %s' % e)
                continue
            gfid = self.master.server.gfid(e)
            if isinstance(gfid, int):
                logging.warn('skipping entry %s..' % e)
                continue
            mo = st.st_mode
            self.counter += 1 if ((stat.S_ISDIR(mo) or
                                   stat.S_ISLNK(mo) or
                                   stat.S_ISREG(mo))) else 0
            if self.counter == self.XSYNC_MAX_ENTRIES:
                self.sync_done(self.stimes, False)
                self.stimes = []
            if stat.S_ISDIR(mo):
                self.write_entry_change("E", [gfid, 'MKDIR', str(mo), str(
                    st.st_uid), str(st.st_gid), escape(os.path.join(pargfid,
                                                                    bname))])
                self.write_entry_change("M", [gfid, "SETATTR", str(st.st_uid),
                                              str(st.st_gid), str(st.st_mode),
                                              str(st.st_atime),
                                              str(st.st_mtime)])
                self.Xcrawl(e, xtr_root)
                stime_to_update = xte
                # Live Changelog Start time indicates that from that time
                # onwards Live changelogs are available. If we update stime
                # greater than live_changelog_start time then Geo-rep will
                # skip those changelogs as already processed. But Xsync
                # actually failed to sync the deletes and Renames. Update
                # stime as min(Live_changelogs_time, Actual_stime) When it
                # switches to Changelog mode, it syncs Deletes and Renames.
                if self.live_changelog_start_time:
                    stime_to_update = min(self.live_changelog_start_time, xte)
                self.stimes.append((e, stime_to_update))
            elif stat.S_ISLNK(mo):
                self.write_entry_change(
                    "E", [gfid, 'SYMLINK', escape(os.path.join(pargfid,
                                                               bname))])
            elif stat.S_ISREG(mo):
                nlink = st.st_nlink
                nlink -= 1  # fixup backend stat link count
                # if a file has a hardlink, create a Changelog entry as
                # 'LINK' so the slave side will decide if to create the
                # new entry, or to create link.
                if nlink == 1:
                    self.write_entry_change("E",
                                            [gfid, 'MKNOD', str(mo),
                                             str(st.st_uid),
                                             str(st.st_gid),
                                             escape(os.path.join(
                                                 pargfid, bname))])
                else:
                    self.write_entry_change(
                        "E", [gfid, 'LINK', escape(os.path.join(pargfid,
                                                                bname))])
                self.write_entry_change("D", [gfid])
        if path == '.':
            stime_to_update = xtl
            if self.live_changelog_start_time:
                stime_to_update = min(self.live_changelog_start_time, xtl)
            self.stimes.append((path, stime_to_update))
            self.sync_done(self.stimes, True)


class BoxClosedErr(Exception):
    pass


class PostBox(list):

    """synchronized collection for storing things thought of as "requests" """

    def __init__(self, *a):
        list.__init__(self, *a)
        # too bad Python stdlib does not have read/write locks...
        # it would suffivce to grab the lock in .append as reader, in .close as
        # writer
        self.lever = Condition()
        self.open = True
        self.done = False

    def wait(self):
        """wait on requests to be processed"""
        self.lever.acquire()
        if not self.done:
            self.lever.wait()
        self.lever.release()
        return self.result

    def wakeup(self, data):
        """wake up requestors with the result"""
        self.result = data
        self.lever.acquire()
        self.done = True
        self.lever.notifyAll()
        self.lever.release()

    def append(self, e):
        """post a request"""
        self.lever.acquire()
        if not self.open:
            raise BoxClosedErr
        list.append(self, e)
        self.lever.release()

    def close(self):
        """prohibit the posting of further requests"""
        self.lever.acquire()
        self.open = False
        self.lever.release()


class Syncer(object):

    """a staged queue to relay rsync requests to rsync workers

    By "staged queue" its meant that when a consumer comes to the
    queue, it takes _all_ entries, leaving the queue empty.
    (I don't know if there is an official term for this pattern.)

    The queue uses a PostBox to accumulate incoming items.
    When a consumer (rsync worker) comes, a new PostBox is
    set up and the old one is passed on to the consumer.

    Instead of the simplistic scheme of having one big lock
    which synchronizes both the addition of new items and
    PostBox exchanges, use a separate lock to arbitrate consumers,
    and rely on PostBox's synchronization mechanisms take
    care about additions.

    There is a corner case racy situation, producers vs. consumers,
    which is not handled by this scheme: namely, when the PostBox
    exchange occurs in between being passed to the producer for posting
    and the post placement. But that's what Postbox.close is for:
    such a posting will find the PostBox closed, in which case
    the producer can re-try posting against the actual PostBox of
    the queue.

    To aid accumlation of items in the PostBoxen before grabbed
    by an rsync worker, the worker goes to sleep a bit after
    each completed syncjob.
    """

    def __init__(self, slave, sync_engine, resilient_errnos=[]):
        """spawn worker threads"""
        self.slave = slave
        self.lock = Lock()
        self.pb = PostBox()
        self.sync_engine = sync_engine
        self.errnos_ok = resilient_errnos
        for i in range(int(gconf.sync_jobs)):
            t = Thread(target=self.syncjob)
            t.start()

    def syncjob(self):
        """the life of a worker"""
        while True:
            pb = None
            while True:
                self.lock.acquire()
                if self.pb:
                    pb, self.pb = self.pb, PostBox()
                self.lock.release()
                if pb:
                    break
                time.sleep(0.5)
            pb.close()
            po = self.sync_engine(pb)
            if po.returncode == 0:
                ret = (True, 0)
            elif po.returncode in self.errnos_ok:
                ret = (False, po.returncode)
            else:
                po.errfail()
            pb.wakeup(ret)

    def add(self, e):
        while True:
            pb = self.pb
            try:
                pb.append(e)
                return pb
            except BoxClosedErr:
                pass