6a95d2389e7c90c176f9429c38efd474ec687809
[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):
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         logger.debug("iotlabv1Node \t add_nodes  nodes %s \r\n " % (nodes[0]))
98         node_elems = []
99         #Then add nodes items to the network item in the xml
100         for node in nodes:
101             #Attach this node to the network element
102             node_fields = ['component_manager_id', 'component_id', 'exclusive',
103                            'boot_state', 'mobile']
104             node_elem = network_elem.add_instance('node', node, node_fields)
105             node_elems.append(node_elem)
106
107             #Set the attibutes of this node element
108             for attribute in node:
109             # set component name
110                 if attribute is 'component_name':
111                     component_name = node['component_name']
112                     node_elem.set('component_name', component_name)
113
114             # set hardware types, extend fields to add Iotlab's architecture
115             #and radio type
116
117                 if attribute is 'hardware_types':
118                     for hardware_type in node.get('hardware_types', []):
119                         fields = HardwareType.fields
120                         fields.extend(['archi', 'radio'])
121                         node_elem.add_instance('hardware_types', node, fields)
122
123             # set mobility
124                 if attribute is 'mobility':
125                     node_elem.add_instance('mobility', node['mobility'],
126                                            IotlabMobility.fields)
127             # set location
128                 if attribute is 'location':
129                     node_elem.add_instance('location', node['location'],
130                                             IotlabLocation.fields)
131
132              # add granularity of the reservation system
133              #TODO put the granularity in network instead SA 18/07/12
134                 if attribute is 'granularity':
135                     granularity = node['granularity']
136                     if granularity:
137                         node_elem.add_instance('granularity',
138                                                granularity, granularity.fields)
139
140             # set available element
141                 if attribute is 'boot_state':
142                     if node.get('boot_state').lower() == 'alive':
143                         available_elem = node_elem.add_element('available',
144                                                                now='true')
145                     else:
146                         available_elem = node_elem.add_element('available',
147                                                                now='false')
148
149             #set position
150                 logger.debug("Iotlabv1Node position node_elem %s" % (node_elem))
151                 if attribute is 'position':
152                     node_elem.add_instance('position', node['position'],
153                                            IotlabPosition.fields)
154                 logger.debug("Iotlabv1Node position node[position] %s "
155                             % (node['position']))
156             ## add services
157             #PGv2Services.add_services(node_elem, node.get('services', []))
158             # add slivers
159                 if attribute is 'slivers':
160                     slivers = node.get('slivers', [])
161                     if not slivers:
162                     # we must still advertise the available sliver types
163                         slivers = Sliver({'type': 'iotlab-node'})
164                     # we must also advertise the available initscripts
165                     #slivers['tags'] = []
166                     #if node.get('pl_initscripts'):
167                         #for initscript in node.get('pl_initscripts', []):
168                             #slivers['tags'].append({'name': 'initscript', \
169                                                     #'value': initscript['name']})
170
171                     Iotlabv1Sliver.add_slivers(node_elem, slivers)
172         return node_elems
173
174     @staticmethod
175     def get_nodes(xml, filter={}):
176         """
177         Parsing method called upon receiving a Rspec request in the iotlab
178         format. (Format is given in the XML header, where 'request' is
179         specified).
180
181         :returns: call to get_node_objs .a list of nodes with their properties
182         :rtype: list of dict
183
184         .. note:: doesn't seem to be used outside sfiListNodes if the iotlab
185             format is specified.
186
187         .. seealso:: get_node_objs
188         """
189         xpath = '//node%s | //default:node%s' % (XpathFilter.xpath(filter),
190                                                  XpathFilter.xpath(filter))
191         node_elems = xml.xpath(xpath)
192         return Iotlabv1Node.get_node_objs(node_elems)
193
194     @staticmethod
195     def get_nodes_with_slivers(xml, sliver_filter={}):
196         """
197         With the nodes found in the Rspec, find the nodes which the user wants
198         to use, based on the definition of a sliver on a node. Search for those
199         nodes.
200
201         :param sliver_filter: unused
202         :returns: call to get_node_objs. A list of nodes where a sliver is
203             defined with their properties;
204         :rtype: list of dict
205
206         .. note:: used by CreateSliver.
207         .. seealso:: get_node_objs
208         """
209
210         xpath = '//node[count(sliver)>0] | \
211                                 //default:node[count(default:sliver) > 0]'
212         node_elems = xml.xpath(xpath)
213         logger.debug("SLABV1NODE \tget_nodes_with_slivers  \
214                                 node_elems %s" % (node_elems))
215         return Iotlabv1Node.get_node_objs(node_elems)
216
217     @staticmethod
218     def get_node_objs(node_elems):
219         """
220         Get information on the nodes on the xml. Gets the attributes in the
221         Rspec.
222
223         :param node_elems: xml node elements
224         :type node_elems: xml xpath return type
225
226         :returns: a list of nodes where a sliver is defined with their
227             properties
228         :rtype: list of dict
229
230         .. seealso:: get_nodes_with_slivers, get_nodes
231
232         """
233         nodes = []
234         for node_elem in node_elems:
235             node = Node(node_elem.attrib, node_elem)
236             nodes.append(node)
237             if 'component_id' in node_elem.attrib:
238                 node['authority_id'] = \
239                     Xrn(node_elem.attrib['component_id']).get_authority_urn()
240
241             # get hardware types
242             hardware_type_elems = node_elem.xpath('./default:hardware_type | \
243                                                             ./hardware_type')
244             node['hardware_types'] = [hw_type.get_instance(HardwareType)
245                                       for hw_type in hardware_type_elems]
246
247             # get location
248             location_elems = node_elem.xpath('./default:location | ./location')
249             locations = [location_elem.get_instance(Location)
250                          for location_elem in location_elems]
251             if len(locations) > 0:
252                 node['location'] = locations[0]
253
254
255             # get interfaces
256             iface_elems = node_elem.xpath('./default:interface | ./interface')
257             node['interfaces'] = [iface_elem.get_instance(Interface)
258                                   for iface_elem in iface_elems]
259
260             # get position
261             position_elems = node_elem.xpath('./default:position | ./position')
262             if position_elems:
263                 position_elem = position_elems[0]
264                 node['position'] = position_elem.get_instance(IotlabPosition)
265
266             # get services
267             #node['services'] = PGv2Services.get_services(node_elem)
268
269             # get slivers
270             node['slivers'] = Iotlabv1Sliver.get_slivers(node_elem)
271             available_elems = node_elem.xpath('./default:available | \
272                                                                 ./available')
273             if len(available_elems) > 0 and 'name' in available_elems[0].attrib:
274                 if available_elems[0].attrib.get('now', '').lower() == 'true':
275                     node['boot_state'] = 'boot'
276                 else:
277                     node['boot_state'] = 'disabled'
278
279         logger.debug("SLABV1NODE \tget_nodes_objs  \
280                                 #nodes %s" % (nodes))
281         return nodes
282
283     @staticmethod
284     def add_slivers(xml, slivers):
285         """Add the slivers in parameter to the nodes, by modifying the
286         xml and adding the sliver element in the RSpec.
287
288         :param slivers: list of slivers, which can be either strings or  dict.
289         :type: list
290
291         :returns: None
292         :rtype: None
293
294         .. seealso:: Iotlabv1Sliver : add_slivers
295         .. note:: used by sfiAddSliver and add_nodes (in the file)
296
297         """
298         logger.debug("Iotlabv1NODE \tadd_slivers ")
299         component_ids = []
300         for sliver in slivers:
301             filter_sliver = {}
302             if isinstance(sliver, str):
303                 filter_sliver['component_id'] = '*%s*' % sliver
304                 sliver = {}
305             elif 'component_id' in sliver and sliver['component_id']:
306                 filter_sliver['component_id'] = '*%s*' % sliver['component_id']
307             if not filter_sliver:
308                 continue
309             nodes = Iotlabv1Node.get_nodes(xml, filter_sliver)
310             if not nodes:
311                 continue
312             node = nodes[0]
313             Iotlabv1Sliver.add_slivers(node, sliver)
314
315     @staticmethod
316     def remove_slivers(xml, hostnames):
317         """
318         Removes the slivers for the nodes whose hostnames are on the list.
319
320         :param hostnames: list of nodes' hostnames whose sliver have to be
321             removed.
322         :type hostnames: list
323         """
324         for hostname in hostnames:
325             nodes = Iotlabv1Node.get_nodes(xml, {'component_id': '*%s*'
326                                            % hostname})
327             for node in nodes:
328                 slivers = Iotlabv1Sliver.get_slivers(node.element)
329                 for sliver in slivers:
330                     node.element.remove(sliver.element)