def __init__(self):
self.fh = None
self.is_running = False
try:
self.fh = open(LOCK_PATH, 'w')
fcntl.lockf(self.fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
except EnvironmentError as err:
if self.fh is not None:
self.is_running = True
else:
raise
python类LOCK_NB的实例源码
def write_pid_file(pid_file, pid):
import fcntl
import stat
try:
fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
stat.S_IRUSR | stat.S_IWUSR)
except OSError as e:
shell.print_exception(e)
return -1
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
assert flags != -1
flags |= fcntl.FD_CLOEXEC
r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
assert r != -1
# There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
# via fcntl.fcntl. So use lockf instead
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
except IOError:
r = os.read(fd, 32)
if r:
logging.error('already started at pid %s' % common.to_str(r))
else:
logging.error('already started')
os.close(fd)
return -1
os.ftruncate(fd, 0)
os.write(fd, common.to_bytes(str(pid)))
return 0
def openLocked(path, mode="w"):
if os.name == "posix":
import fcntl
f = open(path, mode)
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
else:
f = open(path, mode)
return f
def write_pid_file(pid_file, pid):
import fcntl
import stat
try:
fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
stat.S_IRUSR | stat.S_IWUSR)
except OSError as e:
shell.print_exception(e)
return -1
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
assert flags != -1
flags |= fcntl.FD_CLOEXEC
r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
assert r != -1
# There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
# via fcntl.fcntl. So use lockf instead
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
except IOError:
r = os.read(fd, 32)
if r:
logging.error('already started at pid %s' % common.to_str(r))
else:
logging.error('already started')
os.close(fd)
return -1
os.ftruncate(fd, 0)
os.write(fd, common.to_bytes(str(pid)))
return 0
def write_pid_file(pid_file, pid):
try:
fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
stat.S_IRUSR | stat.S_IWUSR)
except OSError as e:
LOG.exception(e)
return -1
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
assert flags != -1
flags |= fcntl.FD_CLOEXEC
r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
assert r != -1
# There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
# via fcntl.fcntl. So use lockf instead
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
except IOError:
r = os.read(fd, 32)
if r:
logging.error('already started at pid %s' % utils.to_str(r))
else:
logging.error('already started')
os.close(fd)
return -1
os.ftruncate(fd, 0)
os.write(fd, utils.to_bytes(str(pid)))
return 0
def _trylock(lockfile):
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
def __init__(self, filename):
self.filename = filename
# This will create it if it does not exist already
self.handle = open(filename, 'w')
# Bitwise OR fcntl.LOCK_NB if you need a non-blocking lock
def _try_lock(self, fd):
"""Try to acquire the lock file without blocking.
:param int fd: file descriptor of the opened file to lock
"""
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as err:
if err.errno in (errno.EACCES, errno.EAGAIN):
logger.debug(
"A lock on %s is held by another process.", self._path)
raise errors.LockError(
"Another instance of Certbot is already running.")
raise
def run_chiboard(self):
pass
import subprocess
from chi import board
from chi.board import CHIBOARD_HOME, MAGIC_PORT
port = None
start = False
cbc = join(CHIBOARD_HOME, CONFIG_NAME)
if os.path.isfile(cbc):
with open(cbc) as f:
import fcntl
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
start = True
fcntl.flock(f, fcntl.LOCK_UN)
except (BlockingIOError, OSError): # chiboard is running
try:
data = json.load(f)
port = data.get('port')
except json.JSONDecodeError:
port = None
else:
start = True
if start:
from chi.board import main
chiboard = main.__file__
subprocess.check_call([sys.executable, chiboard, '--port', str(MAGIC_PORT), '--daemon'])
port = MAGIC_PORT
if port is None:
logger.warning('chiboard seems to be running but port could not be read from its config')
else:
logger.info(f"{self.f.__name__} started. Check progress at http://localhost:{port}/exp/#/local{self.logdir}")
def __init__(self, path):
import json
self._path = path
try:
with open(path) as f:
old_data = json.load(f)
except json.JSONDecodeError:
logger.warning('Could not decode config')
old_data = {}
except OSError:
logger.debug('No config file')
old_data = {}
for i in range(10):
try:
self._f = open(path, 'w+')
fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
self._locked = True
break
except BlockingIOError:
import signal
pid = old_data.get('pid')
if pid:
logger.info(f'Config file is locked (try {i}). Killing previous instance {pid}')
os.kill(pid, signal.SIGTERM)
time.sleep(.05)
else:
logger.error(f'Config file is locked and no pid to kill')
assert self._locked
def lock_file(fname):
"""Lock a file."""
import fcntl
f = open(fname, mode='w')
try:
fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception:
return None
return f
def __enter__(self):
"""Enter RunSingleInstance class
:return: self
"""
self.__checked = True
try:
self.__filelock = open(self.__lockfile, 'w+')
# None blocking lock
fcntl.lockf(self.__filelock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
if self.__filelock is not None:
self.__is_running = True
return self
def do_acquire_read_lock(self, wait):
filedescriptor = self._open(os.O_CREAT | os.O_RDONLY)
if not wait:
try:
fcntl.flock(filedescriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
return True
except IOError:
os.close(filedescriptor)
self._filedescriptor.remove()
return False
else:
fcntl.flock(filedescriptor, fcntl.LOCK_SH)
return True
def do_acquire_write_lock(self, wait):
filedescriptor = self._open(os.O_CREAT | os.O_WRONLY)
if not wait:
try:
fcntl.flock(filedescriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except IOError:
os.close(filedescriptor)
self._filedescriptor.remove()
return False
else:
fcntl.flock(filedescriptor, fcntl.LOCK_EX)
return True
def management_lock(view_func):
def wrapper_lock(*args, **kwargs):
try:
lock_file_path = os.path.join('/tmp/', "{0}.lock".format(args[0].__class__.__module__.split('.')[-1]))
f = open(lock_file_path, 'w')
fcntl.lockf(f, fcntl.LOCK_EX + fcntl.LOCK_NB)
except IOError:
logging.debug("Process already is running.")
os._exit(1)
return view_func(*args, **kwargs)
wrapper_lock.view_func = view_func.view_func if hasattr(view_func, 'view_func') else view_func
return wrapper_lock
def trylock(fd):
import fcntl
import errno
try:
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError, e:
if e.errno in (errno.EACCES, errno.EAGAIN):
return False
else:
raise
return True
def _lock(self):
if not fcntl or not self.ser:
return
fcntl.flock(self.ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
logging.debug('_lock')
def acquire_lock_or_exit(self, wait_for_seconds=10):
lock_file = self.STATE_DIR + '/.iptables.lock'
i = 0
f = open(lock_file, 'w+')
while i < wait_for_seconds:
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
return
except IOError:
i += 1
time.sleep(1)
Iptables.module.fail_json(msg="Could not acquire lock to continue execution! "
"Probably another instance of this module is running.")
# Check if a table has anything to flush (to check all tables pass table='*').
def unlockfile(lf):
"""
Unlock a file locked using lockfile()
"""
try:
# If we had a shared lock, we need to promote to exclusive before
# removing the lockfile. Attempt this, ignore failures.
fcntl.flock(lf.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
os.unlink(lf.name)
except (IOError, OSError):
pass
fcntl.flock(lf.fileno(), fcntl.LOCK_UN)
lf.close()
def unlockfile(lock_file):
"""
Unlock a file locked using lockfile()
"""
try:
# If we had a shared lock, we need to promote to exclusive before
# removing the lockfile. Attempt this, ignore failures.
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
os.unlink(lock_file.name)
except (IOError, OSError):
pass
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
lock_file.close()
#ENDOFCOPY