• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#encoding=utf-8
2from util.log_info import logger
3import os
4import time
5import errno
6
7class FileLockException(Exception):
8    pass
9
10class FileLock(object):
11    """ A file locking mechanism that has context-manager support so
12        you can use it in a with statement. This should be relatively cross
13        compatible as it doesn't rely on msvcrt or fcntl for the locking.
14    """
15
16
17    def __init__(self, timeout=7200, delay=3):
18        """ Prepare the file locker. Specify the file to lock and optionally
19            the maximum timeout and the delay between each attempt to lock.
20        """
21        self.is_locked = False
22        self.timeout = timeout
23        self.delay = delay
24
25    def _setLockFileName(self, file_name):
26        self.lockfile = file_name
27
28    def acquire(self):
29        """ Acquire the lock, if possible. If the lock is in use, it check again
30            every `wait` seconds. It does this until it either gets the lock or
31            exceeds `timeout` number of seconds, in which case it throws
32            an exception.
33        """
34        start_time = time.time()
35        if os.path.isfile(self.lockfile):
36            try:
37                mark_file_mtime = os.path.getmtime(self.lockfile)
38                if (start_time - mark_file_mtime > self.timeout):
39                    os.remove(self.lockfile)
40            except Exception as e:
41                logger.warning("the lock file is locked by other process")
42
43        while True:
44            try:
45                #open file , other application can't open it
46                self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR)
47                break
48            except OSError as e:
49                if e.errno != errno.EEXIST:
50                    raise
51                if (time.time() - start_time) >= self.timeout:
52                    raise FileLockException("Timeout occured.")
53                time.sleep(self.delay)
54        self.is_locked = True
55
56
57    def release(self):
58        """ Get rid of the lock by deleting the lockfile.
59            When working in a `with` statement, this gets automatically
60            called at the end.
61        """
62        #
63        if self.is_locked :
64            os.close(self.fd)
65            os.unlink(self.lockfile)
66            self.is_locked = False
67
68    def lockFile(self, file_name):
69        """ Activated when used in the with statement.
70            Should automatically acquire a lock to be used in the with block.
71        """
72        self._setLockFileName(file_name)
73        if not self.is_locked:
74            self.acquire()
75        return self
76
77    def releaseFile(self):
78        """ Activated at the end of the with statement.
79            It automatically releases the lock if it isn't locked.
80        """
81        if self.is_locked:
82            self.release()
83
84    def __del__(self):
85        """ Make sure that the FileLock instance doesn't leave a lockfile
86            lying around.
87        """
88        self.release()
89
90
91
92#用法比较有意思,使用with关键字。对with关键字来说,FileLock类先执行__enter__函数,然后,执行with块里的那些代码,执行完了之后,再执行__exit__函数,等价于相当于如下形式:
93#try:
94#    执行 __enter__的内容
95#    执行 with_block.
96#finally:
97#    执行 __exit__内容
98#FileLock在__enter__函数独占式创建或打开一个文件,这个文件不会被其他程序或者进程再次创建或者打开,由此形成lock,执行完代码,在__exit__里,关闭并删除文件