remove unsued variable
[tools/mic.git] / mic / utils / lock.py
1 # Copyright (c) 2011 Intel, Inc.
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the Free
5 # Software Foundation; either version 2 of the License, or any later version.
6
7 import os
8 import errno
9
10 class LockfileError(Exception):
11     """ Lockfile Exception"""
12     pass
13
14 class SimpleLockfile(object):
15     """ Simple implementation of lockfile """
16     def __init__(self, fpath):
17         self.fpath = fpath
18         self.lockf = None
19
20     def acquire(self):
21         """ acquire the lock """
22         try:
23             self.lockf = os.open(self.fpath,
24                                  os.O_CREAT | os.O_EXCL | os.O_WRONLY)
25         except OSError as err:
26             if err.errno == errno.EEXIST:
27                 raise LockfileError("File %s is locked already" % self.fpath)
28             raise
29         finally:
30             if self.lockf:
31                 os.close(self.lockf)
32
33     def release(self):
34         """ release the lock """
35         try:
36             os.remove(self.fpath)
37         except OSError as err:
38             if err.errno == errno.ENOENT:
39                 pass
40
41     def __enter__(self):
42         self.acquire()
43         return self
44
45     def __exit__(self, *args):
46         self.release()
47
48     def __del__(self):
49         self.release()