Add count files to tct/resource_locking.py 62/79762/6
authorAleksander Mistewicz <a.mistewicz@samsung.com>
Tue, 12 Jul 2016 15:59:56 +0000 (17:59 +0200)
committerAleksander Mistewicz <a.mistewicz@samsung.com>
Fri, 7 Oct 2016 15:11:22 +0000 (17:11 +0200)
Change-Id: Ie06d890490a66616d909f7953c04e3c86df62a95
Signed-off-by: Aleksander Mistewicz <a.mistewicz@samsung.com>
tct/resource_locking.py

index 3bda871..6eea39b 100755 (executable)
@@ -34,6 +34,7 @@ USAGE = "%prog <opts>"
 UUID_DIR = "/var/tmp/"
 UUID_PREFIX="uuid-"
 LOCK_SUFFIX=".lock"
+CNT_SUFFIX=".cnt"
 
 class Lockfile(object):
     @classmethod
@@ -60,7 +61,9 @@ class UUIDlist(object):
     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
 
@@ -80,6 +83,33 @@ class UUIDlist(object):
                 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
@@ -88,13 +118,15 @@ class UUIDmanager:
         # 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):