2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19 # Lucia Guevgeozian <lucia.guevgeozian_odizzio@inria.fr>
21 from nepi.execution.attribute import Attribute, Flags, Types
22 from nepi.execution.resource import ResourceManager, clsinit_copy, \
23 ResourceState, reschedule_delay
24 from nepi.resources.linux.node import LinuxNode
25 from nepi.resources.planetlab.plcapi import PLCAPIFactory
26 from nepi.util.execfuncs import lexec
27 from nepi.util import sshfuncs
29 from random import randint
35 class PlanetlabNode(LinuxNode):
36 _rtype = "PlanetlabNode"
37 _help = "Controls a PlanetLab host accessible using a SSH key " \
38 "associated to a PlanetLab user account"
39 _backend = "planetlab"
41 lock = threading.Lock()
44 def _register_attributes(cls):
45 ip = Attribute("ip", "PlanetLab host public IP address",
46 flags = Flags.ReadOnly)
48 pl_url = Attribute("plcApiUrl", "URL of PlanetLab PLCAPI host \
49 (e.g. www.planet-lab.eu or www.planet-lab.org) ",
50 default = "www.planet-lab.eu",
51 flags = Flags.Credential)
53 pl_ptn = Attribute("plcApiPattern", "PLC API service regexp pattern \
54 (e.g. https://%(hostname)s:443/PLCAPI/ ) ",
55 default = "https://%(hostname)s:443/PLCAPI/",
56 flags = Flags.ExecReadOnly)
58 pl_user = Attribute("pluser", "PlanetLab account user, as the one to \
59 authenticate in the website) ",
60 flags = Flags.Credential)
62 pl_password = Attribute("plpassword",
63 "PlanetLab account password, as \
64 the one to authenticate in the website) ",
65 flags = Flags.Credential)
67 city = Attribute("city", "Constrain location (city) during resource \
68 discovery. May use wildcards.",
71 country = Attribute("country", "Constrain location (country) during \
72 resource discovery. May use wildcards.",
75 region = Attribute("region", "Constrain location (region) during \
76 resource discovery. May use wildcards.",
79 architecture = Attribute("architecture", "Constrain architecture \
80 during resource discovery.",
81 type = Types.Enumerate,
86 operating_system = Attribute("operatingSystem", "Constrain operating \
87 system during resource discovery.",
88 type = Types.Enumerate,
96 #site = Attribute("site", "Constrain the PlanetLab site this node \
98 # type = Types.Enumerate,
102 # flags = Flags.Filter)
104 min_reliability = Attribute("minReliability", "Constrain reliability \
105 while picking PlanetLab nodes. Specifies a lower \
109 flags = Flags.Filter)
111 max_reliability = Attribute("maxReliability", "Constrain reliability \
112 while picking PlanetLab nodes. Specifies an upper \
116 flags = Flags.Filter)
118 min_bandwidth = Attribute("minBandwidth", "Constrain available \
119 bandwidth while picking PlanetLab nodes. \
120 Specifies a lower acceptable bound.",
123 flags = Flags.Filter)
125 max_bandwidth = Attribute("maxBandwidth", "Constrain available \
126 bandwidth while picking PlanetLab nodes. \
127 Specifies an upper acceptable bound.",
130 flags = Flags.Filter)
132 min_load = Attribute("minLoad", "Constrain node load average while \
133 picking PlanetLab nodes. Specifies a lower acceptable \
137 flags = Flags.Filter)
139 max_load = Attribute("maxLoad", "Constrain node load average while \
140 picking PlanetLab nodes. Specifies an upper acceptable \
144 flags = Flags.Filter)
146 min_cpu = Attribute("minCpu", "Constrain available cpu time while \
147 picking PlanetLab nodes. Specifies a lower acceptable \
151 flags = Flags.Filter)
153 max_cpu = Attribute("maxCpu", "Constrain available cpu time while \
154 picking PlanetLab nodes. Specifies an upper acceptable \
158 flags = Flags.Filter)
160 timeframe = Attribute("timeframe", "Past time period in which to check\
161 information about the node. Values are year,month, \
164 type = Types.Enumerate,
169 flags = Flags.Filter)
171 cls._register_attribute(ip)
172 cls._register_attribute(pl_url)
173 cls._register_attribute(pl_ptn)
174 cls._register_attribute(pl_user)
175 cls._register_attribute(pl_password)
176 #cls._register_attribute(site)
177 cls._register_attribute(city)
178 cls._register_attribute(country)
179 cls._register_attribute(region)
180 cls._register_attribute(architecture)
181 cls._register_attribute(operating_system)
182 cls._register_attribute(min_reliability)
183 cls._register_attribute(max_reliability)
184 cls._register_attribute(min_bandwidth)
185 cls._register_attribute(max_bandwidth)
186 cls._register_attribute(min_load)
187 cls._register_attribute(max_load)
188 cls._register_attribute(min_cpu)
189 cls._register_attribute(max_cpu)
190 cls._register_attribute(timeframe)
192 def __init__(self, ec, guid):
193 super(PlanetlabNode, self).__init__(ec, guid)
196 self._node_to_provision = None
197 self._slicenode = False
202 pl_user = self.get("pluser")
203 pl_pass = self.get("plpassword")
204 pl_url = self.get("plcApiUrl")
205 pl_ptn = self.get("plcApiPattern")
207 self._plapi = PLCAPIFactory.get_api(pl_user, pl_pass, pl_url,
215 def do_discover(self):
217 Based on the attributes defined by the user, discover the suitable
220 hostname = self._get_hostname()
222 # the user specified one particular node to be provisioned
223 # check with PLCAPI if it is alvive
224 node_id = self._query_if_alive(hostname=hostname)
225 node_id = node_id.pop()
227 # check that the node is not blacklisted or being provisioned
229 with PlanetlabNode.lock:
230 plist = self.plapi.reserved()
231 blist = self.plapi.blacklisted()
232 if node_id not in blist and node_id not in plist:
234 # check that is really alive, by performing ping
235 ping_ok = self._do_ping(node_id)
237 self._blacklist_node(node_id)
238 self.fail_node_not_alive(hostname)
240 if self._check_if_in_slice([node_id]):
241 self._slicenode = True
242 self._put_node_in_provision(node_id)
243 self._node_to_provision = node_id
244 super(PlanetlabNode, self).do_discover()
247 self.fail_node_not_available(hostname)
250 # the user specifies constraints based on attributes, zero, one or
251 # more nodes can match these constraints
252 nodes = self._filter_based_on_attributes()
253 nodes_alive = self._query_if_alive(nodes)
255 # nodes that are already part of user's slice have the priority to
257 nodes_inslice = self._check_if_in_slice(nodes_alive)
258 nodes_not_inslice = list(set(nodes_alive) - set(nodes_inslice))
262 node_id = self._choose_random_node(nodes_inslice)
263 self._slicenode = True
266 # Either there were no matching nodes in the user's slice, or
267 # the nodes in the slice were blacklisted or being provisioned
268 # by other RM. Note nodes_not_inslice is never empty
269 node_id = self._choose_random_node(nodes_not_inslice)
270 self._slicenode = False
273 self._node_to_provision = node_id
275 self._set_hostname_attr(node_id)
276 self.info(" Selected node to provision ")
278 with PlanetlabNode.lock:
279 self._blacklist_node(node_id)
282 super(PlanetlabNode, self).do_discover()
284 self.fail_not_enough_nodes()
286 def do_provision(self):
288 Add node to user's slice after verifing that the node is functioning
296 while not provision_ok:
297 node = self._node_to_provision
298 if not self._slicenode:
299 self._add_node_to_slice(node)
301 # check ssh connection
303 while t < timeout and not ssh_ok:
305 cmd = 'echo \'GOOD NODE\''
306 ((out, err), proc) = self.execute(cmd)
307 if out.find("GOOD NODE") < 0:
315 cmd = 'echo \'GOOD NODE\''
316 ((out, err), proc) = self.execute(cmd)
317 if not out.find("GOOD NODE") < 0:
321 # the timeout was reach without establishing ssh connection
322 # the node is blacklisted, deleted from the slice, and a new
323 # node to provision is discovered
324 with PlanetlabNode.lock:
325 self.warn(" Could not SSH login ")
326 self._blacklist_node(node)
327 #self._delete_node_from_slice(node)
328 self.set('hostname', None)
332 # check /proc directory is mounted (ssh_ok = True)
334 cmd = 'mount |grep proc'
335 ((out, err), proc) = self.execute(cmd)
336 if out.find("/proc type proc") < 0:
337 with PlanetlabNode.lock:
338 self.warn(" Could not find directory /proc ")
339 self._blacklist_node(node)
340 #self._delete_node_from_slice(node)
341 self.set('hostname', None)
348 ip = self._get_ip(node)
351 super(PlanetlabNode, self).do_provision()
353 def _filter_based_on_attributes(self):
355 Retrive the list of nodes ids that match user's constraints
357 # Map user's defined attributes with tagnames of PlanetLab
358 timeframe = self.get("timeframe")[0]
361 'country' : 'country',
363 'architecture' : 'arch',
364 'operatingSystem' : 'fcdistro',
365 #'site' : 'pldistro',
366 'minReliability' : 'reliability%s' % timeframe,
367 'maxReliability' : 'reliability%s' % timeframe,
368 'minBandwidth' : 'bw%s' % timeframe,
369 'maxBandwidth' : 'bw%s' % timeframe,
370 'minLoad' : 'load%s' % timeframe,
371 'maxLoad' : 'load%s' % timeframe,
372 'minCpu' : 'cpu%s' % timeframe,
373 'maxCpu' : 'cpu%s' % timeframe,
379 for attr_name, attr_obj in self._attrs.iteritems():
380 attr_value = self.get(attr_name)
382 if attr_value is not None and attr_obj.flags == 8 and \
383 attr_name != 'timeframe':
385 attr_tag = attr_to_tags[attr_name]
386 filters['tagname'] = attr_tag
388 # filter nodes by fixed constraints e.g. operating system
389 if not 'min' in attr_name and not 'max' in attr_name:
390 filters['value'] = attr_value
391 nodes_id = self._filter_by_fixed_attr(filters, nodes_id)
393 # filter nodes by range constraints e.g. max bandwidth
394 elif ('min' or 'max') in attr_name:
395 nodes_id = self._filter_by_range_attr(attr_name, attr_value, filters, nodes_id)
398 nodes = self.plapi.get_nodes()
400 nodes_id.append(node['node_id'])
405 def _filter_by_fixed_attr(self, filters, nodes_id):
407 Query PLCAPI for nodes ids matching fixed attributes defined by the
410 node_tags = self.plapi.get_node_tags(filters)
411 if node_tags is not None:
413 if len(nodes_id) == 0:
414 # first attribute being matched
415 for node_tag in node_tags:
416 nodes_id.append(node_tag['node_id'])
418 # remove the nodes ids that don't match the new attribute
419 # that is being match
422 for node_tag in node_tags:
423 if node_tag['node_id'] in nodes_id:
424 nodes_id_tmp.append(node_tag['node_id'])
426 if len(nodes_id_tmp):
427 nodes_id = set(nodes_id) & set(nodes_id_tmp)
429 # no node from before match the new constraint
430 self.fail_discovery()
432 # no nodes match the filter applied
433 self.fail_discovery()
437 def _filter_by_range_attr(self, attr_name, attr_value, filters, nodes_id):
439 Query PLCAPI for nodes ids matching attributes defined in a certain
442 node_tags = self.plapi.get_node_tags(filters)
443 if node_tags is not None:
445 if len(nodes_id) == 0:
446 # first attribute being matched
447 for node_tag in node_tags:
449 # check that matches the min or max restriction
450 if 'min' in attr_name and node_tag['value'] != 'n/a' and \
451 float(node_tag['value']) > attr_value:
452 nodes_id.append(node_tag['node_id'])
454 elif 'max' in attr_name and node_tag['value'] != 'n/a' and \
455 float(node_tag['value']) < attr_value:
456 nodes_id.append(node_tag['node_id'])
459 # remove the nodes ids that don't match the new attribute
460 # that is being match
462 for node_tag in node_tags:
464 # check that matches the min or max restriction and was a
465 # matching previous filters
466 if 'min' in attr_name and node_tag['value'] != 'n/a' and \
467 float(node_tag['value']) > attr_value and \
468 node_tag['node_id'] in nodes_id:
469 nodes_id_tmp.append(node_tag['node_id'])
471 elif 'max' in attr_name and node_tag['value'] != 'n/a' and \
472 float(node_tag['value']) < attr_value and \
473 node_tag['node_id'] in nodes_id:
474 nodes_id_tmp.append(node_tag['node_id'])
476 if len(nodes_id_tmp):
477 nodes_id = set(nodes_id) & set(nodes_id_tmp)
479 # no node from before match the new constraint
480 self.fail_discovery()
483 # no nodes match the filter applied
484 self.fail_discovery()
488 def _query_if_alive(self, nodes_id=None, hostname=None):
490 Query PLCAPI for nodes that register activity recently, using filters
491 related to the state of the node, e.g. last time it was contacted
493 if nodes_id is None and hostname is None:
494 msg = "Specify nodes_id or hostname"
495 raise RuntimeError, msg
497 if nodes_id is not None and hostname is not None:
498 msg = "Specify either nodes_id or hostname"
499 raise RuntimeError, msg
501 # define PL filters to check the node is alive
503 filters['run_level'] = 'boot'
504 filters['boot_state'] = 'boot'
505 filters['node_type'] = 'regular'
506 #filters['>last_contact'] = int(time.time()) - 2*3600
508 # adding node_id or hostname to the filters to check for the particular
511 filters['node_id'] = list(nodes_id)
512 alive_nodes_id = self._get_nodes_id(filters)
514 filters['hostname'] = hostname
515 alive_nodes_id = self._get_nodes_id(filters)
517 if len(alive_nodes_id) == 0:
518 self.fail_node_not_alive(self, hostname)
521 for node_id in alive_nodes_id:
522 nid = node_id['node_id']
527 def _choose_random_node(self, nodes):
529 From the possible nodes for provision, choose randomly to decrese the
530 probability of different RMs choosing the same node for provision
535 index = randint(0, size)
536 node_id = nodes[index]
537 nodes[index] = nodes[size]
539 # check the node is not blacklisted or being provision by other RM
540 # and perform ping to check that is really alive
541 with PlanetlabNode.lock:
543 blist = self.plapi.blacklisted()
544 plist = self.plapi.reserved()
545 if node_id not in blist and node_id not in plist:
546 ping_ok = self._do_ping(node_id)
548 self._set_hostname_attr(node_id)
549 self.warn(" Node not responding PING ")
550 self._blacklist_node(node_id)
551 self.set('hostname', None)
553 # discovered node for provision, added to provision list
554 self._put_node_in_provision(node_id)
557 def _get_nodes_id(self, filters):
558 return self.plapi.get_nodes(filters, fields=['node_id'])
560 def _add_node_to_slice(self, node_id):
561 self.info(" Adding node to slice ")
562 slicename = self.get("username")
563 with PlanetlabNode.lock:
564 slice_nodes = self.plapi.get_slice_nodes(slicename)
565 slice_nodes.append(node_id)
566 self.plapi.add_slice_nodes(slicename, slice_nodes)
568 def _delete_node_from_slice(self, node):
569 self.warn(" Deleting node from slice ")
570 slicename = self.get("username")
571 self.plapi.delete_slice_node(slicename, [node])
573 def _get_hostname(self):
574 hostname = self.get("hostname")
579 hostname = sshfuncs.gethostbyname(ip)
584 def _set_hostname_attr(self, node):
586 Query PLCAPI for the hostname of a certain node id and sets the
587 attribute hostname, it will over write the previous value
589 hostname = self.plapi.get_nodes(node, ['hostname'])
590 self.set("hostname", hostname[0]['hostname'])
592 def _check_if_in_slice(self, nodes_id):
594 Query PLCAPI to find out if any node id from nodes_id is in the user's
597 slicename = self.get("username")
598 slice_nodes = self.plapi.get_slice_nodes(slicename)
599 nodes_inslice = list(set(nodes_id) & set(slice_nodes))
602 def _do_ping(self, node_id):
604 Perform ping command on node's IP matching node id
607 ip = self._get_ip(node_id)
608 if not ip: return ping_ok
610 command = "ping -c2 %s" % ip
612 (out, err) = lexec(command)
613 if not out.find("2 received") < 0:
618 def _blacklist_node(self, node):
620 Add node mal functioning node to blacklist
622 self.warn(" Blacklisting malfunctioning node ")
623 self._plapi.blacklist_host(node)
625 def _put_node_in_provision(self, node):
627 Add node to the list of nodes being provisioned, in order for other RMs
628 to not try to provision the same one again
630 self._plapi.reserve_host(node)
632 def _get_ip(self, node_id):
634 Query PLCAPI for the IP of a node with certain node id
636 hostname = self.plapi.get_nodes(node_id, ['hostname'])[0]
638 ip = sshfuncs.gethostbyname(hostname['hostname'])
640 # Fail while trying to find the IP
644 def fail_discovery(self):
646 msg = "Discovery failed. No candidates found for node"
648 raise RuntimeError, msg
650 def fail_node_not_alive(self, hostname=None):
652 msg = "Node %s not alive" % hostname
653 raise RuntimeError, msg
655 def fail_node_not_available(self, hostname):
657 msg = "Node %s not available for provisioning" % hostname
658 raise RuntimeError, msg
660 def fail_not_enough_nodes(self):
662 msg = "Not enough nodes available for provisioning"
663 raise RuntimeError, msg
665 def fail_plapi(self):
667 msg = "Failing while trying to instanciate the PLC API"
668 raise RuntimeError, msg
670 def valid_connection(self, guid):