2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 from nepi.core import testbed_impl
6 from nepi.util.constants import TIME_NOW
7 from nepi.util.graphtools import mst
8 from nepi.util import ipaddr2
9 from nepi.util import environ
25 from nepi.util.constants import TESTBED_STATUS_CONFIGURED
27 class TempKeyError(Exception):
30 class TestbedController(testbed_impl.TestbedController):
31 def __init__(self, testbed_version):
32 super(TestbedController, self).__init__(TESTBED_ID, testbed_version)
33 self._home_directory = None
37 import node, interfaces, application
39 self._interfaces = interfaces
40 self._app = application
42 self._blacklist = set()
43 self._just_provisioned = set()
45 self._load_blacklist()
48 def home_directory(self):
49 return self._home_directory
53 if not hasattr(self, '_plapi'):
57 self._plapi = plcapi.PLCAPI(
58 username = self.authUser,
59 password = self.authString,
60 hostname = self.plcHost,
61 urlpattern = self.plcUrl
64 # anonymous access - may not be enough for much
65 self._plapi = plcapi.PLCAPI()
70 if not hasattr(self, '_slice_id'):
71 slices = self.plapi.GetSlices(self.slicename, fields=('slice_id',))
73 self._slice_id = slices[0]['slice_id']
75 # If it wasn't found, don't remember this failure, keep trying
79 def _load_blacklist(self):
80 blpath = environ.homepath('plblacklist')
83 bl = open(blpath, "r")
85 self._blacklist = set()
89 self._blacklist = set(
91 map(str.strip, bl.readlines())
97 def _save_blacklist(self):
98 blpath = environ.homepath('plblacklist')
99 bl = open(blpath, "w")
102 map('%s\n'.__mod__, self._blacklist))
107 self._home_directory = self._attributes.\
108 get_attribute_value("homeDirectory")
109 self.slicename = self._attributes.\
110 get_attribute_value("slice")
111 self.authUser = self._attributes.\
112 get_attribute_value("authUser")
113 self.authString = self._attributes.\
114 get_attribute_value("authPass")
115 self.sliceSSHKey = self._attributes.\
116 get_attribute_value("sliceSSHKey")
117 self.sliceSSHKeyPass = None
118 self.plcHost = self._attributes.\
119 get_attribute_value("plcHost")
120 self.plcUrl = self._attributes.\
121 get_attribute_value("plcUrl")
122 super(TestbedController, self).do_setup()
124 def do_post_asynclaunch(self, guid):
125 # Dependencies were launched asynchronously,
127 dep = self._elements[guid]
128 if isinstance(dep, self._app.Dependency):
129 dep.async_setup_wait()
131 # Two-phase configuration for asynchronous launch
132 do_poststep_preconfigure = staticmethod(do_post_asynclaunch)
133 do_poststep_configure = staticmethod(do_post_asynclaunch)
135 def do_preconfigure(self):
137 # Perform resource discovery if we don't have
138 # specific resources assigned yet
139 self.do_resource_discovery()
141 # Create PlanetLab slivers
142 self.do_provisioning()
145 # Wait for provisioning
150 except self._node.UnresponsiveNodeError:
154 # Plan application deployment
155 self.do_spanning_deployment_plan()
157 # Configure elements per XML data
158 super(TestbedController, self).do_preconfigure()
160 def do_resource_discovery(self):
161 to_provision = self._to_provision = set()
163 reserved = set(self._blacklist)
164 for guid, node in self._elements.iteritems():
165 if isinstance(node, self._node.Node) and node._node_id is not None:
166 reserved.add(node._node_id)
169 # look for perfectly defined nodes
170 # (ie: those with only one candidate)
171 for guid, node in self._elements.iteritems():
172 if isinstance(node, self._node.Node) and node._node_id is None:
173 # Try existing nodes first
174 # If we have only one candidate, simply use it
175 candidates = node.find_candidates(
176 filter_slice_id = self.slice_id)
177 candidates -= reserved
178 if len(candidates) == 1:
179 node_id = iter(candidates).next()
180 node.assign_node_id(node_id)
181 reserved.add(node_id)
183 # Try again including unassigned nodes
184 candidates = node.find_candidates()
185 candidates -= reserved
186 if len(candidates) > 1:
188 if len(candidates) == 1:
189 node_id = iter(candidates).next()
190 node.assign_node_id(node_id)
191 to_provision.add(node_id)
192 reserved.add(node_id)
194 raise RuntimeError, "Cannot assign resources for node %s, no candidates sith %s" % (guid,
195 node.make_filter_description())
197 # Now do the backtracking search for a suitable solution
198 # First with existing slice nodes
201 for guid, node in self._elements.iteritems():
202 if isinstance(node, self._node.Node) and node._node_id is None:
203 # Try existing nodes first
204 # If we have only one candidate, simply use it
205 candidates = node.find_candidates(
206 filter_slice_id = self.slice_id)
207 candidates -= reserved
208 reqs.append(candidates)
213 solution = resourcealloc.alloc(reqs)
214 except resourcealloc.ResourceAllocationError:
215 # Failed, try again with all nodes
218 candidates = node.find_candidates()
219 reqs.append(candidates)
221 solution = resourcealloc.alloc(reqs)
222 to_provision.update(solution)
225 for node, node_id in zip(nodes, solution):
226 node.assign_node_id(node_id)
228 def do_provisioning(self):
229 if self._to_provision:
230 # Add new nodes to the slice
231 cur_nodes = self.plapi.GetSlices(self.slicename, ['node_ids'])[0]['node_ids']
232 new_nodes = list(set(cur_nodes) | self._to_provision)
233 self.plapi.UpdateSlice(self.slicename, nodes=new_nodes)
236 self._just_provisioned = self._to_provision
237 del self._to_provision
239 def do_wait_nodes(self):
240 for guid, node in self._elements.iteritems():
241 if isinstance(node, self._node.Node):
242 # Just inject configuration stuff
243 node.home_path = "nepi-node-%s" % (guid,)
244 node.ident_path = self.sliceSSHKey
245 node.slicename = self.slicename
248 print "PlanetLab Node", guid, "configured at", node.hostname
251 for guid, node in self._elements.iteritems():
252 if isinstance(node, self._node.Node):
253 print "Waiting for Node", guid, "configured at", node.hostname,
256 node.wait_provisioning(
257 (20*60 if node._node_id in self._just_provisioned else 60)
261 except self._node.UnresponsiveNodeError:
265 # Mark all dead nodes (which are unresponsive) on the blacklist
267 for guid, node in self._elements.iteritems():
268 if isinstance(node, self._node.Node):
269 if not node.is_alive():
270 print "Blacklisting", node.hostname, "for unresponsiveness"
271 self._blacklist.add(node._node_id)
275 self._save_blacklist()
279 traceback.print_exc()
283 def do_spanning_deployment_plan(self):
284 # Create application groups by collecting all applications
285 # based on their hash - the hash should contain everything that
286 # defines them and the platform they're built
290 frozenset((app.depends or "").split(' ')),
291 frozenset((app.sources or "").split(' ')),
294 app.node.architecture,
295 app.node.operatingSystem,
299 depgroups = collections.defaultdict(list)
301 for element in self._elements.itervalues():
302 if isinstance(element, self._app.Dependency):
303 depgroups[dephash(element)].append(element)
305 # Set up spanning deployment for those applications that
306 # have been deployed in several nodes.
307 for dh, group in depgroups.iteritems():
309 # Pick root (deterministically)
310 root = min(group, key=lambda app:app.node.hostname)
312 # Obtain all IPs in numeric format
313 # (which means faster distance computations)
315 dep._ip = socket.gethostbyname(dep.node.hostname)
316 dep._ip_n = struct.unpack('!L', socket.inet_aton(dep._ip))[0]
319 # NOTE: the plan is an iterator
322 lambda a,b : ipaddr2.ipdistn(a._ip_n, b._ip_n),
326 # Re-sign private key
328 tempprk, temppuk, tmppass = self._make_temp_private_key()
334 for slave, master in plan:
335 slave.set_master(master)
336 slave.install_keys(tempprk, temppuk, tmppass)
338 # We don't need the user's passphrase anymore
339 self.sliceSSHKeyPass = None
341 def _make_temp_private_key(self):
342 # Get the user's key's passphrase
343 if not self.sliceSSHKeyPass:
344 if 'SSH_ASKPASS' in os.environ:
345 proc = subprocess.Popen(
346 [ os.environ['SSH_ASKPASS'],
347 "Please type the passphrase for the %s SSH identity file. "
348 "The passphrase will be used to re-cipher the identity file with "
349 "a random 256-bit key for automated chain deployment on the "
350 "%s PlanetLab slice" % (
351 os.path.basename(self.sliceSSHKey),
354 stdin = open("/dev/null"),
355 stdout = subprocess.PIPE,
356 stderr = subprocess.PIPE)
357 out,err = proc.communicate()
358 self.sliceSSHKeyPass = out.strip()
360 if not self.sliceSSHKeyPass:
363 # Create temporary key files
364 prk = tempfile.NamedTemporaryFile(
365 dir = self.root_directory,
366 prefix = "pl_deploy_tmpk_",
369 puk = tempfile.NamedTemporaryFile(
370 dir = self.root_directory,
371 prefix = "pl_deploy_tmpk_",
374 # Create secure 256-bits temporary passphrase
375 passphrase = ''.join(map(chr,[rng.randint(0,255)
376 for rng in (random.SystemRandom(),)
377 for i in xrange(32)] )).encode("hex")
380 oprk = open(self.sliceSSHKey, "rb")
381 opuk = open(self.sliceSSHKey+".pub", "rb")
382 shutil.copymode(oprk.name, prk.name)
383 shutil.copymode(opuk.name, puk.name)
384 shutil.copyfileobj(oprk, prk)
385 shutil.copyfileobj(opuk, puk)
391 # A descriptive comment
392 comment = "%s#NEPI_INTERNAL@%s" % (self.authUser, self.slicename)
395 proc = subprocess.Popen(
398 "-P", self.sliceSSHKeyPass,
401 stdout = subprocess.PIPE,
402 stderr = subprocess.PIPE,
403 stdin = subprocess.PIPE
405 out, err = proc.communicate()
408 raise RuntimeError, "Problem generating keys: \n%s\n%r" % (
414 # Change comment on public key
415 puklines = puk.readlines()
416 puklines[0] = puklines[0].split(' ')
417 puklines[0][-1] = comment+'\n'
418 puklines[0] = ' '.join(puklines[0])
421 puk.writelines(puklines)
425 return prk, puk, passphrase
427 def set(self, guid, name, value, time = TIME_NOW):
428 super(TestbedController, self).set(guid, name, value, time)
429 # TODO: take on account schedule time for the task
430 element = self._elements[guid]
432 setattr(element, name, value)
434 if hasattr(element, 'refresh'):
435 # invoke attribute refresh hook
438 def get(self, guid, name, time = TIME_NOW):
439 value = super(TestbedController, self).get(guid, name, time)
440 # TODO: take on account schedule time for the task
441 factory_id = self._create[guid]
442 factory = self._factories[factory_id]
443 if factory.box_attributes.is_attribute_design_only(name):
445 element = self._elements.get(guid)
447 return getattr(element, name)
448 except KeyError, AttributeError:
451 def get_address(self, guid, index, attribute='Address'):
455 iface = self._elements.get(guid)
456 if iface and index == 0:
457 if attribute == 'Address':
459 elif attribute == 'NetPrefix':
460 return iface.netprefix
461 elif attribute == 'Broadcast':
462 return iface.broadcast
464 # if all else fails, query box
465 return super(TestbedController, self).get_address(guid, index, attribute)
467 def action(self, time, guid, action):
468 raise NotImplementedError
471 for trace in self._traces.itervalues():
473 for element in self._elements.itervalues():
474 # invoke cleanup hooks
475 if hasattr(element, 'cleanup'):
477 for element in self._elements.itervalues():
478 # invoke destroy hooks
479 if hasattr(element, 'destroy'):
481 self._elements.clear()
484 def trace(self, guid, trace_id, attribute='value'):
485 app = self._elements[guid]
487 if attribute == 'value':
488 path = app.sync_trace(self.home_directory, trace_id)
495 elif attribute == 'path':
496 content = app.remote_trace_path(trace_id)
501 def follow_trace(self, trace_id, trace):
502 self._traces[trace_id] = trace
504 def _make_generic(self, parameters, kind):
505 app = kind(self.plapi)
507 # Note: there is 1-to-1 correspondence between attribute names
508 # If that changes, this has to change as well
509 for attr,val in parameters.iteritems():
510 setattr(app, attr, val)
514 def _make_node(self, parameters):
515 node = self._make_generic(parameters, self._node.Node)
517 # If emulation is enabled, we automatically need
518 # some vsys interfaces and packages
520 node.required_vsys.add('ipfw-be')
521 node.required_packages.add('ipfwslice')
525 def _make_node_iface(self, parameters):
526 return self._make_generic(parameters, self._interfaces.NodeIface)
528 def _make_tun_iface(self, parameters):
529 return self._make_generic(parameters, self._interfaces.TunIface)
531 def _make_tap_iface(self, parameters):
532 return self._make_generic(parameters, self._interfaces.TapIface)
534 def _make_netpipe(self, parameters):
535 return self._make_generic(parameters, self._interfaces.NetPipe)
537 def _make_internet(self, parameters):
538 return self._make_generic(parameters, self._interfaces.Internet)
540 def _make_application(self, parameters):
541 return self._make_generic(parameters, self._app.Application)
543 def _make_dependency(self, parameters):
544 return self._make_generic(parameters, self._app.Dependency)
546 def _make_nepi_dependency(self, parameters):
547 return self._make_generic(parameters, self._app.NepiDependency)
549 def _make_ns3_dependency(self, parameters):
550 return self._make_generic(parameters, self._app.NS3Dependency)