summaryrefslogtreecommitdiffstats
path: root/src/lib/Server/FileMonitor.py
blob: 6fab0c3281fe68b72a7670833c5c350c22d45a86 (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
import logging
import os
import stat
from time import sleep, time

logger = logging.getLogger('Bcfg2.Server.FileMonitor')

def ShouldIgnore(event):
    """Test if the event should be suppresed."""
    # FIXME should move event suppression out of the core
    if event.filename.split('/')[-1] == '.svn':
        return True
    if event.filename.endswith('~') or \
           event.filename.startswith('#') or event.filename.startswith('.#'):
        #logger.error("Suppressing event for file %s" % (event.filename))
        return True
    return False

class Event(object):
    def __init__(self, request_id, filename, code):
        self.requestID = request_id
        self.filename = filename
        self.action = code

    def code2str(self):
        """return static code for event"""
        return self.action

available = {}
class FileMonitor(object):
    """File Monitor baseclass."""
    def __init__(self, debug=False):
        object.__init__(self)
        self.debug = debug
        self.handles = dict()

    def get_event(self):
        return None

    def pending(self):
        return False

    def fileno(self):
        return 0

    def handle_one_event(self, event):
        if ShouldIgnore(event):
            return
        if event.requestID not in self.handles:
            logger.info("Got event for unexpected id %s, file %s" %
                        (event.requestID, event.filename))
            return
        if self.debug:
            logger.info("Dispatching event %s %s to obj %s" \
                        % (event.code2str(), event.filename,
                           self.handles[event.requestID]))
        try:
            self.handles[event.requestID].HandleEvent(event)
        except:
            logger.error("error in handling of gamin event for %s" % \
                         (event.filename), exc_info=1)

    def handle_event_set(self, lock=None):
        count = 1
        event = self.get_event()
        start = time()
        if lock:
            lock.acquire()
        try:
            self.handle_one_event(event)
            while self.pending():
                self.handle_one_event(self.get_event())
                count += 1
        except:
            pass
        if lock:
            lock.release()
        end = time()
        logger.info("Handled %d events in %.03fs" % (count, (end-start)))

    def handle_events_in_interval(self, interval):
        end = time() + interval
        while time() < end:
            if self.pending():
                self.handle_event_set()
                end = time() + interval
            else:
                sleep(0.5)


class FamFam(object):
    """The fam object is a set of callbacks for file alteration events (FAM support)."""

    def __init__(self):
        object.__init__(self)
        self.fm = _fam.open()
        self.users = {}
        self.handles = {}
        self.debug = False

    def fileno(self):
        """return fam file handle number"""
        return self.fm.fileno()

    def handle_event_set(self, _):
        self.Service()

    def handle_events_in_interval(self, interval):
        now = time()
        while (time() - now) < interval:
            if self.Service():
                now = time()

    def AddMonitor(self, path, obj):
        """Add a monitor to path, installing a callback to obj.HandleEvent."""
        mode = os.stat(path)[stat.ST_MODE]
        if stat.S_ISDIR(mode):
            handle = self.fm.monitorDirectory(path, None)
        else:
            handle = self.fm.monitorFile(path, None)
        self.handles[handle.requestID()] = handle
        if obj != None:
            self.users[handle.requestID()] = obj
        return handle.requestID()

    def Service(self, interval=0.50):
        """Handle all fam work."""
        count = 0
        collapsed = 0
        rawevents = []
        start = time()
        now = time()
        while (time() - now) < interval:
            if self.fm.pending():
                while self.fm.pending():
                    count += 1
                    rawevents.append(self.fm.nextEvent())
                now = time()
        unique = []
        bookkeeping = []
        for event in rawevents:
            if ShouldIgnore(event):
                continue
            if event.code2str() != 'changed':
                # process all non-change events
                unique.append(event)
            else:
                if (event.filename, event.requestID) not in bookkeeping:
                    bookkeeping.append((event.filename, event.requestID))
                    unique.append(event)
                else:
                    collapsed += 1
        for event in unique:
            if event.requestID in self.users:
                try:
                    self.users[event.requestID].HandleEvent(event)
                except:
                    logger.error("handling event for file %s" % (event.filename), exc_info=1)
        end = time()
        logger.info("Processed %s fam events in %03.03f seconds. %s coalesced" %
                    (count, (end - start), collapsed))
        return count



class Fam(FileMonitor):
    """
       The fam object is a set of callbacks for
       file alteration events (FAM support).
    """

    def __init__(self, debug=False):
        FileMonitor.__init__(self, debug)
        self.fm = _fam.open()

    def fileno(self):
        return self.fm.fileno()

    def AddMonitor(self, path, obj):
        """Add a monitor to path, installing a callback to obj.HandleEvent."""
        mode = os.stat(path)[stat.ST_MODE]
        if stat.S_ISDIR(mode):
            handle = self.fm.monitorDirectory(path, None)
        else:
            handle = self.fm.monitorFile(path, None)
        if obj != None:
            self.handles[handle.requestID()] = obj
        return handle.requestID()

    def pending(self):
        return self.fm.pending()

    def get_event(self):
        return self.fm.nextEvent()

class Pseudo(FileMonitor):
    """
       The fam object is a set of callbacks for
       file alteration events (static monitor support).
    """

    def __init__(self, debug=False):
        FileMonitor.__init__(self, debug=False)
        self.pending_events = []

    def pending(self):
        return len(self.pending_events) != 0

    def get_event(self):
        return self.pending_events.pop()

    def AddMonitor(self, path, obj):
        """add a monitor to path, installing a callback to obj.HandleEvent"""
        handleID = len(self.handles.keys())
        mode = os.stat(path)[stat.ST_MODE]
        handle = Event(handleID, path, 'exists')
        if stat.S_ISDIR(mode):
            dirList = os.listdir(path)
            self.pending_events.append(handle)
            for includedFile in dirList:
                self.pending_events.append(Event(handleID, includedFile, 'exists'))
            self.pending_events.append(Event(handleID, path, 'endExist'))
        else:
            self.pending_events.append(Event(handleID, path, 'exists'))
        if obj != None:
            self.handles[handleID] = obj
        return handleID


try:
    from gamin import WatchMonitor, GAMCreated, GAMExists, GAMEndExist, \
                      GAMChanged, GAMDeleted, GAMMoved

    class GaminEvent(Event):
        """
        This class provides an event analogous to
        python-fam events based on gamin sources.
        """
        def __init__(self, request_id, filename, code):
            Event.__init__(self, request_id, filename, code)
            action_map = {GAMCreated: 'created', GAMExists: 'exists',
                          GAMChanged: 'changed', GAMDeleted: 'deleted',
                          GAMEndExist: 'endExist', GAMMoved: 'moved'}
            if code in action_map:
                self.action = action_map[code]

    class Gamin(FileMonitor):
        """
        The fam object is a set of callbacks for
        file alteration events (Gamin support)
        """
        def __init__(self, debug=False):
            FileMonitor.__init__(self, debug)
            self.mon = WatchMonitor()
            self.counter = 0
            self.events = []

        def fileno(self):
            return self.mon.get_fd()

        def queue(self, path, action, request_id):
            """queue up the event for later handling"""
            self.events.append(GaminEvent(request_id, path, action))

        def AddMonitor(self, path, obj):
            """Add a monitor to path, installing a callback to obj.HandleEvent."""
            handle = self.counter
            self.counter += 1
            mode = os.stat(path)[stat.ST_MODE]

            # flush queued gamin events
            while self.mon.event_pending():
                self.mon.handle_one_event()

            if stat.S_ISDIR(mode):
                self.mon.watch_directory(path, self.queue, handle)
            else:
                self.mon.watch_file(path, self.queue, handle)
            self.handles[handle] = obj
            return handle

        def pending(self):
            return len(self.events) > 0 or self.mon.event_pending()

        def get_event(self):
            if self.mon.event_pending():
                self.mon.handle_one_event()
            return self.events.pop(0)

    available['gamin'] = Gamin
except ImportError:
    # fall back to _fam
    pass

try:
    import _fam
    available['fam'] = FamFam
except ImportError:
    pass
available['pseudo'] = Pseudo

for fdrv in ['gamin', 'fam', 'pseudo']:
    if fdrv in available:
        available['default'] = available[fdrv]
        break