1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 """Lockfiles to prove liveliness
31
32 When requesting resources, like locks, from wconfd, requesters have
33 to provide the name of a file they own an exclusive lock on, to prove
34 that they are still alive. Provide methods to obtain such a file.
35 """
36
37 import fcntl
38 import os
39 import struct
40 import time
41
42 from ganeti.utils.algo import NiceSort
43 from ganeti import pathutils
44
45
49
52
54 """Clean up the lockfile.
55
56 """
57 os.remove(self._name)
58
60 return "LiveLockName(" + self.GetPath() + ")"
61
62
64 """Utility for a lockfile needed to request resources from WconfD.
65
66 """
68 if name is None:
69 name = "pid%d_" % os.getpid()
70
71
72 name = "%s_%d" % (name, int(time.time()))
73 fname = os.path.join(pathutils.LIVELOCK_DIR, name)
74 self.lockfile = open(fname, 'w')
75 fcntl.fcntl(self.lockfile, fcntl.F_SETLKW,
76 struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0))
77
79 return self.lockfile.name
80
82 """Close the lockfile and clean it up.
83
84 """
85 self.lockfile.close()
86 os.remove(self.lockfile.name)
87
89 return "LiveLock(" + self.GetPath() + ")"
90
91
93 """For a given name, take the latest file matching.
94
95 @return: the file with the latest name matching the given
96 prefix in LIVELOCK_DIR, or the plain name, if none
97 exists.
98 """
99 lockfiles = filter(lambda n: n.startswith(name),
100 os.listdir(pathutils.LIVELOCK_DIR))
101 if len(lockfiles) > 0:
102 lockfile = NiceSort(lockfiles)[-1]
103 else:
104 lockfile = name
105
106 return os.path.join(pathutils.LIVELOCK_DIR, lockfile)
107