06ed8f7e1ae8c9dfe09268ed8292643b7d3e0c04
[tests.git] / system / TestMapper.py
1 #
2 # Thierry Parmentelat - INRIA Sophia Antipolis 
3 #
4 # mapper class
5
6 # this works on a spec as defined in a config file
7 # and allows to remap various fields, typically to another testbox 
8 # see an example in config_onelab_testbox32.py
9
10
11 import re
12 import utils
13
14 class TestMapper:
15
16     def __init__ (self,plcs,mapper,options):
17         self.plcs=plcs
18         self.mapper=mapper
19         self.options=options
20
21     @staticmethod
22     def match (name,key):
23         key=key.replace("*",".*")
24         return re.compile(key).match(name)
25
26     @staticmethod
27     def plc_name (plc):
28         return plc['name']
29
30     @staticmethod
31     def node_name (node):
32         return node['node_fields']['hostname']
33
34     def apply_first_map (self, type, name, obj, maplist):
35         for (map_pattern,rename_dict) in maplist:
36             if TestMapper.match (name,map_pattern):
37                 utils.header("TestMapper/%s : applying match key %s on plc %s"%(type,map_pattern,name))
38                 for (k,v) in rename_dict.iteritems():
39                     # apply : separator
40                     path=k.split(':')
41                     # step down but last step in path
42                     o=obj
43                     for step in path[:-1]:
44                         if not o.has_key(step):
45                             utils.header ("WARNING : cannot apply step %s in path %s on %s %s"%(
46                                     step,path,type,name))
47                             return
48                         o=obj[step]
49                     # last step is the one for side-effect
50                     step=path[-1]
51                     if not o.has_key(step):
52                         utils.header ("WARNING : cannot apply step %s in path %s on %s %s"%(
53                                 step,path,type,name))
54                         return
55                     # apply formatting if found
56                     if v.find('%s')>=0:
57                         v=v%obj[k]
58                     if self.options.verbose:
59                         utils.header("mapping %s->%s towards %s"%(name,k,v))
60                     o[step]=v
61                 # only apply first rule
62                 return
63
64     def map (self):
65
66         plc_maps = self.mapper['plc']
67
68         for plc in self.plcs:
69             name=TestMapper.plc_name(plc)
70             self.apply_first_map ('plc',name,plc,plc_maps)
71
72             node_maps = self.mapper['node']
73
74             for site in plc['sites']:
75                 for node in site['nodes']:
76                     nodename = TestMapper.node_name(node)
77                     self.apply_first_map('node',nodename,node,node_maps)
78
79         return self.plcs
80                                                
81