This file is indexed.

/usr/lib/python2.7/dist-packages/myghty/synchronization.py is in python-myghty 1.1-6.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# $Id: synchronization.py 2013 2005-12-31 03:19:39Z zzzeek $
# synchronization.py - synchronization functions for Myghty
# Copyright (C) 2004, 2005 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of Myghty and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
#

__all__  = ["Synchronizer", "NameLock", "_threading", "_thread"]


import os, weakref, tempfile, re, sys
from myghty.util import *

try:
    import thread as _thread
    import threading as _threading
except ImportError:
    import dummy_thread as _thread
    import dummy_threading as _threading

# check for fcntl module
try:
    sys.getwindowsversion()
    has_flock = False
except:
    try:
        import fcntl
        has_flock = True
    except ImportError:
        has_flock = False


class NameLock:
    """a proxy for an RLock object that is stored in a name 
    based registry.  
    
    Multiple threads can get a reference to the same RLock based on 
    the name alone, and synchronize operations related to that name.
    """
     
    locks = WeakValuedRegistry()

    class NLContainer:
        """cant put Lock as a weakref"""
        def __init__(self, reentrant):
            if reentrant:
                self.lock = _threading.RLock()
            else:
                self.lock = _threading.Lock()
        def __call__(self):
            return self.lock

    def __init__(self, identifier = None, reentrant = False):
        self.lock = self._get_lock(identifier, reentrant)

    def acquire(self, wait = True):
        return self.lock().acquire(wait)

    def release(self):
        self.lock().release()

    def _get_lock(self, identifier, reentrant):
        
        if identifier is None:
            return NameLock.NLContainer(reentrant)
        
        return NameLock.locks.get(identifier, lambda: NameLock.NLContainer(reentrant))



synchronizers = WeakValuedRegistry()

    
def Synchronizer(identifier = None, use_files = False, lock_dir = None, digest_filenames = True):
    """
    returns an object that synchronizes a block against many simultaneous 
    read operations and several synchronized write operations. 

    Write operations
    are assumed to be much less frequent than read operations,
    and receive precedence when they request a write lock.

    uses strategies to determine if locking is performed via threading objects
    or file objects.
    
    the identifier identifies a name this Synchronizer is synchronizing against.
    All synchronizers of the same identifier will lock against each other, within
    the effective thread/process scope.
    
    use_files determines if this synchronizer will lock against thread mutexes
    or file locks.  this sets the effective scope of the synchronizer, i.e. 
    it will lock against other synchronizers in the same process, or against
    other synchronizers referencing the same filesystem referenced by lock_dir.
    
    the acquire/relase methods support nested/reentrant operation within a single 
    thread via a recursion counter, so that only the outermost call to 
    acquire/release has any effect.  
    """

    if not has_flock:
        use_files = False
        
    if use_files:
        # FileSynchronizer is one per thread
        return synchronizers.sync_get("file_%s_%s" % (identifier, _thread.get_ident()), lambda: FileSynchronizer(identifier, lock_dir, digest_filenames))
    else:
        # ConditionSynchronizer is shared among threads
        return synchronizers.sync_get("condition_%s" % identifier, lambda: ConditionSynchronizer(identifier))


class SyncState:
    """used to track the current thread's reading/writing state as well as reentrant block counting"""
    
    def __init__(self):
        self.reentrantcount = 0
        self.writing = False
        self.reading = False

class SynchronizerImpl(object):
    """base for the synchronizer implementations.  the acquire/release methods keep track of re-entrant
    calls within the current thread, and delegate to the do_XXX methods when appropriate."""
    
    def __init__(self, *args, **params):
        pass

    def release_read_lock(self):
        state = self.state

        if state.writing: raise "lock is in writing state"
        if not state.reading: raise "lock is not in reading state"
        
        if state.reentrantcount == 1:
            self.do_release_read_lock()
            state.reading = False

        state.reentrantcount -= 1
        
    def acquire_read_lock(self, wait = True):
        state = self.state

        if state.writing: raise "lock is in writing state"
        
        if state.reentrantcount == 0:
            x = self.do_acquire_read_lock(wait)
            if (wait or x):
                state.reentrantcount += 1
                state.reading = True
            return x
        elif state.reading:
            state.reentrantcount += 1
            return True
            
    def release_write_lock(self):
        state = self.state

        if state.reading: raise "lock is in reading state"
        if not state.writing: raise "lock is not in writing state"

        if state.reentrantcount == 1:
            self.do_release_write_lock()
            state.writing = False

        state.reentrantcount -= 1
        
    def acquire_write_lock(self, wait  = True):
        state = self.state

        if state.reading: raise "lock is in reading state"
        
        if state.reentrantcount == 0:
            x = self.do_acquire_write_lock(wait)
            if (wait or x): 
                state.reentrantcount += 1
                state.writing = True
            return x
        elif state.writing:
            state.reentrantcount += 1
            return True

    def do_release_read_lock():raise NotImplementedError()
    def do_acquire_read_lock():raise NotImplementedError()
    def do_release_write_lock():raise NotImplementedError()
    def do_acquire_write_lock():raise NotImplementedError()
    
