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 = ( ''.join(map(chr, [
176 for r in (random.SystemRandom(),) ])
177 ).encode("base64").strip() )
181 return "%s<ip:%s/%s %s%s%s>" % (
182 self.__class__.__name__,
183 self.address, self.netprefix,
184 " up" if self.up else " down",
185 " snat" if self.snat else "",
186 (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
193 if self.peer_proto_impl:
194 return self.peer_proto_impl.if_name
196 def routes_here(self, route):
198 Returns True if the route should be attached to this interface
199 (ie, it references a gateway in this interface's network segment)
201 if self.address and self.netprefix:
202 addr, prefix = self.address, self.netprefix
203 pointopoint = self.pointopoint
204 if not pointopoint and self.peer_iface:
205 pointopoint = self.peer_iface.address
210 dest, destprefix, nexthop, metric = route
212 myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
213 gwIp = ipaddr.IPNetwork(nexthop)
216 peerIp = ipaddr.IPNetwork(pointopoint)
225 def add_address(self, address, netprefix, broadcast):
226 if (self.address or self.netprefix or self.netmask) is not None:
227 raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
229 raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
231 self.address = address
232 self.netprefix = netprefix
233 self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
237 raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
238 if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
239 raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
240 if not self.address or not self.netprefix or not self.netmask:
241 raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
242 if self.filter_module and self.peer_proto not in ('udp','tcp',None):
243 raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
244 if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
245 raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
247 def _impl_instance(self, home_path):
248 impl = self._PROTO_MAP[self.peer_proto](
249 self, self.peer_iface, home_path, self.tun_key)
250 impl.port = self.tun_port
251 impl.cross_slice = not self.peer_iface or isinstance(self.peer_iface, _CrossIface)
256 self.peer_proto_impl = self._impl_instance(
258 self.peer_proto_impl.recover()
260 self._delay_recover = True
262 def prepare(self, home_path):
263 if not self.peer_iface and (self.peer_proto and self.peer_addr):
265 self.peer_iface = _CrossIface(
271 if not self.peer_proto_impl:
272 self.peer_proto_impl = self._impl_instance(home_path)
273 if self._delay_recover:
274 self.peer_proto_impl.recover()
277 if self.peer_proto_impl:
278 self.peer_proto_impl.launch()
281 if self.peer_proto_impl:
282 self.peer_proto_impl.shutdown()
285 if self.peer_proto_impl:
286 self.peer_proto_impl.destroy()
287 self.peer_proto_impl = None
290 if self.peer_proto_impl:
291 self.peer_proto_impl.wait()
293 def sync_trace(self, local_dir, whichtrace, tracemap = None):
294 if self.peer_proto_impl:
295 return self.peer_proto_impl.sync_trace(local_dir, whichtrace,
300 def remote_trace_path(self, whichtrace, tracemap = None):
301 if self.peer_proto_impl:
302 return self.peer_proto_impl.remote_trace_path(whichtrace, tracemap)
306 def remote_trace_name(self, whichtrace):
309 class TapIface(TunIface):
310 _PROTO_MAP = tunproto.TAP_PROTO_MAP
313 # Yep, it does nothing - yet
314 class Internet(object):
315 def __init__(self, api=None):
317 api = plcapi.PLCAPI()
320 class NetPipe(object):
321 def __init__(self, api=None):
323 api = plcapi.PLCAPI()
339 # These get initialized when the pipe is connected to its node
341 self.configured = False
345 raise RuntimeError, "Undefined NetPipe mode"
346 if not self.portList:
347 raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
348 if not (self.plrIn or self.bwIn or self.delayIn):
349 raise RuntimeError, "Undefined NetPipe inbound characteristics"
350 if not (self.plrOut or self.bwOut or self.delayOut):
351 raise RuntimeError, "Undefined NetPipe outbound characteristics"
353 raise RuntimeError, "Unconnected NetPipe"
355 def _add_pipedef(self, bw, plr, delay, options):
357 options.extend(("delay","%dms" % (delay,)))
359 options.extend(("bw","%.8fMbit/s" % (bw,)))
361 options.extend(("plr","%.8f" % (plr,)))
363 def _get_ruledef(self):
366 "@" if self.addrList else "",
371 if self.bwIn or self.plrIn or self.delayIn:
373 self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
374 if self.bwOut or self.plrOut or self.delayOut:
375 options.append("OUT")
376 self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
377 options = ' '.join(options)
379 return (scope,options)
382 # Rules are safe on their nodes
383 self.configured = True
387 scope, options = self._get_ruledef()
388 command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
390 (out,err),proc = server.popen_ssh_command(
392 host = self.node.hostname,
394 user = self.node.slicename,
396 ident_key = self.node.ident_path,
397 server_key = self.node.server_key
401 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
403 # we have to clean up afterwards
404 self.configured = True
409 scope, options = self._get_ruledef()
410 command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
412 (out,err),proc = server.popen_ssh_command(
414 host = self.node.hostname,
416 user = self.node.slicename,
418 ident_key = self.node.ident_path,
419 server_key = self.node.server_key
423 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
428 scope, options = self._get_ruledef()
429 command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
431 (out,err),proc = server.popen_ssh_command(
433 host = self.node.hostname,
435 user = self.node.slicename,
437 ident_key = self.node.ident_path,
438 server_key = self.node.server_key
442 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
444 self.configured = False
446 def sync_trace(self, local_dir, whichtrace):
447 if whichtrace != 'netpipeStats':
448 raise ValueError, "Unsupported trace %s" % (whichtrace,)
450 local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
452 # create parent local folders
453 proc = subprocess.Popen(
454 ["mkdir", "-p", os.path.dirname(local_path)],
455 stdout = open("/dev/null","w"),
456 stdin = open("/dev/null","r"))
459 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
461 (out,err),proc = server.popen_ssh_command(
462 "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
463 host = self.node.hostname,
465 user = self.node.slicename,
467 ident_key = self.node.ident_path,
468 server_key = self.node.server_key
472 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
474 # dump results to file
475 f = open(local_path, "wb")
482 class TunFilter(object):
484 # tracename : (remotename, localname)
487 def __init__(self, api=None):
489 api = plcapi.PLCAPI()
496 # These get initialised when the filter is connected
497 self.peer_guid = None
498 self.peer_proto = None
499 self.iface_guid = None
503 def _get(what, self):
508 return getattr(wref, what)
512 def _set(what, self, val):
517 setattr(wref, what, val)
519 tun_proto = property(
520 functools.partial(_get, 'tun_proto'),
521 functools.partial(_set, 'tun_proto') )
523 functools.partial(_get, 'tun_addr'),
524 functools.partial(_set, 'tun_addr') )
526 functools.partial(_get, 'tun_port'),
527 functools.partial(_set, 'tun_port') )
529 functools.partial(_get, 'tun_key'),
530 functools.partial(_set, 'tun_key') )
531 tun_cipher = property(
532 functools.partial(_get, 'tun_cipher'),
533 functools.partial(_set, 'tun_cipher') )
538 def remote_trace_path(self, whichtrace):
540 if iface is not None:
541 return iface.remote_trace_path(whichtrace, self._TRACEMAP)
544 def remote_trace_name(self, whichtrace):
546 if iface is not None:
547 return iface.remote_trace_name(whichtrace, self._TRACEMAP)
550 def sync_trace(self, local_dir, whichtrace):
552 if iface is not None:
553 return iface.sync_trace(local_dir, whichtrace, self._TRACEMAP)
556 class ClassQueueFilter(TunFilter):
558 # tracename : (remotename, localname)
559 'dropped_stats' : ('dropped_stats', 'dropped_stats')
562 def __init__(self, api=None):
563 super(ClassQueueFilter, self).__init__(api)
565 self.module = "classqueue.py"
567 class ToSQueueFilter(TunFilter):
568 def __init__(self, api=None):
569 super(ToSQueueFilter, self).__init__(api)
571 self.module = "tosqueue.py"