NECo: A tool to design and run experiments on arbitrary platforms.
[nepi.git] / src / neco / execution / resource.py
1 import logging
2 import weakref
3
4 def match_tags(box, all_tags, exact_tags):
5     """ returns True if box has required tags """
6     tall = set(all_tags)
7     texact = set(exact_tags)
8
9     if texact and box.connections == texact:
10         return True
11
12     if tall and tall.issubset(box.connections):
13         return True
14
15     return False
16
17 def find_boxes(box, all_tags = None, exact_tags = None, max_depth = 1):
18     """ Look for the connected boxes with the required tags, doing breath-first
19     search, until max_depth ( max_depth = None will traverse the entire graph ).
20     """
21     if not all_tags and not exact_tags:
22         msg = "No matching criteria for resources."
23         raise RuntimeError(msg)
24
25     queue = set()
26     # enqueue (depth, box) 
27     queue.add((0, box))
28     
29     traversed = set()
30     traversed.add(box)
31
32     depth = 0
33
34     result = set()
35
36     while len(q) > 0: 
37         (depth, a) = queue.pop()
38         if match_tags(a, all_tags, exact_tags):
39             result.add(a)
40
41         if not max_depth or depth <= max_depth:
42             depth += 1
43             for b in sorted(a.connections):
44                 if b not in traversed:
45                     traversed.add(b)
46                     queue.add((depth, b))
47     
48     return result
49
50 class Resource(object):
51     def __init__(self, box, ec):
52         self._box = weakref.ref(box)
53         self._ec = weakref.ref(ec)
54
55         # Logging
56         loglevel = "debug"
57         self._logger = logging.getLogger("neco.execution.Resource.%s" % 
58             self.box.guid)
59         self._logger.setLevel(getattr(logging, loglevel.upper()))
60
61     @property
62     def box(self):
63         return self._box()
64
65     @property
66     def ec(self):
67         return self._ec()
68
69     def find_resources(self, all_tags = None, exact_tags = None, 
70         max_depth = 1):
71         resources = set()
72
73         boxes = find_boxes(self.box, all_tags, exact_tags, max_depth)
74         for b in boxes:
75             r = self.ec.resource(b.guid)
76             resources.add(r)
77
78         return resources
79
80 class ResourceResolver(object):
81     def __init__(self):
82         pass  
83
84