first set of semantic changes for python3
[nepi.git] / src / nepi / util / sfarspec_proc.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License version 2 as
7 #    published by the Free Software Foundation;
8 #
9 #    This program is distributed in the hope that it will be useful,
10 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #    GNU General Public License for more details.
13 #
14 #    You should have received a copy of the GNU General Public License
15 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17
18 from nepi.util.logger import Logger
19 try:
20     from sfa.rspecs.rspec import RSpec
21     from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
22 except ImportError:
23     log = Logger("SFA RSpec Processing")
24     log.debug("Package sfa-common not installed.\
25          Could not import sfa.rspecs.rspec and sfa.util.xrn")
26
27 class SfaRSpecProcessing(object):
28     """
29     Class to process SFA RSpecs, parse the RSpec replies such as Advertisement RSpecs,
30     and build in the case of Request RSpecs.
31     """
32     def __init__(self, config=None):
33         self._log = Logger("SFA RSpec Processing")
34         self.config = config 
35
36     def make_dict_rec(self, obj):
37         if not obj or isinstance(obj, (str, bool)):
38             return obj
39         if isinstance(obj, list):
40             objcopy = []
41             for x in obj:
42                 objcopy.append(self.make_dict_rec(x))
43             return objcopy
44         # We thus suppose we have a child of dict
45         objcopy = {}
46         for k, v in list(obj.items()):
47             objcopy[k] = self.make_dict_rec(v)
48         return objcopy
49
50     def parse_sfa_rspec(self, rspec_string):
51         """
52         Parse the RSpec XML as a string.
53         """
54         # rspec_type and rspec_version should be set in the config of the platform,
55         # we use GENIv3 as default one if not
56         if self.config:
57             if 'rspec_type' and 'rspec_version' in self.config:
58                 rspec_version = self.config['rspec_type'] + ' ' + self.config['rspec_version']
59         else:
60             rspec_version = 'GENI 3'
61         self._log.debug(rspec_version)
62         rspec = RSpec(rspec_string, version=rspec_version)
63         
64         try:
65             nodes = rspec.version.get_nodes()
66         except Exception as e:
67             self._log.warn("Could not retrieve nodes in RSpec: %s" % e)
68         try:
69             leases = rspec.version.get_leases()
70         except Exception as e:
71             self._log.warn("Could not retrieve leases in RSpec: %s" % e)
72         try:
73             links = rspec.version.get_links()
74         except Exception as e:
75             self._log.warn("Could not retrieve links in RSpec: %s" % e)
76         try:
77             channels = rspec.version.get_channels()
78         except Exception as e:
79             self._log.warn("Could not retrieve channels in RSpec: %s" % e)
80   
81         resources = [] 
82         # Extend object and Format object field's name
83         for node in nodes:
84             node['type'] = 'node'
85             node['network_hrn'] = Xrn(node['component_id']).authority[0] # network ? XXX
86             node['hrn'] = urn_to_hrn(node['component_id'])[0]
87             node['urn'] = node['component_id']
88             node['hostname'] = node['component_name']
89             node['initscripts'] = node.pop('pl_initscripts')
90             if 'exclusive' in node and node['exclusive']:
91                 node['exclusive'] = node['exclusive'].lower() == 'true'
92  
93             # XXX This should use a MAP as before
94             if 'position' in node: # iotlab
95                 node['x'] = node['position']['posx']
96                 node['y'] = node['position']['posy']
97                 node['z'] = node['position']['posz']
98                 del node['position']
99  
100             if 'location' in node:
101                 if node['location']:
102                     node['latitude'] = node['location']['latitude']
103                     node['longitude'] = node['location']['longitude']
104                 del node['location']
105  
106             # Flatten tags
107             if 'tags' in node:
108                 if node['tags']:
109                     for tag in node['tags']:
110                         node[tag['tagname']] = tag['value']
111                 del node['tags']
112  
113             
114             # We suppose we have children of dict that cannot be serialized
115             # with xmlrpc, let's make dict
116             resources.append(self.make_dict_rec(node))
117  
118         # NOTE a channel is a resource and should not be treated independently
119         #     resource
120         #        |
121         #   +----+------+-------+
122         #   |    |      |       |
123         # node  link  channel  etc.
124         #resources.extend(nodes)
125         #resources.extend(channels)
126  
127         return {'resource': resources, 'lease': leases } 
128 #               'channel': channels \
129 #               }
130
131  
132     def build_sfa_rspec(self, slice_id, resources, properties, leases):
133         """
134         Build the XML RSpec from list of resources' urns.
135         eg. resources = ["urn:publicid:IDN+ple:modenaple+node+planetlab-1.ing.unimo.it"]
136         """
137         #if isinstance(resources, str):
138         #    resources = eval(resources)
139         # rspec_type and rspec_version should be set in the config of the platform,
140         # we use GENIv3 as default one if not
141         if self.config:
142             if 'rspec_type' and 'rspec_version' in self.config:
143                 rspec_version = self.config['rspec_type'] + ' ' + self.config['rspec_version']
144         else:
145             rspec_version = 'GENI 3'
146
147         # extend rspec version with "content_type"
148         rspec_version += ' request'
149         
150         rspec = RSpec(version=rspec_version)
151
152         nodes = []
153         channels = []
154         links = []
155         self._log.debug("Building RSpec for resources %s" % resources)
156         cardinal = 0
157         wilab = False
158         for urn in resources:
159             # XXX TO BE CORRECTED, this handles None values
160             if not urn:
161                 continue
162             self._log.debug(urn)
163             resource = dict()
164             # TODO: take into account the case where we send a dict of URNs without keys
165             #resource['component_id'] = resource.pop('urn')
166             resource['component_id'] = urn
167             resource_hrn, resource_type = urn_to_hrn(resource['component_id'])
168             # build component_manager_id
169             top_auth = resource_hrn.split('.')[0]
170             cm = urn.split("+")
171             resource['component_manager_id'] = "%s+%s+authority+cm" % (cm[0],top_auth)
172
173             if resource_type == 'node':
174                 # XXX dirty hack WiLab !!!
175 #                Commented Lucia, doesn't work for wilabt  
176 #                if self.config:
177 #                    if 'wilab2' in self.config['sm']:
178 #                        resource['client_id'] = "PC"
179 #                        resource['sliver_type'] = "raw-pc"
180                 if 'wilab2' in urn:
181                     wilab = True
182                     resource['client_id'] = "node%s" % cardinal
183                     resource['sliver_type'] = "raw-pc"
184                     resource['disk_image'] = "hola"
185                     top_auth = resource_hrn.replace("\\", "").split('.')
186                     top_auth.pop()
187                     top_auth = '.'.join(top_auth)
188                     cm = urn.split("+")
189                     resource['component_manager_id'] = "%s+%s+authority+cm" % (cm[0],top_auth)
190                     cardinal += 1
191                 nodes.append(resource)
192             elif resource_type == 'link':
193                 links.append(resource)
194             elif resource_type == 'channel':
195                 channels.append(resource)
196             else:
197                 raise Exception("Not supported type of resource") 
198         
199         rspec.version.add_nodes(nodes, rspec_content_type="request")
200         #rspec.version.add_leases(leases)
201         #rspec.version.add_links(links)
202         #rspec.version.add_channels(channels)
203
204         #self._log.debug("request rspec: %s"%rspec.toxml())
205         string = rspec.toxml()
206         if wilab and properties is not None:
207             ## dirty hack for the f4f demo
208             b = string.split('\n')
209             for i, n in enumerate(b):
210                 if 'sliver_type name="raw-pc"' in n:
211                     b[i] = '<sliver_type name="raw-pc">'
212                     b.insert(i+1, '<disk_image name="urn:publicid:IDN+wall2.ilabt.iminds.be+image+emulab-ops//%s"/>' % properties['disk_image'])
213                     #b.insert(i+1, '<disk_image name="urn:publicid:IDN+wilab2.ilabt.iminds.be+image+nepi:%s"/>' % properties['disk_image'])
214                     b.insert(i+2, '</sliver_type>')
215             string = ''.join(b)
216         self._log.debug("request rspec : %s" % string)
217         return string
218
219