UUID_DIR = "/var/tmp/"
UUID_PREFIX="uuid-"
LOCK_SUFFIX=".lock"
+CNT_SUFFIX=".cnt"
class Lockfile(object):
@classmethod
def uuid(self):
ret = set()
for f in self.all():
- if f.startswith(UUID_PREFIX) and not f.endswith(LOCK_SUFFIX):
+ if f.startswith(UUID_PREFIX) \
+ and not f.endswith(LOCK_SUFFIX) \
+ and not f.endswith(CNT_SUFFIX):
ret.add(f)
return ret
ret.add(f)
return ret
+ @classmethod
+ def get_cnt(self, uuid):
+ fname = UUID_DIR + uuid + CNT_SUFFIX
+ logging.debug("Get counter from: %s", fname)
+ if os.path.isfile(fname):
+ with open(fname, 'r') as f:
+ return int(f.read())
+ return 0
+
+ @classmethod
+ def set_cnt(self, uuid, value):
+ fname = UUID_DIR + uuid + CNT_SUFFIX
+ logging.debug("Set counter (%d) for: %s", value, fname)
+ with open(fname, 'w') as f:
+ f.write(str(value))
+
+ @classmethod
+ def sort_cnt(self, targets):
+ cnt = dict()
+ ret = list(targets)
+ for u in ret:
+ cnt[u]=self.get_cnt(u)
+ logging.debug("UUID files with counters: %s", cnt)
+ ret.sort(key=cnt.__getitem__)
+ logging.debug("Sorted list of UUIDs: %s", ret)
+ return ret
+
class UUIDmanager:
def __init__(self, target):
self.target = target
# go through the list of not locked uuid files and stop on the first successfully locked
# returns False if none of the uuid files was locked
# otherwise it returns True and prints filename on stdout
- for uuid in UUIDlist.not_locked(UUIDlist.target(self.target)):
+ for uuid in UUIDlist.sort_cnt(UUIDlist.not_locked(UUIDlist.target(self.target))):
if Lockfile.lock(UUID_DIR + uuid) == 0:
logging.info("Locked: %s", uuid)
with open(UUID_DIR + uuid + LOCK_SUFFIX, 'w') as f:
f.write(str(os.getppid()))
+ UUIDlist.set_cnt(uuid, UUIDlist.get_cnt(uuid)+1)
print uuid[len(UUID_PREFIX):]
return True
+ logging.info("Failed to lock")
return False
def unlock(self):