]> git.phdru.name Git - m_librarian.git/blob - m_librarian/web/utils.py
Feat: Store lock file in a shared directory
[m_librarian.git] / m_librarian / web / utils.py
1 from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
2 from tempfile import gettempdir
3 import os
4 import socket
5
6
7 if os.access('/var/run/lock', os.W_OK):
8     lock_dir = '/var/run/lock'
9 else:
10     lock_dir = gettempdir()
11
12 if hasattr(os, 'getuid'):
13     suffix = '-%d' % os.getuid()
14 else:
15     suffix = ''
16
17 lock_fname = os.path.join(lock_dir, 'm_librarian%s.lock' % suffix)
18
19
20 def get_lock(port):
21     try:
22         lock_file = open(lock_fname, 'r')
23     except IOError:  # no lock file
24         pass
25     else:
26         try:
27             flock(lock_file, LOCK_EX | LOCK_NB)
28         except IOError:  # locked
29             port = int(lock_file.readline())
30             lock_file.close()
31             return None, port
32         else:
33             flock(lock_file, LOCK_UN)
34             lock_file.close()
35
36     lock_file = open(lock_fname, 'w')
37     lock_file.write(str(port))
38     lock_file.close()
39     lock_file = open(lock_fname, 'r')
40     flock(lock_file, LOCK_EX | LOCK_NB)
41     return lock_file, None
42
43
44 def close_lock(lock_file):
45     flock(lock_file, LOCK_UN)
46     lock_file.close()
47     lock_file = open(lock_fname, 'w')
48     lock_file.write('')
49     lock_file.close()
50     os.remove(lock_fname)
51
52
53 def get_open_port():
54     # https://stackoverflow.com/a/2838309/7976758
55     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
56     s.bind(("", 0))
57     # s.listen(1)
58     port = s.getsockname()[1]
59     s.close()
60     return port