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
98 # Cannot access cross peers
99 self.peer_proto_impl = None
103 self.__class__.__name__,
112 class TunIface(object):
113 _PROTO_MAP = tunproto.TUN_PROTO_MAP
116 def __init__(self, api=None):
118 api = plcapi.PLCAPI()
123 self.netprefix = None
129 self.txqueuelen = None
130 self.pointopoint = None
131 self.multicast = False
137 # These get initialized when the iface is connected to its node
140 # These get initialized when the iface is connected to any filter
141 self.filter_module = None
142 self.multicast_forwarder = None
144 # These get initialized when the iface is configured
145 self.external_iface = None
147 # These get initialized when the iface is configured
148 # They're part of the TUN standard attribute set
151 self.tun_cipher = "AES"
153 # These get initialized when the iface is connected to its peer
154 self.peer_iface = None
155 self.peer_proto = None
156 self.peer_addr = None
157 self.peer_port = None
158 self.peer_proto_impl = None
159 self._delay_recover = False
161 # same as peer proto, but for execute-time standard attribute lookups
162 self.tun_proto = None
165 # Generate an initial random cryptographic key to use for tunnelling
166 # Upon connection, both endpoints will agree on a common one based on
168 self.tun_key = ( ''.join(map(chr, [
171 for r in (random.SystemRandom(),) ])
172 ).encode("base64").strip() )
176 return "%s<ip:%s/%s %s%s%s>" % (
177 self.__class__.__name__,
178 self.address, self.netprefix,
179 " up" if self.up else " down",
180 " snat" if self.snat else "",
181 (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
188 if self.peer_proto_impl:
189 return self.peer_proto_impl.if_name
191 def routes_here(self, route):
193 Returns True if the route should be attached to this interface
194 (ie, it references a gateway in this interface's network segment)
196 if self.address and self.netprefix:
197 addr, prefix = self.address, self.netprefix
198 pointopoint = self.pointopoint
200 pointopoint = self.peer_iface.address
205 dest, destprefix, nexthop, metric = route
207 myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
208 gwIp = ipaddr.IPNetwork(nexthop)
211 peerIp = ipaddr.IPNetwork(pointopoint)
220 def add_address(self, address, netprefix, broadcast):
221 if (self.address or self.netprefix or self.netmask) is not None:
222 raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
224 raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
226 self.address = address
227 self.netprefix = netprefix
228 self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
232 raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
233 if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
234 raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
235 if not self.address or not self.netprefix or not self.netmask:
236 raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
237 if self.filter_module and self.peer_proto not in ('udp','tcp',None):
238 raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
239 if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
240 raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
242 def _impl_instance(self, home_path):
243 impl = self._PROTO_MAP[self.peer_proto](
244 self, self.peer_iface, home_path, self.tun_key)
245 impl.port = self.tun_port
246 impl.cross_slice = not self.peer_iface or isinstance(self.peer_iface, _CrossIface)
251 self.peer_proto_impl = self._impl_instance(
253 self.peer_proto_impl.recover()
255 self._delay_recover = True
257 def prepare(self, home_path):
258 if not self.peer_iface and (self.peer_proto and self.peer_addr and self.peer_port):
260 self.peer_iface = _CrossIface(
266 if not self.peer_proto_impl:
267 self.peer_proto_impl = self._impl_instance(home_path)
268 if self._delay_recover:
269 self.peer_proto_impl.recover()
272 if self.peer_proto_impl:
273 self.peer_proto_impl.launch()
276 if self.peer_proto_impl:
277 self.peer_proto_impl.shutdown()
280 if self.peer_proto_impl:
281 self.peer_proto_impl.destroy()
282 self.peer_proto_impl = None
285 if self.peer_proto_impl:
286 self.peer_proto_impl.wait()
288 def sync_trace(self, local_dir, whichtrace, tracemap = None):
289 if self.peer_proto_impl:
290 return self.peer_proto_impl.sync_trace(local_dir, whichtrace,
295 def remote_trace_path(self, whichtrace, tracemap = None):
296 if self.peer_proto_impl:
297 return self.peer_proto_impl.remote_trace_path(whichtrace, tracemap)
301 def remote_trace_name(self, whichtrace):
304 class TapIface(TunIface):
305 _PROTO_MAP = tunproto.TAP_PROTO_MAP
308 # Yep, it does nothing - yet
309 class Internet(object):
310 def __init__(self, api=None):
312 api = plcapi.PLCAPI()
315 class NetPipe(object):
316 def __init__(self, api=None):
318 api = plcapi.PLCAPI()
334 # These get initialized when the pipe is connected to its node
336 self.configured = False
340 raise RuntimeError, "Undefined NetPipe mode"
341 if not self.portList:
342 raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
343 if not (self.plrIn or self.bwIn or self.delayIn):
344 raise RuntimeError, "Undefined NetPipe inbound characteristics"
345 if not (self.plrOut or self.bwOut or self.delayOut):
346 raise RuntimeError, "Undefined NetPipe outbound characteristics"
348 raise RuntimeError, "Unconnected NetPipe"
350 def _add_pipedef(self, bw, plr, delay, options):
352 options.extend(("delay","%dms" % (delay,)))
354 options.extend(("bw","%.8fMbit/s" % (bw,)))
356 options.extend(("plr","%.8f" % (plr,)))
358 def _get_ruledef(self):
361 "@" if self.addrList else "",
366 if self.bwIn or self.plrIn or self.delayIn:
368 self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
369 if self.bwOut or self.plrOut or self.delayOut:
370 options.append("OUT")
371 self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
372 options = ' '.join(options)
374 return (scope,options)
377 # Rules are safe on their nodes
378 self.configured = True
382 scope, options = self._get_ruledef()
383 command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
385 (out,err),proc = server.popen_ssh_command(
387 host = self.node.hostname,
389 user = self.node.slicename,
391 ident_key = self.node.ident_path,
392 server_key = self.node.server_key
396 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
398 # we have to clean up afterwards
399 self.configured = True
404 scope, options = self._get_ruledef()
405 command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
407 (out,err),proc = server.popen_ssh_command(
409 host = self.node.hostname,
411 user = self.node.slicename,
413 ident_key = self.node.ident_path,
414 server_key = self.node.server_key
418 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
423 scope, options = self._get_ruledef()
424 command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
426 (out,err),proc = server.popen_ssh_command(
428 host = self.node.hostname,
430 user = self.node.slicename,
432 ident_key = self.node.ident_path,
433 server_key = self.node.server_key
437 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
439 self.configured = False
441 def sync_trace(self, local_dir, whichtrace):
442 if whichtrace != 'netpipeStats':
443 raise ValueError, "Unsupported trace %s" % (whichtrace,)
445 local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
447 # create parent local folders
448 proc = subprocess.Popen(
449 ["mkdir", "-p", os.path.dirname(local_path)],
450 stdout = open("/dev/null","w"),
451 stdin = open("/dev/null","r"))
454 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
456 (out,err),proc = server.popen_ssh_command(
457 "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
458 host = self.node.hostname,
460 user = self.node.slicename,
462 ident_key = self.node.ident_path,
463 server_key = self.node.server_key
467 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
469 # dump results to file
470 f = open(local_path, "wb")
477 class TunFilter(object):
479 # tracename : (remotename, localname)
482 def __init__(self, api=None):
484 api = plcapi.PLCAPI()
491 # These get initialised when the filter is connected
492 self.peer_guid = None
493 self.peer_proto = None
494 self.iface_guid = None
498 def _get(what, self):
503 return getattr(wref, what)
507 def _set(what, self, val):
512 setattr(wref, what, val)
514 tun_proto = property(
515 functools.partial(_get, 'tun_proto'),
516 functools.partial(_set, 'tun_proto') )
518 functools.partial(_get, 'tun_addr'),
519 functools.partial(_set, 'tun_addr') )
521 functools.partial(_get, 'tun_port'),
522 functools.partial(_set, 'tun_port') )
524 functools.partial(_get, 'tun_key'),
525 functools.partial(_set, 'tun_key') )
526 tun_cipher = property(
527 functools.partial(_get, 'tun_cipher'),
528 functools.partial(_set, 'tun_cipher') )
533 def remote_trace_path(self, whichtrace):
535 if iface is not None:
536 return iface.remote_trace_path(whichtrace, self._TRACEMAP)
539 def remote_trace_name(self, whichtrace):
541 if iface is not None:
542 return iface.remote_trace_name(whichtrace, self._TRACEMAP)
545 def sync_trace(self, local_dir, whichtrace):
547 if iface is not None:
548 return iface.sync_trace(local_dir, whichtrace, self._TRACEMAP)
551 class ClassQueueFilter(TunFilter):
553 # tracename : (remotename, localname)
554 'dropped_stats' : ('dropped_stats', 'dropped_stats')
557 def __init__(self, api=None):
558 super(ClassQueueFilter, self).__init__(api)
560 self.module = "classqueue.py"
562 class ToSQueueFilter(TunFilter):
563 def __init__(self, api=None):
564 super(ToSQueueFilter, self).__init__(api)
566 self.module = "tosqueue.py"