X-Git-Url: https://git.phdru.name/?a=blobdiff_plain;f=m_librarian%2Fweb%2Futils.py;h=8804f3b327df81831fbd707af57def93e965a8e9;hb=054ce4ecc6c93d0289864c80677c7dd8bf8b1962;hp=2efe724a6bdf8fcfb10a9e7e1c4ce9d0ca877de8;hpb=2d76928b93c208d27f942b9a9eb649df1d5b2192;p=m_librarian.git diff --git a/m_librarian/web/utils.py b/m_librarian/web/utils.py index 2efe724..8804f3b 100644 --- a/m_librarian/web/utils.py +++ b/m_librarian/web/utils.py @@ -1,7 +1,57 @@ +from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB +from tempfile import gettempdir +import os +import socket + + +if os.access('/var/run/lock', os.W_OK): + lock_dir = '/var/run/lock' +else: + lock_dir = gettempdir() + +if hasattr(os, 'getuid'): + suffix = '-%d' % os.getuid() +else: + suffix = '' + +lock_fname = os.path.join(lock_dir, 'm_librarian%s.lock' % suffix) + + +def get_lock(port): + try: + lock_file = open(lock_fname, 'r') + except IOError: # no lock file + pass + else: + try: + flock(lock_file, LOCK_EX | LOCK_NB) + except IOError: # locked + port = int(lock_file.readline()) + lock_file.close() + return None, port + else: + flock(lock_file, LOCK_UN) + lock_file.close() + + lock_file = open(lock_fname, 'w') + lock_file.write(str(port)) + lock_file.close() + lock_file = open(lock_fname, 'r') + flock(lock_file, LOCK_EX | LOCK_NB) + return lock_file, None + + +def close_lock(lock_file): + flock(lock_file, LOCK_UN) + lock_file.close() + lock_file = open(lock_fname, 'w') + lock_file.write('') + lock_file.close() + os.remove(lock_fname) + def get_open_port(): # https://stackoverflow.com/a/2838309/7976758 - import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) # s.listen(1)