class FileSynchronizer(SynchronizerImpl):
    """a synchronizer using lock files.   as it relies upon flock(), which
    is not safe to use with the same file descriptor among multiple threads (one file descriptor
    per thread is OK), 
    a separate FileSynchronizer must exist in each thread."""
    
    def __init__(self, identifier, lock_dir, digest_filenames):
        self.state = SyncState()

        if lock_dir is None:
            lock_dir = tempfile.gettempdir()
        else:
            lock_dir = lock_dir

        self.encpath = EncodedPath(lock_dir, [identifier], extension = '.lock', digest = digest_filenames)
        self.filename = self.encpath.path

        self.opened = False
        self.filedesc = None
    
    def _open(self, mode):
        if not self.opened:
            try:
                self.filedesc = os.open(self.filename, mode)
            except OSError, e:
                self.encpath.verify_directory()
                self.filedesc = os.open(self.filename, mode)
            self.opened = True
            
    def do_acquire_read_lock(self, wait):
        self._open(os.O_CREAT | os.O_RDONLY)

        if not wait:
            try:
                fcntl.flock(self.filedesc, fcntl.LOCK_SH | fcntl.LOCK_NB)
                ret = True
            except IOError:
                ret = False
                
            return ret
        else:
            fcntl.flock(self.filedesc, fcntl.LOCK_SH)
            return True
        
        
    def do_acquire_write_lock(self, wait):
        self._open(os.O_CREAT | os.O_WRONLY)

        if not wait:
            try:
                fcntl.flock(self.filedesc, fcntl.LOCK_EX | fcntl.LOCK_NB)
                ret  = True
            except IOError:
                ret = False
                
            return ret
        else:
            fcntl.flock(self.filedesc, fcntl.LOCK_EX);
            return True
    
    def do_release_read_lock(self):
        self.release_all_locks()
    
    def do_release_write_lock(self):
        self.release_all_locks()
    
    def release_all_locks(self):
        if self.opened:
            fcntl.flock(self.filedesc, fcntl.LOCK_UN)
            os.close(self.filedesc)
            self.opened = False

    def __del__(self):
        if os.access(self.filename, os.F_OK):
            try:
                os.remove(self.filename)
            except OSError:
                # occasionally another thread beats us to it
                pass                    


class ConditionSynchronizer(SynchronizerImpl):
    """a synchronizer using a Condition.  this synchronizer is based on threading.Lock() objects and
    therefore must be shared among threads."""
    
    def __init__(self, identifier):
        self.tlocalstate = ThreadLocal(creator = lambda: SyncState())

        # counts how many asynchronous methods are executing
        self.async = 0

        # pointer to thread that is the current sync operation
        self.current_sync_operation = None

        # condition object to lock on
        self.condition = _threading.Condition(_threading.Lock())

    state = property(lambda self: self.tlocalstate())
        
    def do_acquire_read_lock(self, wait = True):    
        self.condition.acquire()

        # see if a synchronous operation is waiting to start
        # or is already running, in which case we wait (or just
        # give up and return)
        if wait:
            while self.current_sync_operation is not None:
                self.condition.wait()
        else:
            if self.current_sync_operation is not None:
                self.condition.release()
                return False

        self.async += 1
        
        self.condition.release()

        if not wait: return True
        
    def do_release_read_lock(self):
        self.condition.acquire()

        self.async -= 1
        
        # check if we are the last asynchronous reader thread 
        # out the door.
        if self.async == 0:
            # yes. so if a sync operation is waiting, notifyAll to wake
            # it up
            if self.current_sync_operation is not None:
                self.condition.notifyAll()
        elif self.async < 0:
            raise "Synchronizer error - too many release_read_locks called"
            
        self.condition.release()

    
    def do_acquire_write_lock(self, wait = True):
        self.condition.acquire()

        # here, we are not a synchronous reader, and after returning,
        # assuming waiting or immediate availability, we will be.
        
        if wait:
            # if another sync is working, wait
            while self.current_sync_operation is not None:
                self.condition.wait()
        else:
            # if another sync is working,
            # we dont want to wait, so forget it
            if self.current_sync_operation is not None:
                self.condition.release()
                return False
            
        # establish ourselves as the current sync 
        # this indicates to other read/write operations
        # that they should wait until this is None again
        self.current_sync_operation = _threading.currentThread()

        # now wait again for asyncs to finish
        if self.async > 0:
            if wait:
                # wait
                self.condition.wait()
            else:
                # we dont want to wait, so forget it
                self.current_sync_operation = None
                self.condition.release()
                return False
        
        self.condition.release()
        
        if not wait: return True

    def do_release_write_lock(self):
        self.condition.acquire()


        if self.current_sync_operation != _threading.currentThread():
            raise "Synchronizer error - current thread doesnt have the write lock"

        # reset the current sync operation so 
        # another can get it
        self.current_sync_operation = None

        # tell everyone to get ready
        self.condition.notifyAll()

        # everyone go !!
        self.condition.release()