2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 import nepi.util.ipaddr2 as ipaddr2
6 import nepi.util.server as server
17 class NodeIface(object):
18 def __init__(self, api=None):
26 # These get initialized at configuration time
32 self._interface_id = None
34 # These get initialized when the iface is connected to its node
37 # These get initialized when the iface is connected to the internet
38 self.has_internet = False
41 return "%s<ip:%s/%s up mac:%s>" % (
42 self.__class__.__name__,
43 self.address, self.netmask,
49 def add_address(self, address, netprefix, broadcast):
50 raise RuntimeError, "Cannot add explicit addresses to public interface"
52 def pick_iface(self, siblings):
54 Picks an interface using the PLCAPI to query information about the node.
56 Needs an assigned node.
59 siblings: other NodeIface elements attached to the same node
62 if self.node is None or self.node._node_id is None:
63 raise RuntimeError, "Cannot pick interface without an assigned node"
65 avail = self._api.GetInterfaces(
66 node_id=self.node._node_id,
67 is_primary=self.primary,
68 fields=('interface_id','mac','netmask','ip') )
70 used = set([sibling._interface_id for sibling in siblings
71 if sibling._interface_id is not None])
73 for candidate in avail:
74 candidate_id = candidate['interface_id']
75 if candidate_id not in used:
77 self._interface_id = candidate_id
78 self.address = candidate['ip']
79 self.lladdr = candidate['mac']
80 self.netprefix = candidate['netmask']
81 self.netmask = ipaddr2.ipv4_dot2mask(self.netprefix) if self.netprefix else None
84 raise RuntimeError, "Cannot configure interface: cannot find suitable interface in PlanetLab node"
87 if not self.has_internet:
88 raise RuntimeError, "All external interface devices must be connected to the Internet"
91 class _CrossIface(object):
92 def __init__(self, proto, addr, port, cipher):
93 self.tun_proto = proto
96 self.tun_cipher = cipher
100 self.netprefix = None
103 # Cannot access cross peers
104 self.peer_proto_impl = None
108 self.__class__.__name__,
117 class TunIface(object):
118 _PROTO_MAP = tunproto.TUN_PROTO_MAP
121 def __init__(self, api=None):
123 api = plcapi.PLCAPI()
128 self.netprefix = None
134 self.txqueuelen = None
135 self.pointopoint = None
136 self.multicast = False
142 # These get initialized when the iface is connected to its node
145 # These get initialized when the iface is connected to any filter
146 self.filter_module = None
147 self.multicast_forwarder = None
149 # These get initialized when the iface is configured
150 self.external_iface = None
152 # These get initialized when the iface is configured
153 # They're part of the TUN standard attribute set
156 self.tun_cipher = "AES"
158 # These get initialized when the iface is connected to its peer
159 self.peer_iface = None
160 self.peer_proto = None
161 self.peer_addr = None
162 self.peer_port = None
163 self.peer_proto_impl = None
164 self._delay_recover = False
166 # same as peer proto, but for execute-time standard attribute lookups
167 self.tun_proto = None
170 # Generate an initial random cryptographic key to use for tunnelling
171 # Upon connection, both endpoints will agree on a common one based on
173 self.tun_key = os.urandom(32).encode("base64").strip()
177 return "%s<ip:%s/%s %s%s%s>" % (
178 self.__class__.__name__,
179 self.address, self.netprefix,
180 " up" if self.up else " down",
181 " snat" if self.snat else "",
182 (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
189 if self.peer_proto_impl:
190 return self.peer_proto_impl.if_name
192 def routes_here(self, route):
194 Returns True if the route should be attached to this interface
195 (ie, it references a gateway in this interface's network segment)
197 if self.address and self.netprefix:
198 addr, prefix = self.address, self.netprefix
199 pointopoint = self.pointopoint
200 if not pointopoint and self.peer_iface:
201 pointopoint = self.peer_iface.address
206 dest, destprefix, nexthop, metric = route
208 myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
209 gwIp = ipaddr.IPNetwork(nexthop)
212 peerIp = ipaddr.IPNetwork(pointopoint)
221 def add_address(self, address, netprefix, broadcast):
222 if (self.address or self.netprefix or self.netmask) is not None:
223 raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
225 raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
227 self.address = address
228 self.netprefix = netprefix
229 self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
233 raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
234 if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
235 raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
236 if not self.address or not self.netprefix or not self.netmask:
237 raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
238 if self.filter_module and self.peer_proto not in ('udp','tcp',None):
239 raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
240 if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
241 raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
243 def _impl_instance(self, home_path):
244 impl = self._PROTO_MAP[self.peer_proto](
245 self, self.peer_iface, home_path, self.tun_key)
246 impl.port = self.tun_port
247 impl.cross_slice = not self.peer_iface or isinstance(self.peer_iface, _CrossIface)
252 self.peer_proto_impl = self._impl_instance(
254 self.peer_proto_impl.recover()
256 self._delay_recover = True
258 def prepare(self, home_path):
259 if not self.peer_iface and (self.peer_proto and self.peer_addr):
261 self.peer_iface = _CrossIface(
267 if not self.peer_proto_impl:
268 self.peer_proto_impl = self._impl_instance(home_path)
269 if self._delay_recover:
270 self.peer_proto_impl.recover()
273 if self.peer_proto_impl:
274 self.peer_proto_impl.launch()
277 if self.peer_proto_impl:
278 self.peer_proto_impl.shutdown()
281 if self.peer_proto_impl:
282 self.peer_proto_impl.destroy()
283 self.peer_proto_impl = None
286 if self.peer_proto_impl:
287 self.peer_proto_impl.wait()
289 def sync_trace(self, local_dir, whichtrace, tracemap = None):
290 if self.peer_proto_impl:
291 return self.peer_proto_impl.sync_trace(local_dir, whichtrace,
296 def remote_trace_path(self, whichtrace, tracemap = None):
297 if self.peer_proto_impl:
298 return self.peer_proto_impl.remote_trace_path(whichtrace, tracemap)
302 def remote_trace_name(self, whichtrace):
305 class TapIface(TunIface):
306 _PROTO_MAP = tunproto.TAP_PROTO_MAP
309 # Yep, it does nothing - yet
310 class Internet(object):
311 def __init__(self, api=None):
313 api = plcapi.PLCAPI()
316 class NetPipe(object):
317 def __init__(self, api=None):
319 api = plcapi.PLCAPI()
335 # These get initialized when the pipe is connected to its node
337 self.configured = False
341 raise RuntimeError, "Undefined NetPipe mode"
342 if not self.portList:
343 raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
344 if not (self.plrIn or self.bwIn or self.delayIn):
345 raise RuntimeError, "Undefined NetPipe inbound characteristics"
346 if not (self.plrOut or self.bwOut or self.delayOut):
347 raise RuntimeError, "Undefined NetPipe outbound characteristics"
349 raise RuntimeError, "Unconnected NetPipe"
351 def _add_pipedef(self, bw, plr, delay, options):
353 options.extend(("delay","%dms" % (delay,)))
355 options.extend(("bw","%.8fMbit/s" % (bw,)))
357 options.extend(("plr","%.8f" % (plr,)))
359 def _get_ruledef(self):
362 "@" if self.addrList else "",
367 if self.bwIn or self.plrIn or self.delayIn:
369 self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
370 if self.bwOut or self.plrOut or self.delayOut:
371 options.append("OUT")
372 self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
373 options = ' '.join(options)
375 return (scope,options)
378 # Rules are safe on their nodes
379 self.configured = True
383 scope, options = self._get_ruledef()
384 command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
386 (out,err),proc = server.popen_ssh_command(
388 host = self.node.hostname,
390 user = self.node.slicename,
392 ident_key = self.node.ident_path,
393 server_key = self.node.server_key
397 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
399 # we have to clean up afterwards
400 self.configured = True
405 scope, options = self._get_ruledef()
406 command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
408 (out,err),proc = server.popen_ssh_command(
410 host = self.node.hostname,
412 user = self.node.slicename,
414 ident_key = self.node.ident_path,
415 server_key = self.node.server_key
419 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
424 scope, options = self._get_ruledef()
425 command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
427 (out,err),proc = server.popen_ssh_command(
429 host = self.node.hostname,
431 user = self.node.slicename,
433 ident_key = self.node.ident_path,
434 server_key = self.node.server_key
438 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
440 self.configured = False
442 def sync_trace(self, local_dir, whichtrace):
443 if whichtrace != 'netpipeStats':
444 raise ValueError, "Unsupported trace %s" % (whichtrace,)
446 local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
448 # create parent local folders
449 proc = subprocess.Popen(
450 ["mkdir", "-p", os.path.dirname(local_path)],
451 stdout = open("/dev/null","w"),
452 stdin = open("/dev/null","r"))
455 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
457 (out,err),proc = server.popen_ssh_command(
458 "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
459 host = self.node.hostname,
461 user = self.node.slicename,
463 ident_key = self.node.ident_path,
464 server_key = self.node.server_key
468 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
470 # dump results to file
471 f = open(local_path, "wb")
478 class TunFilter(object):
480 # tracename : (remotename, localname)
483 def __init__(self, api=None):
485 api = plcapi.PLCAPI()
492 # These get initialised when the filter is connected
493 self.peer_guid = None
494 self.peer_proto = None
495 self.iface_guid = None
499 def _get(what, self):
504 return getattr(wref, what)
508 def _set(what, self, val):
513 setattr(wref, what, val)
515 tun_proto = property(
516 functools.partial(_get, 'tun_proto'),
517 functools.partial(_set, 'tun_proto') )
519 functools.partial(_get, 'tun_addr'),
520 functools.partial(_set, 'tun_addr') )
522 functools.partial(_get, 'tun_port'),
523 functools.partial(_set, 'tun_port') )
525 functools.partial(_get, 'tun_key'),
526 functools.partial(_set, 'tun_key') )
527 tun_cipher = property(
528 functools.partial(_get, 'tun_cipher'),
529 functools.partial(_set, 'tun_cipher') )
534 def remote_trace_path(self, whichtrace):
536 if iface is not None:
537 return iface.remote_trace_path(whichtrace, self._TRACEMAP)
540 def remote_trace_name(self, whichtrace):
542 if iface is not None:
543 return iface.remote_trace_name(whichtrace, self._TRACEMAP)
546 def sync_trace(self, local_dir, whichtrace):
548 if iface is not None:
549 return iface.sync_trace(local_dir, whichtrace, self._TRACEMAP)
552 class ClassQueueFilter(TunFilter):
554 # tracename : (remotename, localname)
555 'dropped_stats' : ('dropped_stats', 'dropped_stats')
558 def __init__(self, api=None):
559 super(ClassQueueFilter, self).__init__(api)
561 self.module = "classqueue.py"
563 class ToSQueueFilter(TunFilter):
564 def __init__(self, api=None):
565 super(ToSQueueFilter, self).__init__(api)
567 self.module = "tosqueue.py"