~free.ekanayaka/landscape-client/lucid-1.5.0-0ubuntu0.10.04.0

« back to all changes in this revision

Viewing changes to landscape/lib/lock.py

  • Committer: Bazaar Package Importer
  • Author(s): Rick Clark
  • Date: 2008-09-08 16:35:57 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20080908163557-l3ixzj5dxz37wnw2
Tags: 1.0.18-0ubuntu1
New upstream release 

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import fcntl
 
2
import time
 
3
import os
 
4
 
 
5
 
 
6
class LockError(Exception):
 
7
    """Raised when unable to lock a file."""
 
8
 
 
9
 
 
10
def lock_path(path, timeout=0):
 
11
    fd = os.open(path, os.O_CREAT)
 
12
    flags = fcntl.fcntl(fd, fcntl.F_GETFD, 0)
 
13
    flags |= fcntl.FD_CLOEXEC
 
14
    fcntl.fcntl(fd, fcntl.F_SETFD, flags)
 
15
 
 
16
    started = time.time()
 
17
 
 
18
    while True:
 
19
        try:
 
20
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
 
21
        except IOError, e:
 
22
            if started < time.time() - timeout:
 
23
                raise LockError("Couldn't obtain lock")
 
24
        else:
 
25
            break
 
26
        time.sleep(0.1)
 
27
 
 
28
    def unlock_path():
 
29
        fcntl.flock(fd, fcntl.LOCK_UN)
 
30
        os.close(fd)
 
31
 
 
32
    return unlock_path