Merge branch 'master' of ssh://git.onelab.eu/git/sfa
[sfa.git] / sfa / rspecs / elements / versions / iotlabv1Node.py
1 """
2 This file describes what the propreties of an iotlab nodes are, if an iotlab
3 rspec is asked. If additionnal node properties have to be defined and exposed
4 to the user, it should be done here.
5 """
6 from sfa.util.xrn import Xrn
7 from sfa.util.xml import XpathFilter
8 from sfa.rspecs.elements.node import Node
9 from sfa.rspecs.elements.sliver import Sliver
10 from sfa.rspecs.elements.location import Location
11 from sfa.rspecs.elements.hardware_type import HardwareType
12 from sfa.rspecs.elements.element import Element
13 from sfa.rspecs.elements.interface import Interface
14 from sfa.rspecs.elements.versions.iotlabv1Sliver import Iotlabv1Sliver
15 from sfa.util.sfalogging import logger
16
17
18 class IotlabNode(Node):
19     """ Defines what kind of information is displayed on the first line of
20     the Rspec describing a node.
21     """
22     #First get the fields already defined in the class Node
23     fields = list(Node.fields)
24     #Extend it with iotlab's specific fields
25     fields.extend(['archi', 'radio', 'mobile', 'position'])
26
27
28 class IotlabPosition(Element):
29     """ Defines the fields needed to diplay node's coordinates in the RSpec. """
30     fields = ['posx', 'posy', 'posz']
31
32
33 class IotlabLocation(Location):
34     """ Needed to display the localisation (Country and city) of a node."""
35     fields = list(Location.fields)
36     fields.extend(['site'])
37
38
39 class IotlabMobility(Element):
40     """ Class to give information of a node's mobility, and what kind of
41     mobility it is (train, roomba robot ...) """
42     fields = ['mobile', 'mobility_type']
43
44
45
46 class Iotlabv1Node:
47
48     @staticmethod
49     def add_connection_information(xml, ldap_username, sites_set):
50         """ Adds login and ssh connection info in the network item in
51         the xml. Does not create the network element, therefore
52         should be used after add_nodes, which creates the network item.
53
54         """
55         logger.debug(" add_connection_information ")
56         #Get network item in the xml
57         network_elems = xml.xpath('//network')
58         if len(network_elems) > 0:
59             network_elem = network_elems[0]
60
61             iotlab_network_dict = {}
62             iotlab_network_dict['login'] = ldap_username
63
64             iotlab_network_dict['ssh'] = \
65                 ['ssh ' + ldap_username + '@'+site+'.iotlab.info'
66                  for site in sites_set]
67             network_elem.set('ssh',
68                              unicode(iotlab_network_dict['ssh']))
69             network_elem.set('login', unicode(iotlab_network_dict['login']))
70
71     @staticmethod
72     def add_nodes(xml, nodes, rspec_content_type=None):
73         """Adds the nodes to the xml.
74
75         Adds the nodes as well as dedicated iotlab fields to the node xml
76         element.
77
78         :param xml: the xml being constructed.
79         :type xml: xml
80         :param nodes: list of node dict
81         :type nodes: list
82         :returns: a list of node elements.
83         :rtype: list
84
85         """
86         #Add network item in the xml
87         network_elems = xml.xpath('//network')
88         if len(network_elems) > 0:
89             network_elem = network_elems[0]
90         elif len(nodes) > 0 and nodes[0].get('component_manager_id'):
91             network_urn = nodes[0]['component_manager_id']
92             network_elem = xml.add_element('network',
93                                            name=Xrn(network_urn).get_hrn())
94         else:
95             network_elem = xml
96
97         node_elems = []
98         #Then add nodes items to the network item in the xml
99         for node in nodes:
100             #Attach this node to the network element
101             node_fields = ['component_manager_id', 'component_id', 'exclusive',
102                            'boot_state', 'mobile']
103             node_elem = network_elem.add_instance('node', node, node_fields)
104             node_elems.append(node_elem)
105
106             #Set the attibutes of this node element
107             for attribute in node:
108             # set component name
109                 if attribute is 'component_name':
110                     component_name = node['component_name']
111                     node_elem.set('component_name', component_name)
112
113             # set hardware types, extend fields to add Iotlab's architecture
114             #and radio type
115
116                 if attribute is 'hardware_types':
117                     for hardware_type in node.get('hardware_types', []):
118                         fields = HardwareType.fields
119                         fields.extend(['archi', 'radio'])
120                         node_elem.add_instance('hardware_types', node, fields)
121
122             # set mobility
123                 if attribute is 'mobility':
124                     node_elem.add_instance('mobility', node['mobility'],
125                                            IotlabMobility.fields)
126             # set location
127                 if attribute is 'location':
128                     node_elem.add_instance('location', node['location'],
129                                             IotlabLocation.fields)
130
131              # add granularity of the reservation system
132              #TODO put the granularity in network instead SA 18/07/12
133                 if attribute is 'granularity':
134                     granularity = node['granularity']
135                     if granularity:
136                         node_elem.add_instance('granularity',
137                                                granularity, granularity.fields)
138
139             # set available element
140                 if attribute is 'boot_state':
141                     if node.get('boot_state').lower() == 'alive':
142                         available_elem = node_elem.add_element('available',
143                                                                now='true')
144                     else:
145                         available_elem = node_elem.add_element('available',
146                                                                now='false')
147
148             #set position
149                 if attribute is 'position':
150                     node_elem.add_instance('position', node['position'],
151                                            IotlabPosition.fields)
152             ## add services
153             #PGv2Services.add_services(node_elem, node.get('services', []))
154             # add slivers
155                 if attribute is 'slivers':
156                     slivers = node.get('slivers', [])
157                     if not slivers:
158                     # we must still advertise the available sliver types
159                         slivers = Sliver({'type': 'iotlab-node'})
160                     # we must also advertise the available initscripts
161                     #slivers['tags'] = []
162                     #if node.get('pl_initscripts'):
163                         #for initscript in node.get('pl_initscripts', []):
164                             #slivers['tags'].append({'name': 'initscript', \
165                                                     #'value': initscript['name']})
166
167                     Iotlabv1Sliver.add_slivers(node_elem, slivers)
168             
169             # add sliver tag in Request Rspec
170             if rspec_content_type == "request":
171                 node_elem.add_instance('sliver', '', [])
172
173         return node_elems
174
175     @staticmethod
176     def get_nodes(xml, filter={}):
177         """
178         Parsing method called upon receiving a Rspec request in the iotlab
179         format. (Format is given in the XML header, where 'request' is
180         specified).
181
182         :returns: call to get_node_objs .a list of nodes with their properties
183         :rtype: list of dict
184
185         .. note:: doesn't seem to be used outside sfiListNodes if the iotlab
186             format is specified.
187
188         .. seealso:: get_node_objs
189         """
190         xpath = '//node%s | //default:node%s' % (XpathFilter.xpath(filter),
191                                                  XpathFilter.xpath(filter))
192         node_elems = xml.xpath(xpath)
193         return Iotlabv1Node.get_node_objs(node_elems)
194
195     @staticmethod
196     def get_nodes_with_slivers(xml, sliver_filter={}):
197         """
198         With the nodes found in the Rspec, find the nodes which the user wants
199         to use, based on the definition of a sliver on a node. Search for those
200         nodes.
201
202         :param sliver_filter: unused
203         :returns: call to get_node_objs. A list of nodes where a sliver is
204             defined with their properties;
205         :rtype: list of dict
206
207         .. note:: used by CreateSliver.
208         .. seealso:: get_node_objs
209         """
210
211         xpath = '//node[count(sliver)>0] | \
212                                 //default:node[count(default:sliver) > 0]'
213         node_elems = xml.xpath(xpath)
214         logger.debug("SLABV1NODE \tget_nodes_with_slivers  \
215                                 node_elems %s" % (node_elems))
216         return Iotlabv1Node.get_node_objs(node_elems)
217
218     @staticmethod
219     def get_node_objs(node_elems):
220         """
221         Get information on the nodes on the xml. Gets the attributes in the
222         Rspec.
223
224         :param node_elems: xml node elements
225         :type node_elems: xml xpath return type
226
227         :returns: a list of nodes where a sliver is defined with their
228             properties
229         :rtype: list of dict
230
231         .. seealso:: get_nodes_with_slivers, get_nodes
232
233         """
234         nodes = []
235         for node_elem in node_elems:
236             node = Node(node_elem.attrib, node_elem)
237             nodes.append(node)
238             if 'component_id' in node_elem.attrib:
239                 node['authority_id'] = \
240                     Xrn(node_elem.attrib['component_id']).get_authority_urn()
241
242             # get hardware types
243             hardware_type_elems = node_elem.xpath('./default:hardware_type | \
244                                                             ./hardware_type')
245             node['hardware_types'] = [hw_type.get_instance(HardwareType)
246                                       for hw_type in hardware_type_elems]
247
248             # get location
249             location_elems = node_elem.xpath('./default:location | ./location')
250             locations = [location_elem.get_instance(Location)
251                          for location_elem in location_elems]
252             if len(locations) > 0:
253                 node['location'] = locations[0]
254
255
256             # get interfaces
257             iface_elems = node_elem.xpath('./default:interface | ./interface')
258             node['interfaces'] = [iface_elem.get_instance(Interface)
259                                   for iface_elem in iface_elems]
260
261             # get position
262             position_elems = node_elem.xpath('./default:position | ./position')
263             if position_elems:
264                 position_elem = position_elems[0]
265                 node['position'] = position_elem.get_instance(IotlabPosition)
266
267             # get services
268             #node['services'] = PGv2Services.get_services(node_elem)
269
270             # get slivers
271             node['slivers'] = Iotlabv1Sliver.get_slivers(node_elem)
272             available_elems = node_elem.xpath('./default:available | \
273                                                                 ./available')
274             if len(available_elems) > 0 and 'name' in available_elems[0].attrib:
275                 if available_elems[0].attrib.get('now', '').lower() == 'true':
276                     node['boot_state'] = 'boot'
277                 else:
278                     node['boot_state'] = 'disabled'
279
280         logger.debug("SLABV1NODE \tget_nodes_objs  \
281                                 #nodes %s" % (nodes))
282         return nodes
283
284     @staticmethod
285     def add_slivers(xml, slivers):
286         """Add the slivers in parameter to the nodes, by modifying the
287         xml and adding the sliver element in the RSpec.
288
289         :param slivers: list of slivers, which can be either strings or  dict.
290         :type: list
291
292         :returns: None
293         :rtype: None
294
295         .. seealso:: Iotlabv1Sliver : add_slivers
296         .. note:: used by sfiAddSliver and add_nodes (in the file)
297
298         """
299         logger.debug("Iotlabv1NODE \tadd_slivers ")
300         component_ids = []
301         for sliver in slivers:
302             filter_sliver = {}
303             if isinstance(sliver, str):
304                 filter_sliver['component_id'] = '*%s*' % sliver
305                 sliver = {}
306             elif 'component_id' in sliver and sliver['component_id']:
307                 filter_sliver['component_id'] = '*%s*' % sliver['component_id']
308             if not filter_sliver:
309                 continue
310             nodes = Iotlabv1Node.get_nodes(xml, filter_sliver)
311             if not nodes:
312                 continue
313             node = nodes[0]
314             Iotlabv1Sliver.add_slivers(node, sliver)
315
316     @staticmethod
317     def remove_slivers(xml, hostnames):
318         """
319         Removes the slivers for the nodes whose hostnames are on the list.
320
321         :param hostnames: list of nodes' hostnames whose sliver have to be
322             removed.
323         :type hostnames: list
324         """
325         for hostname in hostnames:
326             nodes = Iotlabv1Node.get_nodes(xml, {'component_id': '*%s*'
327                                            % hostname})
328             for node in nodes:
329                 slivers = Iotlabv1Sliver.get_slivers(node.element)
330                 for sliver in slivers:
331                     node.element.remove(sliver.element)